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
<file_sep>package entity; /** * AdminTable entity. @author MyEclipse Persistence Tools */ public class AdminTable implements java.io.Serializable { // Fields private Integer mid; private String password; // Constructors /** default constructor */ public AdminTable() { } /** minimal constructor */ public AdminTable(Integer mid) { this.mid = mid; } /** full constructor */ public AdminTable(Integer mid, String password) { this.mid = mid; this.password = <PASSWORD>; } // Property accessors public Integer getMid() { return this.mid; } public void setMid(Integer mid) { this.mid = mid; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = <PASSWORD>; } }<file_sep>package Action; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Random; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.hibernate.Query; import org.hibernate.Session; import tool.QuestionTableDAO; import tool.StudentDAO; import tool.TestArrangeTableDAO; import tool.getTool; import com.opensymphony.xwork2.ActionSupport; import entity.QuestionTable; import entity.Student; import entity.TestArrangeTable; import tool.*; public class chooseTestTypeAction extends ActionSupport{ public String testTypeOption() { HttpServletRequest request = ServletActionContext.getRequest(); String examType = request.getParameter("examType"); QuestionTableDAO QD = new QuestionTableDAO(); if(examType.equals("testYourself")) //如果是自我测试,就从题库随机选取10道题 { List list = QD.findAll(); int Totalnum=list.size(); if(Totalnum<10) {getTool.senderrormessage("对不起,题库中暂时没有足够的题目","http://localhost:8080/ontest1/StudentMainPage.jsp");return null;} else{ Random rand = new Random(); List getRandQuestion = new ArrayList(); int i = 0; while(i<10){ //随机选取10道题 int getRandNum = rand.nextInt(Totalnum); Object Randomquestion = list.get(getRandNum); getRandQuestion.add(Randomquestion); list.remove(getRandNum); Totalnum= Totalnum-1; i++; } request.setAttribute("list", getRandQuestion); request.getSession().setAttribute("examtype", "testbyself"); request.setAttribute("endtime", "0:0:0"); return "begintest"; } } else //班级统考的题目是统一的 { Student s = (Student)request.getSession().getAttribute("student"); String Class_ = s.getClass_(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式 HH:mm:ss String Today=df.format(new Date()); // new Date()为获取当前系统时间 Session sess = getTool.getSessions(); sess.beginTransaction(); Query query = sess.createQuery("from TestArrangeTable where class_ ='"+Class_+"'"); List<TestArrangeTable> AllTest = query.list(); for(TestArrangeTable t : AllTest) { String datetime = t.getBeginTime(); String[] splitArray= datetime.split("T"); String beginDate = splitArray[0]; String beginTime = splitArray[1]; if(Today.equals(beginDate)==false) continue; int limit = t.getLimitTime(); //获取该学生所在班级的所有测试,与今天的日期相比比较,且当前时间在考试时间范围内 String[] temp = beginTime.split(":"); int hour = Integer.parseInt(temp[0]); int minute = Integer.parseInt(temp[1]); int second = Integer.parseInt(temp[2]); if(minute+limit<60) minute=minute+limit; // 计算考试结束时间 else{ hour = hour+(minute+limit)/60; minute=(minute+limit)%60; } String endTime = hour+":"+minute+":"+second; if(getTool.isInDate(System.currentTimeMillis(), beginTime, endTime)) { //在考试时间范围的话就获取试卷题目 QuestionTableDAO qd =new QuestionTableDAO(); List list = new ArrayList(); String[] qidVesse = t.getQidVess().split(","); for(String str : qidVesse) { int id = Integer.parseInt(str); list.add(qd.findById(id)); } request.setAttribute("list", list); request.setAttribute("endtime", endTime); request.getSession().setAttribute("examtype", "testunit"); request.getSession().setAttribute("testarrangetable", t); return "begintest"; } } getTool.senderrormessage("'亲,你当前没有考试哦!","http://localhost:8080/ontest1/StudentMainPage.jsp"); //否则就拒绝进入考试 return null; } } } <file_sep>package Action; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import entity.AdminTable; import entity.Student; import entity.Teacher; import tool.AdminTableDAO; import tool.StudentDAO; import tool.TeacherDAO; import tool.getTool; public class LoginAction extends ActionSupport{ int id; private String password; private String role; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String Nativate() { HttpServletResponse response = ServletActionContext.getResponse(); if(role.equals("student")) { StudentDAO sd=new StudentDAO(); Student s = sd.findById(id); if(s != null && s.getPassword().equals(password)) { HttpServletRequest req = ServletActionContext.getRequest(); req.getSession().setAttribute("student", s); try { response.sendRedirect("http://localhost:8080/ontest1/StudentMainPage.jsp"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else getTool.senderrormessage("您的id或者密码错误", "http://localhost:8080/ontest1/login.jsp"); } else if(role.equals("teacher")) { TeacherDAO td=new TeacherDAO(); Teacher t = td.findById(id); if(t !=null && t.getPassword().equals(password)) { HttpServletRequest req = ServletActionContext.getRequest(); req.getSession().setAttribute("teacher", t); try { response.sendRedirect("http://localhost:8080/ontest1/TeacherMainPage.jsp"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else getTool.senderrormessage("您的id或者密码错误", "http://localhost:8080/ontest1/login.jsp"); } else if(role.equals("admin")) { AdminTableDAO ad = new AdminTableDAO(); AdminTable a = ad.findById(id); if(a !=null && a.getPassword().equals(password)) { HttpServletRequest req = ServletActionContext.getRequest(); req.getSession().setAttribute("admin", a); try { response.sendRedirect("http://localhost:8080/ontest1/admin.jsp"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else getTool.senderrormessage("您的id或者密码错误", "http://localhost:8080/ontest1/login.jsp"); } return null; } } <file_sep>package tool; import java.util.List; import java.util.Set; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.Transaction; import org.hibernate.criterion.Example; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import entity.TestArrangeTable; /** * A data access object (DAO) providing persistence and search support for * TestArrangeTable entities. Transaction control of the save(), update() and * delete() operations can directly support Spring container-managed * transactions or they can be augmented to handle user-managed Spring * transactions. Each of these methods provides additional information for how * to configure it for the desired type of transaction control. * * @see entity.TestArrangeTable * @author MyEclipse Persistence Tools */ public class TestArrangeTableDAO extends BaseHibernateDAO { private static final Logger log = LoggerFactory .getLogger(TestArrangeTableDAO.class); // property constants public static final String QID_VESS = "qidVess"; public static final String BEGIN_TIME = "beginTime"; public static final String LIMIT_TIME = "limitTime"; public static final String CLASS_ = "class_"; public void save(TestArrangeTable transientInstance) { log.debug("saving TestArrangeTable instance"); Transaction tran = getSession().beginTransaction(); try { getSession().saveOrUpdate(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } tran.commit(); getSession().flush(); getSession().close(); } public void delete(TestArrangeTable persistentInstance) { log.debug("deleting TestArrangeTable instance"); Transaction tran = getSession().beginTransaction(); try { getSession().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } tran.commit(); getSession().flush(); getSession().close(); } public TestArrangeTable findById(java.lang.Integer id) { log.debug("getting TestArrangeTable instance with id: " + id); try { TestArrangeTable instance = (TestArrangeTable) getSession().get( "entity.TestArrangeTable", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(TestArrangeTable instance) { log.debug("finding TestArrangeTable instance by example"); try { List results = getSession().createCriteria( "entity.TestArrangeTable").add(Example.create(instance)) .list(); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding TestArrangeTable instance with property: " + propertyName + ", value: " + value); try { String queryString = "from TestArrangeTable as model where model." + propertyName + "= ?"; Query queryObject = getSession().createQuery(queryString); queryObject.setParameter(0, value); return queryObject.list(); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByQidVess(Object qidVess) { return findByProperty(QID_VESS, qidVess); } public List findByBeginTime(Object beginTime) { return findByProperty(BEGIN_TIME, beginTime); } public List findByLimitTime(Object limitTime) { return findByProperty(LIMIT_TIME, limitTime); } public List findByClass_(Object class_) { return findByProperty(CLASS_, class_); } public List findAll() { log.debug("finding all TestArrangeTable instances"); try { String queryString = "from TestArrangeTable"; Query queryObject = getSession().createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public TestArrangeTable merge(TestArrangeTable detachedInstance) { log.debug("merging TestArrangeTable instance"); try { TestArrangeTable result = (TestArrangeTable) getSession().merge( detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(TestArrangeTable instance) { log.debug("attaching dirty TestArrangeTable instance"); try { getSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(TestArrangeTable instance) { log.debug("attaching clean TestArrangeTable instance"); try { getSession().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } }<file_sep>package tool; import java.util.List; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.Transaction; import org.hibernate.criterion.Example; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import entity.QuestionTable; /** * A data access object (DAO) providing persistence and search support for * QuestionTable entities. Transaction control of the save(), update() and * delete() operations can directly support Spring container-managed * transactions or they can be augmented to handle user-managed Spring * transactions. Each of these methods provides additional information for how * to configure it for the desired type of transaction control. * * @see entity.QuestionTable * @author MyEclipse Persistence Tools */ public class QuestionTableDAO extends BaseHibernateDAO { private static final Logger log = LoggerFactory .getLogger(QuestionTableDAO.class); // property constants public static final String QUEST_TEXT = "questText"; public static final String ANSWER = "answer"; public static final String MARK = "mark"; public static final String A = "a"; public static final String B = "b"; public static final String C = "c"; public static final String D = "d"; public void save(QuestionTable transientInstance) { log.debug("saving QuestionTable instance"); Transaction tran = getSession().beginTransaction(); try { getSession().saveOrUpdate(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } tran.commit(); getSession().flush(); getSession().close(); } public void delete(QuestionTable persistentInstance) { log.debug("deleting QuestionTable instance"); Transaction tran = getSession().beginTransaction(); try { getSession().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } tran.commit(); getSession().flush(); getSession().close(); } public QuestionTable findById(java.lang.Integer id) { log.debug("getting QuestionTable instance with id: " + id); try { QuestionTable instance = (QuestionTable) getSession().get( "entity.QuestionTable", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(QuestionTable instance) { log.debug("finding QuestionTable instance by example"); try { List results = getSession().createCriteria("entity.QuestionTable") .add(Example.create(instance)).list(); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding QuestionTable instance with property: " + propertyName + ", value: " + value); try { String queryString = "from QuestionTable as model where model." + propertyName + "= ?"; Query queryObject = getSession().createQuery(queryString); queryObject.setParameter(0, value); return queryObject.list(); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByQuestText(Object questText) { return findByProperty(QUEST_TEXT, questText); } public List findByAnswer(Object answer) { return findByProperty(ANSWER, answer); } public List findByMark(Object mark) { return findByProperty(MARK, mark); } public List findByA(Object a) { return findByProperty(A, a); } public List findByB(Object b) { return findByProperty(B, b); } public List findByC(Object c) { return findByProperty(C, c); } public List findByD(Object d) { return findByProperty(D, d); } public List findAll() { log.debug("finding all QuestionTable instances"); try { String queryString = "from QuestionTable"; Query queryObject = getSession().createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public QuestionTable merge(QuestionTable detachedInstance) { log.debug("merging QuestionTable instance"); try { QuestionTable result = (QuestionTable) getSession().merge( detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(QuestionTable instance) { log.debug("attaching dirty QuestionTable instance"); try { getSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(QuestionTable instance) { log.debug("attaching clean QuestionTable instance"); try { getSession().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } }<file_sep>package Action; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import tool.QuestionTableDAO; import tool.ScoreTableDAO; import tool.StudentDAO; import tool.TestArrangeTableDAO; import com.opensymphony.xwork2.ActionSupport; import entity.TestArrangeTable; import entity.QuestionTable; import entity.ScoreTable; import entity.Student; public class ScoreManager extends ActionSupport{ private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getEid() { return Eid; } public void setEid(int eid) { Eid = eid; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public int getSid() { return Sid; } public void setSid(int sid) { Sid = sid; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } private int Eid; private int score; private int Sid; private String method; public String execute(){ ScoreTableDAO sd=new ScoreTableDAO(); if(method.equals("update")){ ScoreTable scoreTable = sd.findById(id); TestArrangeTableDAO pd=new TestArrangeTableDAO(); TestArrangeTable paperTable = pd.findById(Eid); scoreTable.setTestArrangeTable(paperTable); scoreTable.setScore(score); StudentDAO studao = new StudentDAO(); Student s = studao.findById(Sid); scoreTable.setStudent(s); sd.save(scoreTable); } else if(method.equals("add")) { ScoreTable scoreTable = new ScoreTable(); TestArrangeTableDAO pd=new TestArrangeTableDAO(); TestArrangeTable testArrange = pd.findById(Eid); scoreTable.setTestArrangeTable(testArrange); scoreTable.setScore(score); StudentDAO studao = new StudentDAO(); Student s = studao.findById(Sid); scoreTable.setStudent(s); System.out.println(Eid); System.out.println(score); System.out.println(Sid); sd.save(scoreTable); } else if(method.equals("delete")) {ScoreTable s = sd.findById(id);sd.delete(s);} HttpServletResponse response = ServletActionContext.getResponse(); try { response.sendRedirect("http://localhost:8080/ontest1/admin.jsp"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
d8112307895372e96c79373b28f5f829320eed93
[ "Java" ]
6
Java
DKHeZhiBin/-
f8c7ed0d96131e175105b293c1cfbf5721e7a9a4
7969129f84c8320a96c1d5541fd06c3b96b8481f
refs/heads/master
<file_sep>// show menu function showMenu() { document.getElementById("menu-hamburger").classList.toggle("show"); } window.onclick = function(event) { if(!event.target.matches('.menu-mobile')) { var dropdowns = document.getElementsByClassName("hidden-menu"); var i; for (i =0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } // fim show menu // inicio sticky menu var navbar = document.getElementById("sticky-menu"); function stickyMenu() { var sticky = navbar.offsetTop + 600; if (window.pageYOffset > sticky) { navbar.classList.add("sticky"); } else { navbar.classList.remove("sticky"); } } // fim sticky menu // inicio button scroll up var button = document.getElementById("scroll-up"); function scrollUp() { if (document.documentElement.scrollTop > 20) { button.style.display = "flex"; } else { button.style.display = "none"; } } function clickTop() { document.documentElement.scrollTop = 0; } // fim button scroll up // chama as 2 funções que utilizam window.onscroll window.onscroll = function() { scrollUp(); stickyMenu(); } // inicio lightbox function IdeficaModalLightBox () { var i; for (i =0; i < 3; i++) { var image = document.getElementsByClassName("content-slider")[i]; var modal = document.getElementsByClassName("modal")[i]; var modalImage = document.getElementsByClassName("modal-content")[i]; var close = document.getElementsByClassName("close")[i]; lightbox(image, modal, modalImage, close); } } IdeficaModalLightBox (); function lightbox (image, modal, modalImage, close) { image.onclick = function() { modal.style.display = "block"; button.style.display = "none"; modalImage.src = this.src; navbar.classList.remove("sticky"); } close.onclick = function() { modal.style.display = "none"; button.style.display = "flex"; } } // fim lightbox // start slideshow cont = 0; function buttonSlide(n) { cont += n; var slideContent = document.getElementsByClassName("slideshow"); if (cont == 3 || cont == -3 ){ cont = 0; } if (cont == 0) { slideContent.item(0).innerHTML = '<img src="image/work-0.png" alt="work-0" class="content-slider content-slide0"> <div id="workModal" class="modal"> <a><span class="close">&times;</span></a> <img class="modal-content" id="img"> </div>'; slideContent.item(1).innerHTML = '<img src="image/work-1.png" alt="work-1" class="content-slider content-slide1"> <div id="workModal" class="modal"> <a><span class="close">&times;</span></a> <img class="modal-content" id="img"> </div>'; slideContent.item(2).innerHTML = '<img src="image/work-2.png" alt="work-2" class="content-slider content-slide2"> <div id="workModal" class="modal"> <a><span class="close">&times;</span></a> <img class="modal-content" id="img"> </div>'; // slideContent.item(1).src = "../image/work-1.png"; //null // slideContent.item(1).src = img; //error // img.src = 'work-1.png'; //error } if (cont == 1 || cont == -2){ slideContent.item(0).innerHTML = '<img src="image/work-2.png" alt="work-2" class="content-slider content-slide0"> <div id="workModal" class="modal"> <a><span class="close">&times;</span></a> <img class="modal-content" id="img"> </div>'; slideContent.item(1).innerHTML = '<img src="image/work-0.png" alt="work-0" class="content-slider content-slide1"> <div id="workModal" class="modal"> <a><span class="close">&times;</span></a> <img class="modal-content" id="img"> </div>'; slideContent.item(2).innerHTML = '<img src="image/work-1.png" alt="work-1" class="content-slider content-slide2"> <div id="workModal" class="modal"> <a><span class="close">&times;</span></a> <img class="modal-content" id="img"> </div>'; } if (cont == 2 || cont == -1){ slideContent.item(0).innerHTML = '<img src="image/work-1.png" alt="work-0" class="content-slider content-slide0"> <div id="workModal" class="modal"> <a><span class="close">&times;</span></a> <img class="modal-content" id="img"> </div>'; slideContent.item(1).innerHTML = '<img src="image/work-2.png" alt="work-2" class="content-slider content-slide1"> <div id="workModal" class="modal"> <a><span class="close">&times;</span></a> <img class="modal-content" id="img"> </div>'; slideContent.item(2).innerHTML = '<img src="image/work-0.png" alt="work-1" class="content-slider content-slide2"> <div id="workModal" class="modal"> <a><span class="close">&times;</span></a> <img class="modal-content" id="img"> </div>'; } IdeficaModalLightBox (); } // fim slideShow
4019ff2694c14ea3138f2b4db80b847896420366
[ "JavaScript" ]
1
JavaScript
eriklm42/LandingPage-mobile
97bacada0ef5cad59fc7e946f57a1823463c0f3d
34958c1f903b52ff02cf764ca74659ed339a0de6
refs/heads/main
<file_sep>import Voice from "./Voice"; export default class Shouter { Id: string; name: string; location: string; email: string; phone: string; constructor( Id: string, name: string, location: string, email: string, phone: string ) { this.Id = Id; this.name = name; this.location = location; this.email = email; this.phone = phone; } shout(message: string): Voice { return new Voice(Math.round(Math.random() * 999).toString(), this, message); } } <file_sep>import Shouter from "./Shouter"; import Voice from "./Voice"; export default interface State { me: Shouter; myVoices: Array<Voice>; voices: Array<Voice>; isLoggedIn: boolean; } const herve: Shouter = new Shouter( "1234", "herves", "LS16 5RQ, Leeds", "<EMAIL>", "078575853" ); const jeanyves: Shouter = new Shouter( "4334", "jumbo", "LS16 5RQ, Leeds", "<EMAIL>", "078575853" ); const andre: Shouter = new Shouter( "6723", "andre", "LS16 5RQ, Leeds", "<EMAIL>", "078575853" ); export const defaultState: State = { me: herve, myVoices: [], voices: [ new Voice("3824", herve, "iphone 10X, color black, 250GB, $500"), new Voice("3524", jeanyves, "car BMW, color red, $15.000, year: 2011"), new Voice("3924", andre, "Nike air, color black, 2018, $500"), ], isLoggedIn: false, }; <file_sep>import { useHistory } from "react-router-dom"; import useIsLoggedIn from "./useIsLoggedIn"; const useAuthRequired = () => { const isLoggedIn = useIsLoggedIn(); const history = useHistory(); if (!isLoggedIn) { history.push("/login"); } }; export default useAuthRequired; <file_sep>import { useContext } from "react"; import { useHistory } from "react-router-dom"; import context from "../context"; const useLogout = () => { const ctx = useContext(context); const history = useHistory(); return () => { if (ctx.setState) { history.push("/"); ctx.setState({ ...ctx.state, isLoggedIn: false }); console.log("success logging out"); } }; }; export default useLogout; <file_sep>import { useContext } from "react"; import context from "../context"; import Voice from "../state/Voice"; const useMyvoices = (): Array<Voice> => { return useContext(context).state.myVoices; }; export default useMyvoices; <file_sep>import { createContext, Dispatch, SetStateAction } from "react"; import State, { defaultState } from "../state"; interface contextValue { state: State; setState?: Dispatch<SetStateAction<State>>; } const value: contextValue = { state: defaultState, }; const context = createContext(value); export default context; <file_sep>import Shouter from "./Shouter"; export default class Voice { Id: string; shouter: Shouter; message: string; haveBeenHeard: boolean = false; constructor(Id: string, shouter: Shouter, message: string) { this.Id = Id; this.shouter = shouter; this.message = message; } contactShouterViaEmail( name: string, email: string, message: string ): boolean { alert(`${name} contacted shouter ${this.shouter.name} via Email ...`); return true; } markAsHeard(): boolean { this.haveBeenHeard = true; return true; } } export function hearParticularVoice( voices: Array<Voice>, message: string ): Array<Voice> { return voices.filter((voice) => voice.message.includes(message)); } export function myVoices(shouter: Shouter, voices: Array<Voice>): Array<Voice> { return voices.filter((voice) => voice.shouter.Id === shouter.Id); } <file_sep>import React, { useEffect } from "react"; const useWindowScrollY = (cb: (scrollY: number) => void) => { useEffect(() => { document.addEventListener("scroll", () => { const y = window.scrollY; cb(y); }); }); }; export default useWindowScrollY; <file_sep>import { useContext } from "react"; import context from "../context"; const useIsLoggedIn = (): boolean => { const ctx = useContext(context); return ctx.state.isLoggedIn; }; export default useIsLoggedIn; <file_sep>import { useContext } from "react"; import context from "../context"; import Voice from "../state/Voice"; const useVoices = (): Array<Voice> => { const ctx = useContext(context); return ctx.state.voices; }; export default useVoices; <file_sep>import { useContext } from "react"; import context from "../context"; import Voice from "../state/Voice"; import useVoices from "./useVoices"; const useUpdateVoice = () => { const voices = useVoices(); const ctx = useContext(context); return (updatedVoice: Voice) => { const filteredVoices = voices.filter( (voice) => voice.Id !== updatedVoice.Id ); filteredVoices.push(updatedVoice); if (ctx.setState) ctx.setState({ ...ctx.state, voices: filteredVoices }); }; }; export default useUpdateVoice; <file_sep>import React, { useContext } from "react"; import context from "../context"; import Voice from "../state/Voice"; const useVoice = (voiceId: string): Voice | undefined => { const ctx = useContext(context); const voiceData = ctx.state.voices.find((voice) => voice.Id === voiceId); return voiceData; }; export default useVoice;
6498e449fdc1d48270cd8fb0d65f12f974e48206
[ "TypeScript" ]
12
TypeScript
toundaherve/shout
9412288f223f0664c7527b5e81811fa3eb8f59f7
d89397bb2c9e8b359f6140574e58610b2153bb60
refs/heads/master
<file_sep># UnityCustom3rdPartyToolsLocations Plugin to customize installation paths for 3rd party tools like blender ## Why? Unity has the option to directly import models from 3rd party tools like Blender. This allows you to place your *.blend files directly into the Assets folder and Unity will happily import those as models *as long as you have Blender installed*. This is a really nice feature but you have to manage your Blender installation separately to your Unity installation. This becomes a real hassle when working on multiple projects with different Blender requirements, like requiring a specific version or even a customized version. So this plugin is built to allow you to customize the paths to your 3rd party tools like Blender for specific Unity projects. Any Unity project can now reference their very own Blender installation. *(This project is really heavily influenced by the specifics of Blender. It currently has no support for other tools but that can be easily added)* ## How? In order to customize the location of blender.exe for a specific project: - Download the appropriate release archive for your platform - Unzip the contents (DLL + meta) into your Asset folder - Close your Unity editor - Create a text file `blender-config.txt` into your unity project folder (next to the Assets, Library, ProjectSettings, .. folders) - Open the text file with a text editor and put the path to your blender.exe into it. It can be relative to the project directory, like `..\blender-2.79b-windows64\blender.exe` - save it - Open your Unity project - Add `.blend` files to it! ## Technicalities In order to provide Unity with the path to the custom executable, the plugin hooks into the `FindExecutableW()` function. Unity uses this to find the program responsible for opening specific files, like .blend files. By hijacking the invocation the plugin can just return a custom executable locations when it sees fit, like the custom blender executable path when Unity wants to open a .blend file. ## How to build - Clone the repo - Open `UnityCustom3rdPartyToolsLocations.sln` - Build the project for x64 Release - Copy the DLL and meta from the folder `PackageTemplate` into your Unity project ## License This project is licensed under the [MIT](LICENSE) license. ## Acknowledgements This project uses the <https://github.com/microsoft/Detours> library for hooking API methods.<file_sep>// dllmain.cpp : Definiert den Einstiegspunkt für die DLL-Anwendung. #include "pch.h" #include <stdio.h> #include <shellapi.h> #include <locale> #include <codecvt> #include <string> #include <fstream> // Target pointer for the uninstrumented FindExecutable API. // static HINSTANCE(WINAPI* TrueFindExecutableW)(_In_ LPCWSTR lpFile, _In_opt_ LPCWSTR lpDirectory, _Out_writes_(MAX_PATH) LPWSTR lpResult) = FindExecutableW; static bool hasCustomBlender = false; static std::wstring customBlenderExecutablePath; // Detour function that replaces the FindExecutable API. // HINSTANCE WINAPI HookedFindExecutableW(_In_ LPCWSTR lpFile, _In_opt_ LPCWSTR lpDirectory, _Out_writes_(MAX_PATH) LPWSTR lpResult) { if (hasCustomBlender) { LPCWSTR extension = wcsrchr(lpFile, L'.'); // Check if it's a blendfile, and apparently unity may add quotes around the path "just to be sure" I guess if (wcscmp(extension, L".blend") == 0 || wcscmp(extension, L".blend\"") == 0) { wcscpy_s(lpResult, MAX_PATH, customBlenderExecutablePath.c_str()); // Something > 32 return (HINSTANCE)33; } } HINSTANCE result = TrueFindExecutableW(lpFile, lpDirectory, lpResult); return result; } void LoadConfig() { std::ifstream config; config.open("blender-config.txt"); if (config.is_open()) { std::string customBlenderExecutablePathUtf8; std::getline(config, customBlenderExecutablePathUtf8); std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; customBlenderExecutablePath = converter.from_bytes(customBlenderExecutablePathUtf8); config.close(); hasCustomBlender = true; } else { hasCustomBlender = false; } } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { LoadConfig(); DetourRestoreAfterWith(); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach(&(PVOID&)TrueFindExecutableW, HookedFindExecutableW); DetourTransactionCommit(); }break; case DLL_THREAD_ATTACH:break; case DLL_THREAD_DETACH:break; case DLL_PROCESS_DETACH: { DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourDetach(&(PVOID&)TrueFindExecutableW, HookedFindExecutableW); DetourTransactionCommit(); } break; } return TRUE; }
661cd31e2835e514e75df65d861aa2e02a63c446
[ "Markdown", "C++" ]
2
Markdown
jorik041/UnityCustom3rdPartyToolsLocations
840904a92c1f0029fd00b12424af2ab9ee793549
1b5ca19c7b48d282fab8c6617df3c8c556b2e6f4
refs/heads/master
<file_sep>""" Django settings for NewsUp project. Generated by 'django-admin startproject' using Django 1.8.1. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<KEY>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'newsApp', 'django_crontab', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'newsApp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'NewsUp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'news_schema', # Or path to database file if using sqlite3. 'USER': 'root', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '127.0.0.1', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '3306', # Set to empty string for default. Not used with sqlite3. } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'django.utils.log.NullHandler', }, 'console':{ 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'formatter': 'verbose' }, 'logfile': { 'level': 'INFO', 'class': 'logging.handlers.WatchedFileHandler', 'filename': 'E:\NewsApp\NewsUp\greenfield.log', 'formatter': 'verbose' }, }, 'loggers': { 'django': { 'handlers': ['logfile','console'], 'propagate': True, 'level': 'ERROR', }, 'django.request': { 'handlers': ['mail_admins','logfile'], 'level': 'ERROR', 'propagate': False, } } } CRONJOBS = [ ('30 6,9,11,15,17,20 * * *', 'NewsUp.cron.my_scheduled_job_Kimono_Hourly'), ('30 5,13,16 * * *', 'NewsUp.cron.my_scheduled_job_Kimono_Daily'), ('0 6 * * *', 'NewsUp.cron.my_schedule_job_video_daily'), ('30 8 * * *', 'NewsUp.cron.my_scheduled_job_TopN'), ('58 9 * * *', 'NewsUp.cron.my_scheduled_job_delete_TopN'), ('0 10 * * *', 'NewsUp.cron.my_scheduled_job_Top_News'), ('0 12 * * *', 'NewsUp.cron.my_scheduled_job_Top_News'), ('0 14 * * *', 'NewsUp.cron.my_scheduled_job_hourly'), ('0 16 * * *', 'NewsUp.cron.my_scheduled_job_Top_News'), ('0 17 * * *', 'NewsUp.cron.my_scheduled_job_hourly'), ('58 16 * * *', 'NewsUp.cron.my_scheduled_job_TopN'), ('0 18 * * *', 'NewsUp.cron.my_scheduled_job_Top_News'), ('30 21 * * *', 'NewsUp.cron.my_scheduled_job_Top_News'), ('28 21 * * *', 'NewsUp.cron.my_scheduled_job_delete_TopN'), ('58 23 * * *', 'NewsUp.cron.my_scheduled_job_delete_article') ]<file_sep># -*- coding: utf-8 -*- from django.http import HttpResponse from django.shortcuts import render_to_response from Utils import * from youtube import * from userConstants import * from django.template.context import RequestContext from simplejson import dumps from models import * import logging from django.utils.datastructures import MultiValueDictKeyError from loadNews import * from django.core.exceptions import ObjectDoesNotExist import urllib # Python URL functions import csv from xlrd import open_workbook logger = logging.getLogger('django') def insertLanguageCategory(request): #insertWithoutClustering(HINDI,FARIDABAD,DELTA_HOURS_TWENTY_FOUR) #clusterOnLanguageCategory(ENGLISH,TOP_STORIES,DELTA_HOURS_TWELVE) '''clusterOnLanguageCategory(HINDI,TOP_STORIES,DELTA_HOURS_TWELVE) clusterOnLanguageCategory(HINDI,WORLD,DELTA_HOURS_TWENTY_FOUR) insertWithoutClustering(HINDI,OPINION,DELTA_HOURS_TWENTY_FOUR) insertWithoutClustering(HINDI,HEALTH,DELTA_HOURS_TWENTY_FOUR) insertWithoutClustering(HINDI,LIFESTYLE,DELTA_HOURS_TWENTY_FOUR) insertWithoutClustering(HINDI,ENTERTAINMENT,DELTA_HOURS_TWENTY_FOUR) clusterOnLanguageCategory(HINDI,TECHNOLOGY,DELTA_HOURS_TWENTY_FOUR) clusterOnLanguageCategory(HINDI,AUTO,DELTA_HOURS_TWENTY_FOUR) clusterOnLanguageCategory(HINDI,POLITICS,DELTA_HOURS_TWENTY_FOUR) insertWithoutClustering(HINDI,ENVIRONMENT,DELTA_HOURS_TWENTY_FOUR) insertWithoutClustering(HINDI,TRAVEL,DELTA_HOURS_TWENTY_FOUR) insertWithoutClustering(HINDI,SCIENCE,DELTA_HOURS_TWENTY_FOUR) clusterOnLanguageCategory(HINDI,BUSINESS,DELTA_HOURS_TWENTY_FOUR) insertWithoutClustering(HINDI,FOOD,DELTA_HOURS_TWENTY_FOUR) clusterOnLanguageCategory(HINDI,FASHION,DELTA_HOURS_TWENTY_FOUR) insertWithoutClustering(HINDI,CRIME,DELTA_HOURS_TWENTY_FOUR)''' createURLFile() return HttpResponse("Hello world") import urllib # Python URL functions import csv from xlrd import open_workbook def createURLFile(): f = open_workbook('E:/ImportIOurls15Mar.xlsx','r') for line in f.sheets(): for row in range(line.nrows): lang = (line.cell(row,0).value) cat = (line.cell(row,1).value) prevURL = (line.cell(row,2).value) source = (line.cell(row,3).value) finalURL = (line.cell(row,7).value) #print row #print '====================================' #sourceObj = News_Source.objects.get(Name=source) #langObj = Language.objects.get(Name=lang) #categoryObj = News_Category.objects.get(Name=cat) try: feedObj = News_Feed.objects.get(URL = prevURL, ) '''for feed in feedObj: feed.URL = finalURL feed.save()''' feedObj.URL = finalURL feedObj.save() except: print row def TopN(request): logger.info("Entered TopN ") deleteLangCategoryTable(MARATHI, TOPN) createTopN(MARATHI) deleteLangCategoryTable(ENGLISH, TOPN) createTopN(ENGLISH) deleteLangCategoryTable(HINDI, TOPN) createTopN(HINDI) logger.info("Exited TopN ") return HttpResponse("Hello world") def insertVideoLanguageCategory(request): getVideoForLanguageCategory(HINDI,TOP_STORIES,DELTA_HOURS_TWELVE) getVideoForLanguageCategory(HINDI,ENTERTAINMENT,DELTA_HOURS_TWELVE) getVideoForLanguageCategory(HINDI,BUSINESS,DELTA_HOURS_TWELVE) '''getVideoForLanguageCategory(ENGLISH,ENTERTAINMENT,DELTA_HOURS_THREE_SIXTY) getVideoForLanguageCategory(ENGLISH,SPORTS,DELTA_HOURS_THREE_SIXTY) getVideoForLanguageCategory(MARATHI,TOP_STORIES,DELTA_HOURS_TWELVE) getVideoForLanguageCategory(MARATHI,ENTERTAINMENT,DELTA_HOURS_THREE_SIXTY) getVideoForLanguageCategory(ENGLISH,WORLD,DELTA_HOURS_TWENTY_FOUR) getVideoForLanguageCategory(ENGLISH,BUSINESS,DELTA_HOURS_TWENTY_FOUR) getVideoForLanguageCategory(ENGLISH,LIFESTYLE,DELTA_HOURS_THREE_SIXTY) getVideoForLanguageCategory(ENGLISH,HEALTH,DELTA_HOURS_THREE_SIXTY) getVideoForLanguageCategory(ENGLISH,FASHION,DELTA_HOURS_THREE_SIXTY) getVideoForLanguageCategory(ENGLISH,TECHNOLOGY,DELTA_HOURS_THREE_SIXTY) getVideoForLanguageCategory(ENGLISH,ENVIRONMENT,DELTA_HOURS_THREE_SIXTY) getVideoForLanguageCategory(ENGLISH,SCIENCE,DELTA_HOURS_THREE_SIXTY) getVideoForLanguageCategory(ENGLISH,FOOD,DELTA_HOURS_THREE_SIXTY)''' #getVideoForLanguageCategory(MARATHI,SPORTS) return HttpResponse("Hello world insertVideoLanguageCategory is done") def sourceNews(request): if request.method == "GET": try: lang=request.GET['language'] except MultiValueDictKeyError: lang=ENGLISH try: category=request.GET['category'] except MultiValueDictKeyError: category=TOP_STORIES sourceId=int(request.GET['sourceid']) newsDictList=loadNewsForSourceNews(lang, category,sourceId) return HttpResponse(dumps(newsDictList,ensure_ascii=True), content_type="application/json") def socialIndicator(request): #socialIndicators(ENGLISH,TOP_STORIES) #socialIndicators(HINDI,TOP_STORIES) createURLFile1() return HttpResponse("Hello world ") def createURLFile1(): url1="https://api.import.io/store/connector/" url2 = '/_query?input=webpage/url:' url3 = '&&_apikey=' f = open_workbook('E:/NewsApp/AllImportFeeds2.xls','r') for line in f.sheets(): for row in range(line.nrows): lang = (line.cell(row,0).value) cat = (line.cell(row,1).value) urlprev = (line.cell(row,2).value) source = (line.cell(row,3).value) connector = (line.cell(row,4).value) apikey = (line.cell(row,5).value) webpageURL = (line.cell(row,7).value) #webpage = urlprev.split('webpage/url:')[1].split('&&_apikey')[0] webpage = urllib.quote_plus(webpageURL) #webpage = urllib.quote_plus(urlprev) print 'lang: ',lang print 'cat: ',cat print 'urlprev: ',urlprev print 'source: ',source print 'connector: ' ,connector print 'apikey : ',apikey print 'webpage: ',webpage finalURL = url1+connector+url2+webpage+url3+apikey print 'finalURL: ',finalURL langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=cat) sourceObj = News_Source.objects.get(Name=source) feedObj = News_Feed.objects.get(Language = langObj, Category = categoryObj, Source = sourceObj, URL = urlprev) #feedObj.URL = finalURL feedObj.URL = webpageURL feedObj.Type = 'RSS 2.0' feedObj.save() '''feedObj = News_Feed(Language = langObj, Category = categoryObj, Source = sourceObj, URL = finalURL) feedObj.save()''' #These methods are API METHODS. The app user will directly call them --------------------------- def loadNewsForHome(request): if request.method == "GET": lang=request.GET['language'] categoryString=request.GET['category'] categoryList=categoryString.split(",") newsDictList=loadNewsForHomeScreen(lang,categoryList) userDict={'newsDictList':newsDictList} return HttpResponse(dumps(userDict,ensure_ascii=True), content_type="application/json") def loadNewsForCategory1(request): lang="English" category="Economy" maxClusterId=0 similarNewsDict={} newsDictList=loadNewsForCategoryScreen(lang, category, maxClusterId) # also get similar news articles for articles in newsDictList: clusterId=articles['Cluster_Id'] similarNewsDict[clusterId]=getSimilarNewsArticles(lang, category, clusterId) userDict={'newsDictList':newsDictList, 'similarNewsDict':similarNewsDict} return render_to_response('category.html', userDict,context_instance=RequestContext(request)) def loadSimilarNews(request): if request.method == "GET": lang=request.GET['language'] category=request.GET['category'] clusterId=request.GET['clusterid'] userDict=getSimilarNewsArticles(lang, category, clusterId) return HttpResponse(dumps(userDict,ensure_ascii=True), content_type="application/json") def loadNewsForCategory(request): if request.method == "GET": try: lang=request.GET['language'] except MultiValueDictKeyError: lang=ENGLISH try: category=request.GET['category'] except MultiValueDictKeyError: category=TOP_STORIES try: maxClusterId=int(request.GET['maxclusterid']) except MultiValueDictKeyError: maxClusterId=0 similarNewsDict={} newsDictList=loadNewsForCategoryScreen(lang, category, maxClusterId) #return render_to_response('category.html', newsDictList,context_instance=RequestContext(request)) return HttpResponse(dumps(newsDictList,ensure_ascii=True), content_type="application/json") def loadTopN(request): #logger.info("Entered loadTopN ") if request.method == "GET": try: lang=request.GET['language'] except MultiValueDictKeyError: lang=ENGLISH userDict = getSimilarTopN(lang) return HttpResponse(dumps(userDict,ensure_ascii=True), content_type="application/json") def loadTopNVideo(request): #logger.info("Entered loadTopN ") if request.method == "GET": try: lang=request.GET['language'] except MultiValueDictKeyError: lang=ENGLISH userDict = getSimilarTopNVideo(lang) #logger.info("Exited loadTopN ") return HttpResponse(dumps(userDict,ensure_ascii=True), content_type="application/json") def loadVideoForCategory(request): if request.method == "GET": try: lang=request.GET['language'] except MultiValueDictKeyError: lang=ENGLISH try: category=request.GET['category'] except MultiValueDictKeyError: category=TOP_STORIES try: maxClusterId=int(request.GET['maxclusterid']) except MultiValueDictKeyError: maxClusterId=0 if not maxClusterId: # this means that the request is for the first time maxClusterId=0 limit=CATEGORY_VIDEO_LIMIT newsDictList=getVideoForCategoryScreen(lang, category, limit, maxClusterId) return HttpResponse(dumps(newsDictList,ensure_ascii=True), content_type="application/json") def isVideoAvailable(request): if request.method == "GET": lang=request.GET['language'] category=request.GET['category'] found = 0 for dict in videoLangCatList: if found == 0: if dict['lang'].lower() == lang.lower(): if dict['category'].lower() == category.lower(): found = 1 isVideoPresent ={} isVideoPresent['isPresent'] = found return HttpResponse(dumps(isVideoPresent,ensure_ascii=True), content_type="application/json") def loadNewsForCategoryNew(request): if request.method == "GET": try: lang=request.GET['language'] except MultiValueDictKeyError: lang=ENGLISH try: category=request.GET['category'] except MultiValueDictKeyError: category=TOP_STORIES try: maxClusterId=int(request.GET['maxclusterid']) except MultiValueDictKeyError: maxClusterId=0 similarNewsDict={} newsDictList=loadNewsForCategoryScreenNew(lang, category, maxClusterId) #return render_to_response('category.html', newsDictList,context_instance=RequestContext(request)) return HttpResponse(dumps(newsDictList,ensure_ascii=True), content_type="application/json") def loadSimilarNewsNew(request): if request.method == "GET": lang=request.GET['language'] category=request.GET['category'] clusterId=request.GET['clusterid'] userDict=getSimilarNewsArticlesNew(lang, category, clusterId) return HttpResponse(dumps(userDict,ensure_ascii=True), content_type="application/json")<file_sep>from models import * from userConstants import * import datetime #These methods are API METHODS. The app user will directly call them --------------------------- def loadNewsForHomeScreen(lang,categoryList): # Calling Screen: HOME #I/P: 1. langList - List of users language prefferences # 2. categoryList- List of users category prefferences #O/P: Top news from all those categories as provided in the list by language masterCategoryDict={} languageDict={} limit=HOME_ARTICLE_LIMIT maxClusterId=0 if lang.lower()==ENGLISH.lower(): languageDictList=[] for category in categoryList: masterCategoryDict[category]=getEnglishNewsFromCategory(category,limit,maxClusterId) languageDictList.append(masterCategoryDict) languageDict[lang]=languageDictList elif lang.lower()==MARATHI.lower(): languageDictList=[] for category in categoryList: masterCategoryDict[category]=getMarathiNewsFromCategory(category,limit,maxClusterId) languageDictList.append(masterCategoryDict) languageDict[lang]=languageDictList return languageDict def loadNewsForCategoryScreen(lang,category,maxClusterId): # Calling Screen: CATEGORY #I/P: 1. lang - users language # 2. category - users category # 3. maxClusterId - Highest value of the cluster Id #O/P: Top news from that category limit=CATEGORY_ARTICLE_LIMIT if not maxClusterId: # this means that the request is for the first time maxClusterId=0 if lang.lower()==ENGLISH.lower(): categoryDict=getEnglishNewsFromCategory(category,limit,maxClusterId) elif lang.lower()==MARATHI.lower(): categoryDict=getMarathiNewsFromCategory(category, limit, maxClusterId) return categoryDict def loadNewsForCategoryScreenNew(lang,category,maxClusterId): limit=CATEGORY_ARTICLE_LIMIT if not maxClusterId: # this means that the request is for the first time maxClusterId=0 if lang.lower()==ENGLISH.lower(): categoryDict=getEnglishNewsFromCategoryNew(category,limit,maxClusterId) elif lang.lower()==MARATHI.lower(): categoryDict=getMarathiNewsFromCategoryNew(category, limit, maxClusterId) elif lang.lower()==HINDI.lower(): categoryDict=getHindiNewsFromCategoryNew(category, limit, maxClusterId) return categoryDict def loadNewsForSourceNews(lang,category,sourceId): limit=CATEGORY_SOURCE_LIMIT if lang.lower()==ENGLISH.lower(): categoryDict=getEnglishNewsForSource(category,limit,sourceId) elif lang.lower()==MARATHI.lower(): categoryDict=getMarathiNewsForSource(category, limit,sourceId) elif lang.lower()==HINDI.lower(): categoryDict=getHindiNewsForSource(category, limit,sourceId) return categoryDict # This method will be called from the HOME SCREEN. It will load news by category. def getEnglishNewsFromCategory(category,limit,maxClusterId): if category.lower() == ECONOMY.lower(): categoryDict = English_Economy.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == SPORTS.lower(): categoryDict = English_Sports.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == TOP_STORIES.lower(): categoryDict = English_Top_Stories.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == WORLD.lower(): categoryDict = English_World.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == OPINION.lower(): if maxClusterId: categoryDict = English_Opinion.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Opinion.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == HEALTH.lower(): categoryDict = English_Health.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == LIFESTYLE.lower(): categoryDict = English_Lifestyle.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == ENTERTAINMENT.lower(): categoryDict = English_Entertainment.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == TECHNOLOGY.lower(): categoryDict = English_Technology.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == POLITICS.lower(): categoryDict = English_Politics.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == ENVIRONMENT.lower(): categoryDict = English_Environment.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == TRAVEL.lower(): categoryDict = English_Travel.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == SCIENCE.lower(): categoryDict = English_Science.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == BUSINESS.lower(): categoryDict = English_Business.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == STOCKS.lower(): categoryDict = English_Stocks.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == FOOD.lower(): categoryDict = English_Food.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == FASHION.lower(): categoryDict = English_Fashion.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == MUMBAI.lower(): if maxClusterId: categoryDict = English_Mumbai.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Mumbai.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == PUNE.lower(): if maxClusterId: categoryDict = English_Pune.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Pune.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] return parseDateTimeToString(categoryDict) def getEnglishNewsFromCategoryNew(category,limit,maxClusterId): if category.lower() == ECONOMY.lower(): categoryDict = English_Economy.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == SPORTS.lower(): categoryDict = English_Sports.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == TOP_STORIES.lower(): categoryDict = English_Top_Stories.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == WORLD.lower(): categoryDict = English_World.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == OPINION.lower(): if maxClusterId: categoryDict = English_Opinion.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Opinion.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == HEALTH.lower(): categoryDict = English_Health.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == LIFESTYLE.lower(): categoryDict = English_Lifestyle.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == ENTERTAINMENT.lower(): categoryDict = English_Entertainment.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == TECHNOLOGY.lower(): categoryDict = English_Technology.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == POLITICS.lower(): categoryDict = English_Politics.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == ENVIRONMENT.lower(): categoryDict = English_Environment.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == TRAVEL.lower(): categoryDict = English_Travel.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == SCIENCE.lower(): categoryDict = English_Science.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == BUSINESS.lower(): categoryDict = English_Business.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == STOCKS.lower(): categoryDict = English_Stocks.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == FOOD.lower(): categoryDict = English_Food.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == FASHION.lower(): categoryDict = English_Fashion.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == MUMBAI.lower(): if maxClusterId: categoryDict = English_Mumbai.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Mumbai.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == PUNE.lower(): if maxClusterId: categoryDict = English_Pune.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Pune.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] return parseDateTimeToStringSourceName(categoryDict) def getEnglishNewsForSource(category,limit,sourceId): sourceObj = News_Source.objects.get(id=sourceId) if category.lower() == ECONOMY.lower(): categoryDict = English_Economy.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SPORTS.lower(): categoryDict = English_Sports.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == TOP_STORIES.lower(): categoryDict = English_Top_Stories.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == WORLD.lower(): categoryDict = English_World.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == OPINION.lower(): categoryDict = English_Opinion.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == HEALTH.lower(): categoryDict = English_Health.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == LIFESTYLE.lower(): categoryDict = English_Lifestyle.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == ENTERTAINMENT.lower(): categoryDict = English_Entertainment.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == TECHNOLOGY.lower(): categoryDict = English_Technology.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == POLITICS.lower(): categoryDict = English_Politics.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == ENVIRONMENT.lower(): categoryDict = English_Environment.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == TRAVEL.lower(): categoryDict = English_Travel.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SCIENCE.lower(): categoryDict = English_Science.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BUSINESS.lower(): categoryDict = English_Business.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == STOCKS.lower(): categoryDict = English_Stocks.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == FOOD.lower(): categoryDict = English_Food.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == FASHION.lower(): categoryDict = English_Fashion.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == MUMBAI.lower(): categoryDict = English_Mumbai.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == PUNE.lower(): categoryDict = English_Pune.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] return parseDateTimeToStringSourceName(categoryDict) # This method will be called from the HOME SCREEN. It will load news by category. def getMarathiNewsFromCategory(category,limit,maxClusterId): if category.lower() == SPORTS.lower(): categoryDict = Marathi_Sports.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == TOP_STORIES.lower(): categoryDict = Marathi_Top_Stories.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == MAHARASHTRA.lower(): categoryDict = Marathi_Maharashtra.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == WORLD.lower(): categoryDict = Marathi_World.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == OPINION.lower(): if maxClusterId: categoryDict = Marathi_Opinion.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Opinion.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == HEALTH.lower(): categoryDict = Marathi_Health.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == LIFESTYLE.lower(): categoryDict = Marathi_Lifestyle.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == ENTERTAINMENT.lower(): if maxClusterId: categoryDict = Marathi_Entertainment.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Entertainment.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == TECHNOLOGY.lower(): categoryDict = Marathi_Technology.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == POLITICS.lower(): categoryDict = Marathi_Politics.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == TRAVEL.lower(): categoryDict = Marathi_Travel.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == SCIENCE.lower(): categoryDict = Marathi_Science.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == BUSINESS.lower(): categoryDict = Marathi_Business.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == FASHION.lower(): categoryDict = Marathi_Fashion.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == MUMBAI.lower(): if maxClusterId: categoryDict = Marathi_Mumbai.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Mumbai.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == PUNE.lower(): if maxClusterId: categoryDict = Marathi_Pune.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Pune.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == NAGPUR.lower(): if maxClusterId: categoryDict = Marathi_Nagpur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Nagpur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == NASIK.lower(): if maxClusterId: categoryDict = Marathi_Nasik.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Nasik.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == AURANGABAD.lower(): if maxClusterId: categoryDict = Marathi_Aurangabad.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Aurangabad.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SOLAPUR.lower(): if maxClusterId: categoryDict = Marathi_Solapur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Solapur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == KOLHAPUR.lower(): if maxClusterId: categoryDict = Marathi_Kolhapur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Kolhapur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SATARA.lower(): if maxClusterId: categoryDict = Marathi_Satara.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Satara.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SANGLI.lower(): if maxClusterId: categoryDict = Marathi_Sangli.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Sangli.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == AKOLA.lower(): if maxClusterId: categoryDict = Marathi_Akola.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Akola.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == AHMEDNAGAR.lower(): if maxClusterId: categoryDict = Marathi_Ahmednagar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Ahmednagar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == JALGAON.lower(): if maxClusterId: categoryDict = Marathi_Jalgaon.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Jalgaon.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == GOA.lower(): if maxClusterId: categoryDict = Marathi_Goa.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Goa.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == CHANDRAPUR.lower(): if maxClusterId: categoryDict = Marathi_Chandrapur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Chandrapur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == WARDHA.lower(): if maxClusterId: categoryDict = Marathi_Wardha.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Wardha.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] return parseDateTimeToString(categoryDict) def getMarathiNewsFromCategoryNew(category,limit,maxClusterId): if category.lower() == SPORTS.lower(): categoryDict = Marathi_Sports.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == TOP_STORIES.lower(): categoryDict = Marathi_Top_Stories.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == MAHARASHTRA.lower(): if maxClusterId: categoryDict = Marathi_Maharashtra.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Maharashtra.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == WORLD.lower(): categoryDict = Marathi_World.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == OPINION.lower(): if maxClusterId: categoryDict = Marathi_Opinion.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Opinion.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == HEALTH.lower(): if maxClusterId: categoryDict = Marathi_Health.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Health.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == LIFESTYLE.lower(): if maxClusterId: categoryDict = Marathi_Lifestyle.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Lifestyle.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == ENTERTAINMENT.lower(): if maxClusterId: categoryDict = Marathi_Entertainment.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Entertainment.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == TECHNOLOGY.lower(): categoryDict = Marathi_Technology.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == POLITICS.lower(): categoryDict = Marathi_Politics.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == TRAVEL.lower(): categoryDict = Marathi_Travel.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == SCIENCE.lower(): categoryDict = Marathi_Science.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == BUSINESS.lower(): if maxClusterId: categoryDict = Marathi_Business.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Business.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == FASHION.lower(): categoryDict = Marathi_Fashion.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == MUMBAI.lower(): if maxClusterId: categoryDict = Marathi_Mumbai.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Mumbai.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == PUNE.lower(): if maxClusterId: categoryDict = Marathi_Pune.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Pune.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == NAGPUR.lower(): if maxClusterId: categoryDict = Marathi_Nagpur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Nagpur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == NASIK.lower(): if maxClusterId: categoryDict = Marathi_Nasik.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Nasik.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == AURANGABAD.lower(): if maxClusterId: categoryDict = Marathi_Aurangabad.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Aurangabad.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SOLAPUR.lower(): if maxClusterId: categoryDict = Marathi_Solapur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Solapur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == KOLHAPUR.lower(): if maxClusterId: categoryDict = Marathi_Kolhapur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Kolhapur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SATARA.lower(): if maxClusterId: categoryDict = Marathi_Satara.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Satara.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SANGLI.lower(): if maxClusterId: categoryDict = Marathi_Sangli.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Sangli.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == AKOLA.lower(): if maxClusterId: categoryDict = Marathi_Akola.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Akola.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == AHMEDNAGAR.lower(): if maxClusterId: categoryDict = Marathi_Ahmednagar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Ahmednagar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == JALGAON.lower(): if maxClusterId: categoryDict = Marathi_Jalgaon.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Jalgaon.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == GOA.lower(): if maxClusterId: categoryDict = Marathi_Goa.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Goa.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == CHANDRAPUR.lower(): if maxClusterId: categoryDict = Marathi_Chandrapur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Chandrapur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == WARDHA.lower(): if maxClusterId: categoryDict = Marathi_Wardha.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Wardha.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] return parseDateTimeToStringSourceName(categoryDict) def getMarathiNewsForSource(category,limit,sourceId): sourceObj = News_Source.objects.get(id=sourceId) if category.lower() == SPORTS.lower(): categoryDict = Marathi_Sports.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == TOP_STORIES.lower(): categoryDict = Marathi_Top_Stories.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == MAHARASHTRA.lower(): categoryDict = Marathi_Maharashtra.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == WORLD.lower(): categoryDict = Marathi_World.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == OPINION.lower(): categoryDict = Marathi_Opinion.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == HEALTH.lower(): categoryDict = Marathi_Health.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == LIFESTYLE.lower(): categoryDict = Marathi_Lifestyle.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == ENTERTAINMENT.lower(): categoryDict = Marathi_Entertainment.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == TECHNOLOGY.lower(): categoryDict = Marathi_Technology.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == POLITICS.lower(): categoryDict = Marathi_Politics.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == TRAVEL.lower(): categoryDict = Marathi_Travel.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SCIENCE.lower(): categoryDict = Marathi_Science.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BUSINESS.lower(): categoryDict = Marathi_Business.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == FASHION.lower(): categoryDict = Marathi_Fashion.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == MUMBAI.lower(): categoryDict = Marathi_Mumbai.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == PUNE.lower(): categoryDict = Marathi_Pune.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == NAGPUR.lower(): categoryDict = Marathi_Nagpur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == NASIK.lower(): categoryDict = Marathi_Nasik.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == AURANGABAD.lower(): categoryDict = Marathi_Aurangabad.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SOLAPUR.lower(): categoryDict = Marathi_Solapur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == KOLHAPUR.lower(): categoryDict = Marathi_Kolhapur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SATARA.lower(): categoryDict = Marathi_Satara.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SANGLI.lower(): categoryDict = Marathi_Sangli.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == AKOLA.lower(): categoryDict = Marathi_Akola.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == AHMEDNAGAR.lower(): categoryDict = Marathi_Ahmednagar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == JALGAON.lower(): categoryDict = Marathi_Jalgaon.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == GOA.lower(): categoryDict = Marathi_Goa.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == CHANDRAPUR.lower(): categoryDict = Marathi_Chandrapur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == WARDHA.lower(): categoryDict = Marathi_Wardha.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] return parseDateTimeToStringSourceName(categoryDict) def getSimilarNewsArticles(lang,category,clusterId): limit=SIMILAR_ARTICLE_LIMIT if lang.lower()==ENGLISH.lower(): categoryDict=getSimilarEnglishNewsArticles(category,limit,clusterId) elif lang.lower()==MARATHI.lower(): categoryDict=getSimilarMarathiNewsArticles(category,limit,clusterId) return categoryDict # This method will be called from the HOME/CATEGORY SCREEN. It will return similar news article details. def getSimilarNewsArticlesNew(lang,category,clusterId): limit=SIMILAR_ARTICLE_LIMIT if lang.lower()==ENGLISH.lower(): categoryDict=getSimilarEnglishNewsArticlesNew(category,limit,clusterId) elif lang.lower()==MARATHI.lower(): categoryDict=getSimilarMarathiNewsArticlesNew(category,limit,clusterId) elif lang.lower()==HINDI.lower(): categoryDict=getSimilarHindiNewsArticlesNew(category,limit,clusterId) return categoryDict # This method will be called from the HOME/CATEGORY SCREEN. It will return similar news article details. def getSimilarEnglishNewsArticles(category,limit,clusterId): if category.lower() == ECONOMY.lower(): categoryDict = English_Economy.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SPORTS.lower(): categoryDict = English_Sports.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TOP_STORIES.lower(): categoryDict = English_Top_Stories.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == WORLD.lower(): categoryDict = English_World.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == OPINION.lower(): categoryDict = English_Opinion.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == HEALTH.lower(): categoryDict = English_Health.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == LIFESTYLE.lower(): categoryDict = English_Lifestyle.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ENTERTAINMENT.lower(): categoryDict = English_Entertainment.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TECHNOLOGY.lower(): categoryDict = English_Technology.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == POLITICS.lower(): categoryDict = English_Politics.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ENVIRONMENT.lower(): categoryDict = English_Environment.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TRAVEL.lower(): categoryDict = English_Travel.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SCIENCE.lower(): categoryDict = English_Science.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BUSINESS.lower(): categoryDict = English_Business.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == STOCKS.lower(): categoryDict = English_Stocks.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == FOOD.lower(): categoryDict = English_Food.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == FASHION.lower(): categoryDict = English_Fashion.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MUMBAI.lower(): categoryDict = English_Mumbai.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == PUNE.lower(): categoryDict = English_Pune.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] return parseDateTimeToString(categoryDict) def getSimilarEnglishNewsArticlesNew(category,limit,clusterId): if category.lower() == ECONOMY.lower(): categoryDict = English_Economy.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SPORTS.lower(): categoryDict = English_Sports.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TOP_STORIES.lower(): categoryDict = English_Top_Stories.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == WORLD.lower(): categoryDict = English_World.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == OPINION.lower(): categoryDict = English_Opinion.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == HEALTH.lower(): categoryDict = English_Health.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == LIFESTYLE.lower(): categoryDict = English_Lifestyle.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ENTERTAINMENT.lower(): categoryDict = English_Entertainment.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TECHNOLOGY.lower(): categoryDict = English_Technology.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == POLITICS.lower(): categoryDict = English_Politics.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ENVIRONMENT.lower(): categoryDict = English_Environment.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TRAVEL.lower(): categoryDict = English_Travel.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SCIENCE.lower(): categoryDict = English_Science.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BUSINESS.lower(): categoryDict = English_Business.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == STOCKS.lower(): categoryDict = English_Stocks.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == FOOD.lower(): categoryDict = English_Food.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == FASHION.lower(): categoryDict = English_Fashion.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MUMBAI.lower(): categoryDict = English_Mumbai.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == PUNE.lower(): categoryDict = English_Pune.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] return parseDateTimeToStringSourceName(categoryDict) def getSimilarMarathiNewsArticles(category,limit,clusterId): # This method will be called from the HOME/CATEGORY SCREEN. It will return similar news article details. if category.lower() == SPORTS.lower(): categoryDict = Marathi_Sports.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TOP_STORIES.lower(): categoryDict = Marathi_Top_Stories.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == WORLD.lower(): categoryDict = Marathi_World.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == OPINION.lower(): categoryDict = Marathi_Opinion.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == HEALTH.lower(): categoryDict = Marathi_Health.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == LIFESTYLE.lower(): categoryDict = Marathi_Lifestyle.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ENTERTAINMENT.lower(): categoryDict = Marathi_Entertainment.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TECHNOLOGY.lower(): categoryDict = Marathi_Technology.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == POLITICS.lower(): categoryDict = Marathi_Politics.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TRAVEL.lower(): categoryDict = Marathi_Travel.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SCIENCE.lower(): categoryDict = Marathi_Science.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BUSINESS.lower(): categoryDict = Marathi_Business.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == FASHION.lower(): categoryDict = Marathi_Fashion.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MUMBAI.lower(): categoryDict = Marathi_Mumbai.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == PUNE.lower(): categoryDict = Marathi_Pune.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == NAGPUR.lower(): categoryDict = Marathi_Nagpur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == NASIK.lower(): categoryDict = Marathi_Nasik.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == AURANGABAD.lower(): categoryDict = Marathi_Aurangabad.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SOLAPUR.lower(): categoryDict = Marathi_Solapur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == KOLHAPUR.lower(): categoryDict = Marathi_Kolhapur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SATARA.lower(): categoryDict = Marathi_Satara.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SANGLI.lower(): categoryDict = Marathi_Sangli.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == AKOLA.lower(): categoryDict = Marathi_Akola.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == AHMEDNAGAR.lower(): categoryDict = Marathi_Ahmednagar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == JALGAON.lower(): categoryDict = Marathi_Jalgaon.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == GOA.lower(): categoryDict = Marathi_Goa.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == CHANDRAPUR.lower(): categoryDict = Marathi_Chandrapur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == WARDHA.lower(): categoryDict = Marathi_Wardha.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MAHARASHTRA.lower(): categoryDict = Marathi_Maharashtra.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] return parseDateTimeToString(categoryDict) def getSimilarMarathiNewsArticlesNew(category,limit,clusterId): if category.lower() == SPORTS.lower(): categoryDict = Marathi_Sports.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TOP_STORIES.lower(): categoryDict = Marathi_Top_Stories.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == WORLD.lower(): categoryDict = Marathi_World.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == OPINION.lower(): categoryDict = Marathi_Opinion.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == HEALTH.lower(): categoryDict = Marathi_Health.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == LIFESTYLE.lower(): categoryDict = Marathi_Lifestyle.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ENTERTAINMENT.lower(): categoryDict = Marathi_Entertainment.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TECHNOLOGY.lower(): categoryDict = Marathi_Technology.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == POLITICS.lower(): categoryDict = Marathi_Politics.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TRAVEL.lower(): categoryDict = Marathi_Travel.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SCIENCE.lower(): categoryDict = Marathi_Science.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BUSINESS.lower(): categoryDict = Marathi_Business.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == FASHION.lower(): categoryDict = Marathi_Fashion.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MUMBAI.lower(): categoryDict = Marathi_Mumbai.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == PUNE.lower(): categoryDict = Marathi_Pune.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == NAGPUR.lower(): categoryDict = Marathi_Nagpur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == NASIK.lower(): categoryDict = Marathi_Nasik.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == AURANGABAD.lower(): categoryDict = Marathi_Aurangabad.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SOLAPUR.lower(): categoryDict = Marathi_Solapur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == KOLHAPUR.lower(): categoryDict = Marathi_Kolhapur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SATARA.lower(): categoryDict = Marathi_Satara.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SANGLI.lower(): categoryDict = Marathi_Sangli.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == AKOLA.lower(): categoryDict = Marathi_Akola.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == AHMEDNAGAR.lower(): categoryDict = Marathi_Ahmednagar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == JALGAON.lower(): categoryDict = Marathi_Jalgaon.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == GOA.lower(): categoryDict = Marathi_Goa.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == CHANDRAPUR.lower(): categoryDict = Marathi_Chandrapur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == WARDHA.lower(): categoryDict = Marathi_Wardha.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MAHARASHTRA.lower(): categoryDict = Marathi_Maharashtra.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] return parseDateTimeToStringSourceName(categoryDict) def getSimilarHindiNewsArticlesNew(category,limit,clusterId): if category.lower() == UTTARPRADESH.lower(): categoryDict = Hindi_UttarPradesh.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == UTTARAKHAND.lower(): categoryDict = Hindi_Uttarakhand.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == HIMACHALPRADESH.lower(): categoryDict = Hindi_HimachalPradesh.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == DELHI.lower(): categoryDict = Hindi_Delhi.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == JAMMUKASHMIR.lower(): categoryDict = Hindi_JammuKashmir.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == PUNJAB.lower(): categoryDict = Hindi_Punjab.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MADHYAPRADESH.lower(): categoryDict = Hindi_MadhyaPradesh.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == JHARKHAND.lower(): categoryDict = Hindi_Jharkhand.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BIHAR.lower(): categoryDict = Hindi_Bihar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == HARYANA.lower(): categoryDict = Hindi_Haryana.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == CHATTISGARH.lower(): categoryDict = Hindi_Chattisgarh.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == RAJASTHAN.lower(): categoryDict = Hindi_Rajasthan.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == WESTBENGAL.lower(): categoryDict = Hindi_WestBengal.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ORISSA.lower(): categoryDict = Hindi_Orissa.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == GUJRAT.lower(): categoryDict = Hindi_Gujrat.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MAHARASHTRA.lower(): categoryDict = Hindi_Maharashtra.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == LUCKNOW.lower(): categoryDict = Hindi_Lucknow.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ALLAHABAD.lower(): categoryDict = Hindi_Allahabad.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == PRATAPGARH.lower(): categoryDict = Hindi_Pratapgarh.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == KANPUR.lower(): categoryDict = Hindi_Kanpur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MERATH.lower(): categoryDict = Hindi_Merath.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == AGRA.lower(): categoryDict = Hindi_Agra.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == NOIDA.lower(): categoryDict = Hindi_Noida.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == GAZIABAD.lower(): categoryDict = Hindi_Gaziabad.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BAGPAT.lower(): categoryDict = Hindi_Bagpat.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SAHARNPUR.lower(): categoryDict = Hindi_Saharnpur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BULANDSHAHAR.lower(): categoryDict = Hindi_Bulandshahar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == VARANASI.lower(): categoryDict = Hindi_Varanasi.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == GORAKHPUR.lower(): categoryDict = Hindi_Gorakhpur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == JHANSI.lower(): categoryDict = Hindi_Jhansi.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MUZAFFARNAGAR.lower(): categoryDict = Hindi_Muzaffarnagar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SITAPUR.lower(): categoryDict = Hindi_Sitapur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == JAUNPUR.lower(): categoryDict = Hindi_Jaunpur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == AZAMGARH.lower(): categoryDict = Hindi_Azamgarh.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MORADABAD.lower(): categoryDict = Hindi_Moradabad.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BAREILLY.lower(): categoryDict = Hindi_Bareilly.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BALIA.lower(): categoryDict = Hindi_Balia.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ALIGARH.lower(): categoryDict = Hindi_Aligarh.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MATHURA.lower(): categoryDict = Hindi_Mathura.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BHOPAL.lower(): categoryDict = Hindi_Bhopal.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == INDORE.lower(): categoryDict = Hindi_Indore.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == GWALIOR.lower(): categoryDict = Hindi_Gwalior.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == JABALPUR.lower(): categoryDict = Hindi_Jabalpur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == UJJAIN.lower(): categoryDict = Hindi_Ujjain.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == RATLAM.lower(): categoryDict = Hindi_Ratlam.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SAGAR.lower(): categoryDict = Hindi_Sagar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == DEWAS.lower(): categoryDict = Hindi_Dewas.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SATNA.lower(): categoryDict = Hindi_Satna.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == REWA.lower(): categoryDict = Hindi_Rewa.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == PATNA.lower(): categoryDict = Hindi_Patna.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BHAGALPUR.lower(): categoryDict = Hindi_Bhagalpur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MUJAFFARPUR.lower(): categoryDict = Hindi_Mujaffarpur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == GAYA.lower(): categoryDict = Hindi_Gaya.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == DARBHANGA.lower(): categoryDict = Hindi_Darbhanga.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == POORNIYA.lower(): categoryDict = Hindi_Poorniya.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SEWAN.lower(): categoryDict = Hindi_Sewan.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BEGUSARAI.lower(): categoryDict = Hindi_Begusarai.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == KATIHAR.lower(): categoryDict = Hindi_Katihar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == JAIPUR.lower(): categoryDict = Hindi_Jaipur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == UDAIPUR.lower(): categoryDict = Hindi_Udaipur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == JODHPUR.lower(): categoryDict = Hindi_Jodhpur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == AJMER.lower(): categoryDict = Hindi_Ajmer.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BIKANER.lower(): categoryDict = Hindi_Bikaner.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ALWAR.lower(): categoryDict = Hindi_Alwar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SIKAR.lower(): categoryDict = Hindi_Sikar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == KOTA.lower(): categoryDict = Hindi_Kota.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BHILWARA.lower(): categoryDict = Hindi_Bhilwara.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BHARATPUR.lower(): categoryDict = Hindi_Bharatpur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == CHHATIS.lower(): categoryDict = Hindi_Chhatis.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == RAIPUR.lower(): categoryDict = Hindi_Raipur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BHILAI.lower(): categoryDict = Hindi_Bhilai.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == RAJNANDGAO.lower(): categoryDict = Hindi_Rajnandgao.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == RAIGARH.lower(): categoryDict = Hindi_Raigarh.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == JAGDALPUR.lower(): categoryDict = Hindi_Jagdalpur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == KORVA.lower(): categoryDict = Hindi_Korva.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == RANCHI.lower(): categoryDict = Hindi_Ranchi.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == DHANBAD.lower(): categoryDict = Hindi_Dhanbad.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == JAMSHEDPUR.lower(): categoryDict = Hindi_Jamshedpur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == GIRIDIHI.lower(): categoryDict = Hindi_Giridihi.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == HAZARIBAGH.lower(): categoryDict = Hindi_Hazaribagh.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BOKARO.lower(): categoryDict = Hindi_Bokaro.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == DEHRADUN.lower(): categoryDict = Hindi_Dehradun.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == NAINITAAL.lower(): categoryDict = Hindi_Nainitaal.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == HARIDWAAR.lower(): categoryDict = Hindi_Haridwaar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ALMORAH.lower(): categoryDict = Hindi_Almorah.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == UDDHAMSINGHNAGAR.lower(): categoryDict = Hindi_UddhamSinghNagar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SIMLA.lower(): categoryDict = Hindi_Simla.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MANDI.lower(): categoryDict = Hindi_Mandi.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BILASPUR.lower(): categoryDict = Hindi_Bilaspur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == AMRITSAR.lower(): categoryDict = Hindi_Amritsar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == JALANDHAR.lower(): categoryDict = Hindi_Jalandhar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == LUDHIANA.lower(): categoryDict = Hindi_Ludhiana.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ROPARH.lower(): categoryDict = Hindi_Roparh.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == CHANDIGARH.lower(): categoryDict = Hindi_Chandigarh.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ROHTAK.lower(): categoryDict = Hindi_Rohtak.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == PANCHKULA.lower(): categoryDict = Hindi_Panchkula.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == AMBALA.lower(): categoryDict = Hindi_Ambala.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == PANIPAT.lower(): categoryDict = Hindi_Panipat.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == GURGAON.lower(): categoryDict = Hindi_Gurgaon.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == HISSAR.lower(): categoryDict = Hindi_Hissar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == JAMMU.lower(): categoryDict = Hindi_Jammu.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SRINAGAR.lower(): categoryDict = Hindi_Srinagar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == POONCH.lower(): categoryDict = Hindi_Poonch.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == KOLKATA.lower(): categoryDict = Hindi_Kolkata.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == JALPAIGURHI.lower(): categoryDict = Hindi_Jalpaigurhi.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == DARJEELING.lower(): categoryDict = Hindi_Darjeeling.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ASANSOL.lower(): categoryDict = Hindi_Asansol.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SILIGURHI.lower(): categoryDict = Hindi_Siligurhi.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BHUVANESHWAR.lower(): categoryDict = Hindi_Bhuvaneshwar.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == PURI.lower(): categoryDict = Hindi_Puri.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == CUTTACK.lower(): categoryDict = Hindi_Cuttack.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == AHMEDABAD.lower(): categoryDict = Hindi_Ahmedabad.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SURAT.lower(): categoryDict = Hindi_Surat.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == VADODARA.lower(): categoryDict = Hindi_Vadodara.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == MUMBAI.lower(): categoryDict = Hindi_Mumbai.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == NAGPUR.lower(): categoryDict = Hindi_Nagpur.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == PUNE.lower(): categoryDict = Hindi_Pune.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SPORTS.lower(): categoryDict = Hindi_Sports.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TOP_STORIES.lower(): categoryDict = Hindi_Top_Stories.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == WORLD.lower(): categoryDict = Hindi_World.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == OPINION.lower(): categoryDict = Hindi_Opinion.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == HEALTH.lower(): categoryDict = Hindi_Health.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == LIFESTYLE.lower(): categoryDict = Hindi_Lifestyle.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ENTERTAINMENT.lower(): categoryDict = Hindi_Entertainment.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TECHNOLOGY.lower(): categoryDict = Hindi_Technology.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == POLITICS.lower(): categoryDict = Hindi_Politics.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == ENVIRONMENT.lower(): categoryDict = Hindi_Environment.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == TRAVEL.lower(): categoryDict = Hindi_Travel.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == SCIENCE.lower(): categoryDict = Hindi_Science.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == BUSINESS.lower(): categoryDict = Hindi_Business.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == STOCKS.lower(): categoryDict = Hindi_Stocks.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == FOOD.lower(): categoryDict = Hindi_Food.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == WEEKEND.lower(): categoryDict = Hindi_Weekend.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] if category.lower() == FASHION.lower(): categoryDict = Hindi_Fashion.objects.filter(Is_Rep = 0,Cluster_Id=clusterId).order_by('-Published_Date')[:limit] return parseDateTimeToStringSourceName(categoryDict) def getHindiNewsFromCategoryNew(category,limit,maxClusterId): if category.lower() == SPORTS.lower(): categoryDict = Hindi_Sports.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == CRIME.lower(): if maxClusterId: categoryDict = Hindi_Crime.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Crime.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == AUTO.lower(): if maxClusterId: categoryDict = Hindi_Auto.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Auto.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == TOP_STORIES.lower(): categoryDict = Hindi_Top_Stories.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == MAHARASHTRA.lower(): if maxClusterId: categoryDict = Hindi_Maharashtra.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Maharashtra.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == WORLD.lower(): categoryDict = Hindi_World.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == OPINION.lower(): if maxClusterId: categoryDict = Hindi_Opinion.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Opinion.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == HEALTH.lower(): if maxClusterId: categoryDict = Hindi_Health.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Health.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == LIFESTYLE.lower(): if maxClusterId: categoryDict = Hindi_Lifestyle.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Lifestyle.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == ENTERTAINMENT.lower(): if maxClusterId: categoryDict = Hindi_Entertainment.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Entertainment.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == TECHNOLOGY.lower(): if maxClusterId: categoryDict = Hindi_Technology.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Technology.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == POLITICS.lower(): if maxClusterId: categoryDict = Hindi_Politics.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Politics.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == TRAVEL.lower(): if maxClusterId: categoryDict = Hindi_Travel.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Travel.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SCIENCE.lower(): if maxClusterId: categoryDict = Hindi_Science.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Science.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BUSINESS.lower(): if maxClusterId: categoryDict = Hindi_Business.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Business.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == FASHION.lower(): categoryDict = Hindi_Fashion.objects.filter(Is_Rep = 1,Cluster_Id__gt=maxClusterId).order_by('Cluster_Id')[:limit] if category.lower() == UTTARPRADESH.lower(): if maxClusterId: categoryDict = Hindi_UttarPradesh.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_UttarPradesh.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == UTTARAKHAND.lower(): if maxClusterId: categoryDict = Hindi_Uttarakhand.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Uttarakhand.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == HIMACHALPRADESH.lower(): if maxClusterId: categoryDict = Hindi_HimachalPradesh.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_HimachalPradesh.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == DELHI.lower(): if maxClusterId: categoryDict = Hindi_Delhi.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Delhi.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == JAMMUKASHMIR.lower(): if maxClusterId: categoryDict = Hindi_JammuKashmir.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_JammuKashmir.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == PUNJAB.lower(): if maxClusterId: categoryDict = Hindi_Punjab.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Punjab.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == MADHYAPRADESH.lower(): if maxClusterId: categoryDict = Hindi_MadhyaPradesh.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_MadhyaPradesh.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == JHARKHAND.lower(): if maxClusterId: categoryDict = Hindi_Jharkhand.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Jharkhand.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BIHAR.lower(): if maxClusterId: categoryDict = Hindi_Bihar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Bihar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == HARYANA.lower(): if maxClusterId: categoryDict = Hindi_Haryana.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Haryana.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == CHATTISGARH.lower(): if maxClusterId: categoryDict = Hindi_Chattisgarh.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Chattisgarh.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == RAJASTHAN.lower(): if maxClusterId: categoryDict = Hindi_Rajasthan.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Rajasthan.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == WESTBENGAL.lower(): if maxClusterId: categoryDict = Hindi_WestBengal.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_WestBengal.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == ORISSA.lower(): if maxClusterId: categoryDict = Hindi_Orissa.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Orissa.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == GUJRAT.lower(): if maxClusterId: categoryDict = Hindi_Gujrat.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Gujrat.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == MAHARASHTRA.lower(): if maxClusterId: categoryDict = Hindi_Maharashtra.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Maharashtra.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == LUCKNOW.lower(): if maxClusterId: categoryDict = Hindi_Lucknow.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Lucknow.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == ALLAHABAD.lower(): if maxClusterId: categoryDict = Hindi_Allahabad.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Allahabad.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == PRATAPGARH.lower(): if maxClusterId: categoryDict = Hindi_Pratapgarh.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Pratapgarh.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == KANPUR.lower(): if maxClusterId: categoryDict = Hindi_Kanpur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Kanpur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == MERATH.lower(): if maxClusterId: categoryDict = Hindi_Merath.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Merath.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == AGRA.lower(): if maxClusterId: categoryDict = Hindi_Agra.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Agra.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == NOIDA.lower(): if maxClusterId: categoryDict = Hindi_Noida.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Noida.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == GAZIABAD.lower(): if maxClusterId: categoryDict = Hindi_Gaziabad.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Gaziabad.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BAGPAT.lower(): if maxClusterId: categoryDict = Hindi_Bagpat.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Bagpat.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SAHARNPUR.lower(): if maxClusterId: categoryDict = Hindi_Saharnpur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Saharnpur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BULANDSHAHAR.lower(): if maxClusterId: categoryDict = Hindi_Bulandshahar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Bulandshahar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == VARANASI.lower(): if maxClusterId: categoryDict = Hindi_Varanasi.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Varanasi.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == GORAKHPUR.lower(): if maxClusterId: categoryDict = Hindi_Gorakhpur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Gorakhpur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == JHANSI.lower(): if maxClusterId: categoryDict = Hindi_Jhansi.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Jhansi.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == MUZAFFARNAGAR.lower(): if maxClusterId: categoryDict = Hindi_Muzaffarnagar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Muzaffarnagar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SITAPUR.lower(): if maxClusterId: categoryDict = Hindi_Sitapur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Sitapur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == JAUNPUR.lower(): if maxClusterId: categoryDict = Hindi_Jaunpur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Jaunpur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == AZAMGARH.lower(): if maxClusterId: categoryDict = Hindi_Azamgarh.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Azamgarh.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == MORADABAD.lower(): if maxClusterId: categoryDict = Hindi_Moradabad.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Moradabad.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BAREILLY.lower(): if maxClusterId: categoryDict = Hindi_Bareilly.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Bareilly.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BALIA.lower(): if maxClusterId: categoryDict = Hindi_Balia.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Balia.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == ALIGARH.lower(): if maxClusterId: categoryDict = Hindi_Aligarh.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Aligarh.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == MATHURA.lower(): if maxClusterId: categoryDict = Hindi_Mathura.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Mathura.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BHOPAL.lower(): if maxClusterId: categoryDict = Hindi_Bhopal.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Bhopal.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == INDORE.lower(): if maxClusterId: categoryDict = Hindi_Indore.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Indore.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == GWALIOR.lower(): if maxClusterId: categoryDict = Hindi_Gwalior.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Gwalior.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == JABALPUR.lower(): if maxClusterId: categoryDict = Hindi_Jabalpur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Jabalpur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == UJJAIN.lower(): if maxClusterId: categoryDict = Hindi_Ujjain.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Ujjain.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == RATLAM.lower(): if maxClusterId: categoryDict = Hindi_Ratlam.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Ratlam.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SAGAR.lower(): if maxClusterId: categoryDict = Hindi_Sagar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Sagar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == DEWAS.lower(): if maxClusterId: categoryDict = Hindi_Dewas.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Dewas.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SATNA.lower(): if maxClusterId: categoryDict = Hindi_Satna.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Satna.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == REWA.lower(): if maxClusterId: categoryDict = Hindi_Rewa.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Rewa.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == PATNA.lower(): if maxClusterId: categoryDict = Hindi_Patna.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Patna.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BHAGALPUR.lower(): if maxClusterId: categoryDict = Hindi_Bhagalpur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Bhagalpur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == MUJAFFARPUR.lower(): if maxClusterId: categoryDict = Hindi_Mujaffarpur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Mujaffarpur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == GAYA.lower(): if maxClusterId: categoryDict = Hindi_Gaya.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Gaya.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == DARBHANGA.lower(): if maxClusterId: categoryDict = Hindi_Darbhanga.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Darbhanga.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == POORNIYA.lower(): if maxClusterId: categoryDict = Hindi_Poorniya.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Poorniya.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SEWAN.lower(): if maxClusterId: categoryDict = Hindi_Sewan.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Sewan.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BEGUSARAI.lower(): if maxClusterId: categoryDict = Hindi_Begusarai.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Begusarai.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == KATIHAR.lower(): if maxClusterId: categoryDict = Hindi_Katihar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Katihar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == JAIPUR.lower(): if maxClusterId: categoryDict = Hindi_Jaipur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Jaipur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == UDAIPUR.lower(): if maxClusterId: categoryDict = Hindi_Udaipur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Udaipur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == JODHPUR.lower(): if maxClusterId: categoryDict = Hindi_Jodhpur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Jodhpur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == AJMER.lower(): if maxClusterId: categoryDict = Hindi_Ajmer.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Ajmer.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BIKANER.lower(): if maxClusterId: categoryDict = Hindi_Bikaner.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Bikaner.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == ALWAR.lower(): if maxClusterId: categoryDict = Hindi_Alwar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Alwar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SIKAR.lower(): if maxClusterId: categoryDict = Hindi_Sikar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Sikar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == KOTA.lower(): if maxClusterId: categoryDict = Hindi_Kota.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Kota.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BHILWARA.lower(): if maxClusterId: categoryDict = Hindi_Bhilwara.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Bhilwara.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BHARATPUR.lower(): if maxClusterId: categoryDict = Hindi_Bharatpur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Bharatpur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == CHHATIS.lower(): if maxClusterId: categoryDict = Hindi_Chhatis.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Chhatis.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == RAIPUR.lower(): if maxClusterId: categoryDict = Hindi_Raipur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Raipur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BHILAI.lower(): if maxClusterId: categoryDict = Hindi_Bhilai.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Bhilai.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == RAJNANDGAO.lower(): if maxClusterId: categoryDict = Hindi_Rajnandgao.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Rajnandgao.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == RAIGARH.lower(): if maxClusterId: categoryDict = Hindi_Raigarh.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Raigarh.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == JAGDALPUR.lower(): if maxClusterId: categoryDict = Hindi_Jagdalpur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Jagdalpur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == KORVA.lower(): if maxClusterId: categoryDict = Hindi_Korva.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Korva.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == RANCHI.lower(): if maxClusterId: categoryDict = Hindi_Ranchi.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Ranchi.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == DHANBAD.lower(): if maxClusterId: categoryDict = Hindi_Dhanbad.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Dhanbad.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == JAMSHEDPUR.lower(): if maxClusterId: categoryDict = Hindi_Jamshedpur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Jamshedpur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == GIRIDIHI.lower(): if maxClusterId: categoryDict = Hindi_Giridihi.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Giridihi.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == HAZARIBAGH.lower(): if maxClusterId: categoryDict = Hindi_Hazaribagh.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Hazaribagh.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BOKARO.lower(): if maxClusterId: categoryDict = Hindi_Bokaro.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Bokaro.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == DEHRADUN.lower(): if maxClusterId: categoryDict = Hindi_Dehradun.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Dehradun.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == NAINITAAL.lower(): if maxClusterId: categoryDict = Hindi_Nainitaal.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Nainitaal.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == HARIDWAAR.lower(): if maxClusterId: categoryDict = Hindi_Haridwaar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Haridwaar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == ALMORAH.lower(): if maxClusterId: categoryDict = Hindi_Almorah.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Almorah.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == UDDHAMSINGHNAGAR.lower(): if maxClusterId: categoryDict = Hindi_UddhamSinghNagar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_UddhamSinghNagar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SIMLA.lower(): if maxClusterId: categoryDict = Hindi_Simla.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Simla.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == MANDI.lower(): if maxClusterId: categoryDict = Hindi_Mandi.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Mandi.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BILASPUR.lower(): if maxClusterId: categoryDict = Hindi_Bilaspur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Bilaspur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == AMRITSAR.lower(): if maxClusterId: categoryDict = Hindi_Amritsar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Amritsar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == JALANDHAR.lower(): if maxClusterId: categoryDict = Hindi_Jalandhar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Jalandhar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == LUDHIANA.lower(): if maxClusterId: categoryDict = Hindi_Ludhiana.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Ludhiana.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == ROPARH.lower(): if maxClusterId: categoryDict = Hindi_Roparh.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Roparh.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == CHANDIGARH.lower(): if maxClusterId: categoryDict = Hindi_Chandigarh.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Chandigarh.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == ROHTAK.lower(): if maxClusterId: categoryDict = Hindi_Rohtak.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Rohtak.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == PANCHKULA.lower(): if maxClusterId: categoryDict = Hindi_Panchkula.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Panchkula.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == AMBALA.lower(): if maxClusterId: categoryDict = Hindi_Ambala.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Ambala.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == PANIPAT.lower(): if maxClusterId: categoryDict = Hindi_Panipat.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Panipat.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == GURGAON.lower(): if maxClusterId: categoryDict = Hindi_Gurgaon.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Gurgaon.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == HISSAR.lower(): if maxClusterId: categoryDict = Hindi_Hissar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Hissar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == JAMMU.lower(): if maxClusterId: categoryDict = Hindi_Jammu.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Jammu.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SRINAGAR.lower(): if maxClusterId: categoryDict = Hindi_Srinagar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Srinagar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == POONCH.lower(): if maxClusterId: categoryDict = Hindi_Poonch.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Poonch.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == KOLKATA.lower(): if maxClusterId: categoryDict = Hindi_Kolkata.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Kolkata.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == JALPAIGURHI.lower(): if maxClusterId: categoryDict = Hindi_Jalpaigurhi.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Jalpaigurhi.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == DARJEELING.lower(): if maxClusterId: categoryDict = Hindi_Darjeeling.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Darjeeling.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == ASANSOL.lower(): if maxClusterId: categoryDict = Hindi_Asansol.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Asansol.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SILIGURHI.lower(): if maxClusterId: categoryDict = Hindi_Siligurhi.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Siligurhi.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BHUVANESHWAR.lower(): if maxClusterId: categoryDict = Hindi_Bhuvaneshwar.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Bhuvaneshwar.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == PURI.lower(): if maxClusterId: categoryDict = Hindi_Puri.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Puri.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == CUTTACK.lower(): if maxClusterId: categoryDict = Hindi_Cuttack.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Cuttack.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == AHMEDABAD.lower(): if maxClusterId: categoryDict = Hindi_Ahmedabad.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Ahmedabad.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SURAT.lower(): if maxClusterId: categoryDict = Hindi_Surat.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Surat.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == VADODARA.lower(): if maxClusterId: categoryDict = Hindi_Vadodara.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Vadodara.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == MUMBAI.lower(): if maxClusterId: categoryDict = Hindi_Mumbai.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Mumbai.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == NAGPUR.lower(): if maxClusterId: categoryDict = Hindi_Nagpur.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Nagpur.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == PUNE.lower(): if maxClusterId: categoryDict = Hindi_Pune.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Pune.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] return parseDateTimeToStringSourceName(categoryDict) def getHindiNewsForSource(category, limit,sourceId): sourceObj = News_Source.objects.get(id=sourceId) if category.lower() == UTTARPRADESH.lower(): categoryDict = Hindi_UttarPradesh.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == UTTARAKHAND.lower(): categoryDict = Hindi_Uttarakhand.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == HIMACHALPRADESH.lower(): categoryDict = Hindi_HimachalPradesh.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == DELHI.lower(): categoryDict = Hindi_Delhi.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == JAMMUKASHMIR.lower(): categoryDict = Hindi_JammuKashmir.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == PUNJAB.lower(): categoryDict = Hindi_Punjab.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == MADHYAPRADESH.lower(): categoryDict = Hindi_MadhyaPradesh.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == JHARKHAND.lower(): categoryDict = Hindi_Jharkhand.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BIHAR.lower(): categoryDict = Hindi_Bihar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == HARYANA.lower(): categoryDict = Hindi_Haryana.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == CHATTISGARH.lower(): categoryDict = Hindi_Chattisgarh.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == RAJASTHAN.lower(): categoryDict = Hindi_Rajasthan.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == WESTBENGAL.lower(): categoryDict = Hindi_WestBengal.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == ORISSA.lower(): categoryDict = Hindi_Orissa.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == GUJRAT.lower(): categoryDict = Hindi_Gujrat.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == MAHARASHTRA.lower(): categoryDict = Hindi_Maharashtra.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == LUCKNOW.lower(): categoryDict = Hindi_Lucknow.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == ALLAHABAD.lower(): categoryDict = Hindi_Allahabad.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == PRATAPGARH.lower(): categoryDict = Hindi_Pratapgarh.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == KANPUR.lower(): categoryDict = Hindi_Kanpur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == MERATH.lower(): categoryDict = Hindi_Merath.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == AGRA.lower(): categoryDict = Hindi_Agra.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == NOIDA.lower(): categoryDict = Hindi_Noida.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == GAZIABAD.lower(): categoryDict = Hindi_Gaziabad.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BAGPAT.lower(): categoryDict = Hindi_Bagpat.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SAHARNPUR.lower(): categoryDict = Hindi_Saharnpur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BULANDSHAHAR.lower(): categoryDict = Hindi_Bulandshahar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == VARANASI.lower(): categoryDict = Hindi_Varanasi.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == GORAKHPUR.lower(): categoryDict = Hindi_Gorakhpur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == JHANSI.lower(): categoryDict = Hindi_Jhansi.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == MUZAFFARNAGAR.lower(): categoryDict = Hindi_Muzaffarnagar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SITAPUR.lower(): categoryDict = Hindi_Sitapur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == JAUNPUR.lower(): categoryDict = Hindi_Jaunpur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == AZAMGARH.lower(): categoryDict = Hindi_Azamgarh.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == MORADABAD.lower(): categoryDict = Hindi_Moradabad.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BAREILLY.lower(): categoryDict = Hindi_Bareilly.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BALIA.lower(): categoryDict = Hindi_Balia.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == ALIGARH.lower(): categoryDict = Hindi_Aligarh.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == MATHURA.lower(): categoryDict = Hindi_Mathura.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BHOPAL.lower(): categoryDict = Hindi_Bhopal.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == INDORE.lower(): categoryDict = Hindi_Indore.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == GWALIOR.lower(): categoryDict = Hindi_Gwalior.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == JABALPUR.lower(): categoryDict = Hindi_Jabalpur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == UJJAIN.lower(): categoryDict = Hindi_Ujjain.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == RATLAM.lower(): categoryDict = Hindi_Ratlam.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SAGAR.lower(): categoryDict = Hindi_Sagar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == DEWAS.lower(): categoryDict = Hindi_Dewas.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SATNA.lower(): categoryDict = Hindi_Satna.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == REWA.lower(): categoryDict = Hindi_Rewa.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == PATNA.lower(): categoryDict = Hindi_Patna.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BHAGALPUR.lower(): categoryDict = Hindi_Bhagalpur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == MUJAFFARPUR.lower(): categoryDict = Hindi_Mujaffarpur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == GAYA.lower(): categoryDict = Hindi_Gaya.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == DARBHANGA.lower(): categoryDict = Hindi_Darbhanga.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == POORNIYA.lower(): categoryDict = Hindi_Poorniya.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SEWAN.lower(): categoryDict = Hindi_Sewan.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BEGUSARAI.lower(): categoryDict = Hindi_Begusarai.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == KATIHAR.lower(): categoryDict = Hindi_Katihar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == JAIPUR.lower(): categoryDict = Hindi_Jaipur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == UDAIPUR.lower(): categoryDict = Hindi_Udaipur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == JODHPUR.lower(): categoryDict = Hindi_Jodhpur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == AJMER.lower(): categoryDict = Hindi_Ajmer.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BIKANER.lower(): categoryDict = Hindi_Bikaner.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == ALWAR.lower(): categoryDict = Hindi_Alwar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SIKAR.lower(): categoryDict = Hindi_Sikar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == KOTA.lower(): categoryDict = Hindi_Kota.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BHILWARA.lower(): categoryDict = Hindi_Bhilwara.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BHARATPUR.lower(): categoryDict = Hindi_Bharatpur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == CHHATIS.lower(): categoryDict = Hindi_Chhatis.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == RAIPUR.lower(): categoryDict = Hindi_Raipur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BHILAI.lower(): categoryDict = Hindi_Bhilai.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == RAJNANDGAO.lower(): categoryDict = Hindi_Rajnandgao.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == RAIGARH.lower(): categoryDict = Hindi_Raigarh.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == JAGDALPUR.lower(): categoryDict = Hindi_Jagdalpur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == KORVA.lower(): categoryDict = Hindi_Korva.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == RANCHI.lower(): categoryDict = Hindi_Ranchi.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == DHANBAD.lower(): categoryDict = Hindi_Dhanbad.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == JAMSHEDPUR.lower(): categoryDict = Hindi_Jamshedpur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == GIRIDIHI.lower(): categoryDict = Hindi_Giridihi.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == HAZARIBAGH.lower(): categoryDict = Hindi_Hazaribagh.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BOKARO.lower(): categoryDict = Hindi_Bokaro.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == DEHRADUN.lower(): categoryDict = Hindi_Dehradun.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == NAINITAAL.lower(): categoryDict = Hindi_Nainitaal.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == HARIDWAAR.lower(): categoryDict = Hindi_Haridwaar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == ALMORAH.lower(): categoryDict = Hindi_Almorah.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == UDDHAMSINGHNAGAR.lower(): categoryDict = Hindi_UddhamSinghNagar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SIMLA.lower(): categoryDict = Hindi_Simla.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == MANDI.lower(): categoryDict = Hindi_Mandi.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BILASPUR.lower(): categoryDict = Hindi_Bilaspur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == AMRITSAR.lower(): categoryDict = Hindi_Amritsar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == JALANDHAR.lower(): categoryDict = Hindi_Jalandhar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == LUDHIANA.lower(): categoryDict = Hindi_Ludhiana.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == ROPARH.lower(): categoryDict = Hindi_Roparh.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == CHANDIGARH.lower(): categoryDict = Hindi_Chandigarh.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == ROHTAK.lower(): categoryDict = Hindi_Rohtak.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == PANCHKULA.lower(): categoryDict = Hindi_Panchkula.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == AMBALA.lower(): categoryDict = Hindi_Ambala.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == PANIPAT.lower(): categoryDict = Hindi_Panipat.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == GURGAON.lower(): categoryDict = Hindi_Gurgaon.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == HISSAR.lower(): categoryDict = Hindi_Hissar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == JAMMU.lower(): categoryDict = Hindi_Jammu.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SRINAGAR.lower(): categoryDict = Hindi_Srinagar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == POONCH.lower(): categoryDict = Hindi_Poonch.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == KOLKATA.lower(): categoryDict = Hindi_Kolkata.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == JALPAIGURHI.lower(): categoryDict = Hindi_Jalpaigurhi.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == DARJEELING.lower(): categoryDict = Hindi_Darjeeling.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == ASANSOL.lower(): categoryDict = Hindi_Asansol.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SILIGURHI.lower(): categoryDict = Hindi_Siligurhi.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BHUVANESHWAR.lower(): categoryDict = Hindi_Bhuvaneshwar.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == PURI.lower(): categoryDict = Hindi_Puri.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == CUTTACK.lower(): categoryDict = Hindi_Cuttack.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == AHMEDABAD.lower(): categoryDict = Hindi_Ahmedabad.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SURAT.lower(): categoryDict = Hindi_Surat.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == VADODARA.lower(): categoryDict = Hindi_Vadodara.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == MUMBAI.lower(): categoryDict = Hindi_Mumbai.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == NAGPUR.lower(): categoryDict = Hindi_Nagpur.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == PUNE.lower(): categoryDict = Hindi_Pune.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SPORTS.lower(): categoryDict = Hindi_Sports.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == TOP_STORIES.lower(): categoryDict = Hindi_Top_Stories.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == WORLD.lower(): categoryDict = Hindi_World.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == OPINION.lower(): categoryDict = Hindi_Opinion.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == HEALTH.lower(): categoryDict = Hindi_Health.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == LIFESTYLE.lower(): categoryDict = Hindi_Lifestyle.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == ENTERTAINMENT.lower(): categoryDict = Hindi_Entertainment.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == TECHNOLOGY.lower(): categoryDict = Hindi_Technology.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == POLITICS.lower(): categoryDict = Hindi_Politics.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == ENVIRONMENT.lower(): categoryDict = Hindi_Environment.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == TRAVEL.lower(): categoryDict = Hindi_Travel.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == SCIENCE.lower(): categoryDict = Hindi_Science.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == BUSINESS.lower(): categoryDict = Hindi_Business.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == STOCKS.lower(): categoryDict = Hindi_Stocks.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == FOOD.lower(): categoryDict = Hindi_Food.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == WEEKEND.lower(): categoryDict = Hindi_Weekend.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] if category.lower() == FASHION.lower(): categoryDict = Hindi_Fashion.objects.filter(Source = sourceObj).order_by('-Published_Date')[:limit] return parseDateTimeToStringSourceName(categoryDict) def parseDateTimeToString(dictList): thumbStr='Thumbnail' isRepStr='Is_Rep' titleStr='Title' urlStr='URL' summStr='Summary' clusterStr='-Published_Date' sourceStr='Source_id' articleStr='Article_id' idStr='id' pubDateStr='Published_Date' currDateStr = 'Current_Date' newsDictList=[] for rec in dictList: newsDict={} newsDict[thumbStr]=rec.Thumbnail if rec.Is_Rep: newsDict[isRepStr]=1 else: newsDict[isRepStr]=0 newsDict[titleStr]=rec.Title finalUrl = checkForMobileURL(rec.URL,rec.Source_id) newsDict[urlStr]=finalUrl newsDict[summStr]=rec.Summary newsDict[clusterStr]=rec.Cluster_Id newsDict[sourceStr]=rec.Source_id newsDict[articleStr]=rec.Article_id newsDict[idStr]=rec.id articleObj = News_Article.objects.get(id = rec.Article_id) if articleObj.Current_Date - rec.Published_Date < datetime.timedelta(minutes=2) and articleObj.Current_Date - rec.Published_Date >= datetime.timedelta(minutes=0): rec.Published_Date = rec.Published_Date + datetime.timedelta(hours=5,minutes=30) newsDict[pubDateStr]=rec.Published_Date.strftime('%Y-%m-%d %H:%M') newsDictList.append(newsDict) return newsDictList def parseDateTimeToStringSourceName(dictList): thumbStr='Thumbnail' isRepStr='Is_Rep' titleStr='Title' urlStr='URL' summStr='Summary' clusterStr='Cluster_Id' sourceStr='Source_id' sourceStrForNews='Source_id_News' articleStr='Article_id' idStr='id' pubDateStr='Published_Date' currDateStr = 'Current_Date' newsDictList=[] for rec in dictList: newsDict={} newsDict[thumbStr]=rec.Thumbnail if rec.Is_Rep: newsDict[isRepStr]=1 else: newsDict[isRepStr]=0 newsDict[titleStr]=rec.Title finalUrl = checkForMobileURL(rec.URL,rec.Source_id) newsDict[urlStr]=finalUrl newsDict[summStr]=rec.Summary newsDict[clusterStr]=rec.Cluster_Id newsDict[sourceStrForNews] = rec.Source_id sourceObj = News_Source.objects.get(id=rec.Source_id) foundSource = False f=open(SOURCE_MARATHI_FILE,'r') for line in f: marathiSourceLine = line marathiSourceId = marathiSourceLine.split('=')[0] marathiSourceName = marathiSourceLine.split('=')[1] marathiSourceName = marathiSourceName.split('\r\n')[0] if foundSource == False and rec.Source_id == int(marathiSourceId): newsDict[sourceStr]=marathiSourceName foundSource = True f.close() if foundSource == False: newsDict[sourceStr]=sourceObj.Name newsDict[articleStr]=rec.Article_id newsDict[idStr]=rec.id articleObj = News_Article.objects.get(id = rec.Article_id) if articleObj.Current_Date - rec.Published_Date < datetime.timedelta(minutes=3) and articleObj.Current_Date - rec.Published_Date >= datetime.timedelta(minutes=0): rec.Published_Date = rec.Published_Date + datetime.timedelta(hours=5,minutes=30) newsDict[pubDateStr]=rec.Published_Date.strftime('%Y-%m-%d %H:%M') newsDictList.append(newsDict) return newsDictList def __if_number_get_string(number): converted_str = number if isinstance(number, int) or \ isinstance(number, float): converted_str = str(number) return converted_str def get_unicode(strOrUnicode, encoding='utf-8'): strOrUnicode = __if_number_get_string(strOrUnicode) if isinstance(strOrUnicode, unicode): return strOrUnicode return unicode(strOrUnicode, encoding, errors='ignore') def getSimilarTopN(lang): #Send Notifications if lang.lower() == ENGLISH.lower(): categoryDict = TopN_English.objects.filter() if lang.lower() == MARATHI.lower(): categoryDict = TopN_Marathi.objects.filter() if lang.lower() == HINDI.lower(): categoryDict = TopN_Hindi.objects.filter() return parseDateTimeToStringTopN(categoryDict) def parseDateTimeToStringTopN(dictList): thumbStr='Thumbnail' #isRepStr='Is_Rep' titleStr='Title' urlStr='URL' summStr='Summary' #clusterStr='Cluster_Id' sourceStr='Source_id' articleStr='Article_id' idStr='id' pubDateStr='Published_Date' newsDictList=[] for rec in dictList: newsDict={} newsDict[thumbStr]=rec.Thumbnail #if rec.Is_Rep: #newsDict[isRepStr]=1 #else: #newsDict[isRepStr]=0 newsDict[titleStr]=rec.Title newsDict[urlStr]=rec.URL newsDict[summStr]=rec.Summary #newsDict[clusterStr]=rec.Cluster_Id newsDict[sourceStr]=rec.Source_id newsDict[articleStr]=rec.Article_id newsDict[idStr]=rec.id newsDict[pubDateStr]=rec.Published_Date.strftime('%Y-%m-%d %H:%M') newsDictList.append(newsDict) return newsDictList def getSimilarTopNVideo(lang): #Send Notifications if lang.lower() == ENGLISH.lower(): categoryDict = TopN_English_Video.objects.filter() if lang.lower() == MARATHI.lower(): categoryDict = TopN_Marathi_Video.objects.filter() if lang.lower() == HINDI.lower(): categoryDict = TopN_Hindi_Video.objects.filter() return parseDateTimeToStringTopNVideo(categoryDict) def parseDateTimeToStringTopNVideo(dictList): thumbStr='Thumbnail' videoIDStr='VideoId' videoTableIDStr='VideoTableId' titleStr='Title' urlStr='URL' summStr='Summary' #clusterStr='Cluster_Id' sourceStr='Source_id' idStr='id' pubDateStr='Published_Date' newsDictList=[] for rec in dictList: newsDict={} newsDict[idStr]=rec.id newsDict[videoTableIDStr] = rec.Video_id newsDict[videoIDStr]=rec.VideoId newsDict[urlStr]=rec.URL newsDict[titleStr]=rec.Title newsDict[summStr]=rec.Summary newsDict[thumbStr]=rec.Thumbnail newsDict[sourceStr]=rec.Source_id newsDict[pubDateStr]=rec.Published_Date.strftime('%Y-%m-%d %H:%M') newsDictList.append(newsDict) return newsDictList def convertMobileSite(URL,Source_id): mobileURL = URL if URL[7:10]=='www': mobileURL = 'http://m.' + URL[11:] elif Source_id == 30: mobileURL = 'http://m.maharashtratimes.com' + URL[38:] elif Source_id == 153: if URL[7:17] == 'mp.patrika' or URL[7:17] == 'up.patrika': return URL else: mobileURL = 'http://m.' + URL[7:] return mobileURL def checkForMobileURL(URL,Source_id): for mobileURLId in sourceIdForMobileURL: if mobileURLId == Source_id: URL = convertMobileSite(URL,Source_id) for transcodeId in transcode: if transcodeId == Source_id: URL = GOOGLEWEBLIGHT + URL if Source_id == 39: URL = URL.encode("utf-8") return URL <file_sep># -*- coding: utf-8 -*- from googleapiclient.discovery import build from models import * import isodate from django.http import HttpResponse from dateutil import parser from userConstants import * import datetime from django.db.models import Max from django.utils.datastructures import MultiValueDictKeyError from simplejson import dumps import logging logger = logging.getLogger('django') def getChannelForVideo(lang, category): logger.info("Entered getChannelForVideo ") channelList = [] langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) channelObj = Video_Channel.objects.filter(Language=langObj, Category=categoryObj) for i in channelObj: videoDict = {} videoDict['Channel_Id'] = i.Channel_Id videoDict['Source'] = i.Source_id channelList.append(videoDict) logger.info("Exited getChannelForVideo ") return channelList def getVideoData(lang, category, channelList): logger.info("Entered getVideoData ") langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) youtube = build('youtube', 'v3', developerKey='<KEY>') videoList = [] for channelDict in channelList: search_response = youtube.search().list(part="id", type='video', order='date', channelId=channelDict['Channel_Id'], maxResults=MAX_VIDEO_PER_CHANNEL).execute() videoIds = [] for search_result in search_response.get("items", []): if search_result["id"]["kind"] == "youtube#video": videoIds.append(search_result['id']['videoId']) search_response = youtube.videos().list( id=",".join(videoIds), part="id,snippet,contentDetails" ).execute() cnt = 0 for search_result in search_response.get("items", []): dur=isodate.parse_duration(search_result["contentDetails"]["duration"]) videoDict = {} videoDict['language'] = langObj videoDict['category'] = categoryObj videoDict['Video_Id'] = search_result['id'] videoDict['title'] = search_result["snippet"]["title"] videoDict['summary'] = search_result["snippet"]["localized"]['description'] videoDict['thumbnail'] = search_result['snippet']['thumbnails']['high']['url'] videoDict['published'] = search_result["snippet"]["publishedAt"] videoDict['source'] = channelDict['Source'] videoDict['duration'] = str(dur) videoList.append(videoDict) cnt+=1 logger.info("Exited getVideoData ") return videoList def inserNewsVideo(videoList): logger.info("Entered inserNewsVideo ") newsVideoObj = News_Video.objects.all() for videoDict in videoList: found = 0 for item in newsVideoObj: if item.VideoId == videoDict['Video_Id']: found = 1 if found == 0: sourceObj = Video_Source.objects.get(id = videoDict['source']) dt = parser.parse(videoDict['published']) video = News_Video(Language = videoDict['language'], Category = videoDict['category'], VideoId = videoDict['Video_Id'], Title = videoDict['title'], Summary = videoDict['summary'], Thumbnail = videoDict['thumbnail'], Source = sourceObj, Published_Date = dt, Duration = videoDict['duration']) video.save() logger.info("Exited inserNewsVideo ") def insertLangCategoryVideoTable(lang, category, videoObj, maxClusterId, isRep): logger.info("Entered insertLangCategoryVideoTable ") if lang.lower() == ENGLISH.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = English_Top_Stories_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategoryObj = English_Entertainment_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == SPORTS.lower(): langCategoryObj = English_Sports_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == WORLD.lower(): langCategoryObj = English_World_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == BUSINESS.lower(): langCategoryObj = English_Business_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == LIFESTYLE.lower(): langCategoryObj = English_Lifestyle_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == HEALTH.lower(): langCategoryObj = English_Health_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == FASHION.lower(): langCategoryObj = English_Fashion_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == TECHNOLOGY.lower(): langCategoryObj = English_Technology_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == ENVIRONMENT.lower(): langCategoryObj = English_Environment_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == SCIENCE.lower(): langCategoryObj = English_Science_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == FOOD.lower(): langCategoryObj = English_Food_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == MARATHI.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = Marathi_Top_Stories_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == MARATHI.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategoryObj = Marathi_Entertainment_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == MARATHI.lower(): if category.lower() == SPORTS.lower(): langCategoryObj = Marathi_Sports_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = Hindi_Top_Stories_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategoryObj = Hindi_Entertainment_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = Hindi_Business_Video(Cluster_Id = maxClusterId, Video = videoObj, VideoId = videoObj.VideoId, Title = videoObj.Title, Summary = videoObj.Summary, Thumbnail = videoObj.Thumbnail, Source = videoObj.Source, Published_Date = videoObj.Published_Date, Duration = videoObj.Duration, Is_Rep = isRep) langCategoryObj.save() logger.info("Exited insertLangCategoryVideoTable ") def deleteLangCategoryVideoTable(lang, category): logger.info("Entered deleteLangCategoryVideoTable ") if lang.lower() == ENGLISH.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = English_Top_Stories_Video.objects.all().delete() elif category.lower() == ENTERTAINMENT.lower(): langCategoryObj = English_Entertainment_Video.objects.all().delete() elif category.lower() == SPORTS.lower(): langCategoryObj = English_Sports_Video.objects.all().delete() elif category.lower() == WORLD.lower(): langCategoryObj = English_World_Video.objects.all().delete() elif category.lower() == BUSINESS.lower(): langCategoryObj = English_Business_Video.objects.all().delete() elif category.lower() == LIFESTYLE.lower(): langCategoryObj = English_Lifestyle_Video.objects.all().delete() elif category.lower() == HEALTH.lower(): langCategoryObj = English_Health_Video.objects.all().delete() elif category.lower() == FASHION.lower(): langCategoryObj = English_Fashion_Video.objects.all().delete() elif category.lower() == TECHNOLOGY.lower(): langCategoryObj = English_Technology_Video.objects.all().delete() elif category.lower() == ENVIRONMENT.lower(): langCategoryObj = English_Environment_Video.objects.all().delete() elif category.lower() == SCIENCE.lower(): langCategoryObj = English_Science_Video.objects.all().delete() elif category.lower() == FOOD.lower(): langCategoryObj = English_Food_Video.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = Marathi_Top_Stories_Video.objects.all().delete() elif category.lower() == ENTERTAINMENT.lower(): langCategoryObj = Marathi_Entertainment_Video.objects.all().delete() if lang.lower() == HINDI.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = Hindi_Top_Stories_Video.objects.all().delete() elif category.lower() == ENTERTAINMENT.lower(): langCategoryObj = Hindi_Entertainment_Video.objects.all().delete() elif category.lower() == BUSINESS.lower(): langCategoryObj = Hindi_Business_Video.objects.all().delete() logger.info("Exited deleteLangCategoryVideoTable ") def getMaxClusterIdVideo(lang, category): logger.info("Entered getMaxClusterIdVideo ") if lang == ENGLISH: if category.lower() == TOP_STORIES.lower(): maxDict = English_Top_Stories_Video.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ENTERTAINMENT.lower(): maxDict = English_Entertainment_Video.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SPORTS.lower(): maxDict = English_Sports_Video.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == WORLD.lower(): maxDict = English_World_Video.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BUSINESS.lower(): maxDict = English_Business_Video.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == LIFESTYLE.lower(): maxDict = English_Lifestyle_Video.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == HEALTH.lower(): maxDict = English_Health_Video.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == FASHION.lower(): maxDict = English_Fashion_Video.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == TECHNOLOGY.lower(): maxDict = English_Technology_Video.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ENVIRONMENT.lower(): maxDict = English_Environment_Video.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SCIENCE.lower(): maxDict = English_Science_Video.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == FOOD.lower(): maxDict = English_Food_Video.objects.all().aggregate(Max('Cluster_Id')) elif lang == MARATHI: if category.lower() == TOP_STORIES.lower(): maxDict = Marathi_Top_Stories_Video.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ENTERTAINMENT.lower(): maxDict = Marathi_Entertainment_Video.objects.all().aggregate(Max('Cluster_Id')) elif lang == HINDI: if category.lower() == TOP_STORIES.lower(): maxDict = Hindi_Top_Stories_Video.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ENTERTAINMENT.lower(): maxDict = Hindi_Entertainment_Video.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BUSINESS.lower(): maxDict = Hindi_Business_Video.objects.all().aggregate(Max('Cluster_Id')) logger.info("Exited getMaxClusterIdVideo ") return maxDict def getVideoForLanguageCategory(lang,category,deltaHours): logger.info("Entered getVideoForLanguageCategory ") channelList = getChannelForVideo(lang, category) videoList = getVideoData(lang, category, channelList) inserNewsVideo(videoList) langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) deltaDate = datetime.datetime.now() - datetime.timedelta(hours = deltaHours) videoObjAll = News_Video.objects.filter(Language=langObj, Category=categoryObj, Published_Date__gt=deltaDate).order_by('Published_Date') maxDict = getMaxClusterIdVideo(lang,category) if maxDict['Cluster_Id__max'] : maxClusterId = maxDict['Cluster_Id__max'] + 1 else : maxClusterId = 1 deleteLangCategoryVideoTable(lang, category) for videoObj in videoObjAll : insertLangCategoryVideoTable(lang, category, videoObj, maxClusterId, 1) maxClusterId +=1 logger.info("Exited getVideoForLanguageCategory ") def getVideoForCategoryScreen(lang, category, limit, maxClusterId): if lang.lower()==ENGLISH.lower(): if category.lower() == TOP_STORIES.lower(): if maxClusterId: categoryDict = English_Top_Stories_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Top_Stories_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == ENTERTAINMENT.lower(): if maxClusterId: categoryDict = English_Entertainment_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Entertainment_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SPORTS.lower(): if maxClusterId: categoryDict = English_Sports_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Sports_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == WORLD.lower(): if maxClusterId: categoryDict = English_World_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_World_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BUSINESS.lower(): if maxClusterId: categoryDict = English_Business_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Business_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == LIFESTYLE.lower(): if maxClusterId: categoryDict = English_Lifestyle_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Lifestyle_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == HEALTH.lower(): if maxClusterId: categoryDict = English_Health_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Health_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == FASHION.lower(): if maxClusterId: categoryDict = English_Fashion_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Fashion_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == TECHNOLOGY.lower(): if maxClusterId: categoryDict = English_Technology_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Technology_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == ENVIRONMENT.lower(): if maxClusterId: categoryDict = English_Environment_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Environment_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == SCIENCE.lower(): if maxClusterId: categoryDict = English_Science_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Science_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == FOOD.lower(): if maxClusterId: categoryDict = English_Food_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = English_Food_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] elif lang.lower()==MARATHI.lower(): if category.lower() == TOP_STORIES.lower(): if maxClusterId: categoryDict = Marathi_Top_Stories_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Top_Stories_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == ENTERTAINMENT.lower(): if maxClusterId: categoryDict = Marathi_Entertainment_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Marathi_Entertainment_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] elif lang.lower()==HINDI.lower(): if category.lower() == TOP_STORIES.lower(): if maxClusterId: categoryDict = Hindi_Top_Stories_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Top_Stories_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == ENTERTAINMENT.lower(): if maxClusterId: categoryDict = Hindi_Entertainment_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Entertainment_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] if category.lower() == BUSINESS.lower(): if maxClusterId: categoryDict = Hindi_Business_Video.objects.filter(Is_Rep = 1,Cluster_Id__lt=maxClusterId).order_by('-Cluster_Id')[:limit] else: categoryDict = Hindi_Business_Video.objects.filter(Is_Rep = 1).order_by('-Cluster_Id')[:limit] return parseDateTimeToStringVideo(categoryDict) def parseDateTimeToStringVideo(dictList): thumbStr='Thumbnail' isRepStr='Is_Rep' titleStr='Title' VideoIdStr='VideoId' summStr='Summary' clusterStr='Cluster_Id' sourceStr='Source_id' videoStr='Video_id' idStr='id' pubDateStr='Published_Date' durStr = 'Duration' currDateStr = 'Current_Date' newsDictList=[] for rec in dictList: sourceObj = Video_Source.objects.get(id=rec.Source_id) newsDict={} newsDict[thumbStr]=rec.Thumbnail if rec.Is_Rep: newsDict[isRepStr]=1 else: newsDict[isRepStr]=0 newsDict[titleStr]=rec.Title newsDict[VideoIdStr]=rec.VideoId newsDict[summStr]=rec.Summary newsDict[clusterStr]=rec.Cluster_Id newsDict[sourceStr]=sourceObj.Name newsDict[videoStr]=rec.Video_id newsDict[idStr]=rec.id newsDict[durStr]=rec.Duration newsDict[pubDateStr]=rec.Published_Date.strftime('%Y-%m-%d %H:%M') newsDictList.append(newsDict) return newsDictList<file_sep># -*- coding: utf-8 -*- PATH = 'E:/NewsApp/OutputFiles' IMAGEPATH = 'E:/NewsApp/NewsInSight/newsApp/static/images' FONT_PATH_NOTOSANS = 'E:/NewsApp/NewsInSight/newsApp/static/fonts/NotoSans-Regular.ttf' WORDLIST_MARATHI = 'E:/NewsApp/clubbedWordlist/WordList_From_40K_Words_Clubbed.txt' SUMMARY_MARATHI_FILE = 'E:/NewsApp/Marathi_Summary.txt' VIDEO_CATEGORY_FILE = 'E:/NewsApp/video_category.txt' SOURCE_MARATHI_FILE = 'E:/NewsApp/Marathi_Source.txt' SOCIAL_URL_FILE_ENG = "E:/NewsApp/inputClusterFileEng.txt" SOCIAL_URL_FILE_MAR = "E:/NewsApp/inputClusterFileMar.txt" SOCIAL_URL_FILE_HIN = "E:/NewsApp/inputClusterFileHin.txt" TITLES_DICT = 'Titles.dict' TITLES_DICT_MM = 'Titles.mm' CLUSTER_FILE = 'cluster.txt' OUTLIER_FILE = 'outlier.txt' TITLES_ALL = 'Alltitles.txt' TITLES_TOPN_DICT = 'TitlesTopN.dict' TITLES_TOPN_DICT_MM = 'TitlesTopN.mm' TITLES_TOPN_ALL= 'Alltitles.txt' ENGLISH = 'English' MARATHI = 'Marathi' HINDI = 'Hindi' POLITICS = 'Politics' TOPN = 'TopN' ECONOMY = 'Economy' SPORTS = 'Sports' TOP_STORIES = 'Top Stories' WORLD = 'World' OPINION = 'Opinion' HEALTH = 'Health' LIFESTYLE = 'Lifestyle' ENTERTAINMENT = 'Entertainment' TECHNOLOGY = 'Technology' ENVIRONMENT = 'Environment' BOOKS = 'Books' TRAVEL = 'Travel' SCIENCE = 'Science' BUSINESS = 'Business' STOCKS = 'Stocks' FOOD = 'Food' WEEKEND = 'Weekend' FASHION = 'Fashion' MUMBAI = 'Mumbai' PUNE = 'Pune' NAGPUR = 'Nagpur' NASIK = 'Nasik' AURANGABAD = 'Aurangabad' SOLAPUR = 'Solapur' KOLHAPUR = 'Kolhapur' SATARA = 'Satara' SANGLI = 'Sangli' AKOLA = 'Akola' AHMEDNAGAR = 'Ahmednagar' JALGAON = 'Jalgaon' GOA = 'Goa' CHANDRAPUR = 'Chandrapur' WARDHA = 'Wardha' MAHARASHTRA = 'Maharashtra' UTTARPRADESH = "UttarPradesh" UTTARAKHAND = "Uttarakhand" HIMACHALPRADESH = "HimachalPradesh" DELHI = "Delhi" JAMMUKASHMIR = "JammuKashmir" PUNJAB = "Punjab" MADHYAPRADESH = "MadhyaPradesh" JHARKHAND = "Jharkhand" BIHAR = "Bihar" HARYANA = "Haryana" CHATTISGARH = "Chattisgarh" RAJASTHAN = "Rajasthan" WESTBENGAL = "WestBengal" ORISSA = "Orissa" GUJRAT = "Gujrat" LUCKNOW = "Lucknow" ALLAHABAD = "Allahabad" PRATAPGARH = "Pratapgarh" KANPUR = "Kanpur" MERATH = "Merath" AGRA = "Agra" NOIDA = "Noida" GAZIABAD = "Gaziabad" BAGPAT = "Bagpat" SAHARNPUR = "Saharnpur" BULANDSHAHAR = "Bulandshahar" VARANASI = "Varanasi" GORAKHPUR = "Gorakhpur" JHANSI = "Jhansi" MUZAFFARNAGAR = "Muzaffarnagar" SITAPUR = "Sitapur" JAUNPUR = "Jaunpur" AZAMGARH = "Azamgarh" MORADABAD = "Moradabad" BAREILLY = "Bareilly" BALIA = "Balia" ALIGARH = "Aligarh" MATHURA = "Mathura" BHOPAL = "Bhopal" INDORE = "Indore" GWALIOR = "Gwalior" JABALPUR = "Jabalpur" UJJAIN = "Ujjain" RATLAM = "Ratlam" SAGAR = "Sagar" DEWAS = "Dewas" SATNA = "Satna" REWA = "Rewa" PATNA = "Patna" BHAGALPUR = "Bhagalpur" MUJAFFARPUR = "Mujaffarpur" GAYA = "Gaya" DARBHANGA = "Darbhanga" POORNIYA = "Poorniya" SEWAN = "Sewan" BEGUSARAI = "Begusarai" KATIHAR = "Katihar" JAIPUR = "Jaipur" UDAIPUR = "Udaipur" JODHPUR = "Jodhpur" AJMER = "Ajmer" BIKANER = "Bikaner" ALWAR = "Alwar" SIKAR = "Sikar" KOTA = "Kota" BHILWARA = "Bhilwara" BHARATPUR = "Bharatpur" CHHATIS = "Chhatis" RAIPUR = "Raipur" BILASPUR = "Bilaspur" BHILAI = "Bhilai" RAJNANDGAO = "Rajnandgao" RAIGARH = "Raigarh" JAGDALPUR = "Jagdalpur" KORVA = "Korva" RANCHI = "Ranchi" DHANBAD = "Dhanbad" JAMSHEDPUR = "Jamshedpur" GIRIDIHI = "Giridihi" HAZARIBAGH = "Hazaribagh" BOKARO = "Bokaro" DEHRADUN = "Dehradun" NAINITAAL = "Nainitaal" HARIDWAAR = "Haridwaar" ALMORAH = "Almorah" UDDHAMSINGHNAGAR = "UddhamSinghNagar" SIMLA = "Simla" MANDI = "Mandi" AMRITSAR = "Amritsar" JALANDHAR = "Jalandhar" LUDHIANA = "Ludhiana" ROPARH = "Roparh" CHANDIGARH = "Chandigarh" ROHTAK = "Rohtak" PANCHKULA = "Panchkula" AMBALA = "Ambala" PANIPAT = "Panipat" GURGAON = "Gurgaon" HISSAR = "Hissar" JAMMU = "Jammu" SRINAGAR = "Srinagar" POONCH = "Poonch" KOLKATA = "Kolkata" JALPAIGURHI = "Jalpaigurhi" DARJEELING = "Darjeeling" ASANSOL = "Asansol" SILIGURHI = "Siligurhi" BHUVANESHWAR = "Bhuvaneshwar" PURI = "Puri" CUTTACK = "Cuttack" AHMEDABAD = "Ahmedabad" SURAT = "Surat" VADODARA = "Vadodara" CRIME = "Crime" AUTO = "Auto" FARIDABAD = 'Faridabad' GOOGLE_EN = 'en' GOOGLE_MR = 'mr' GOOGLE_HI = 'hi' DELTA_DAYS_ONE = 1 DELTA_DAYS_TWO = 2 DELTA_DAYS_THREE = 3 DELTA_DAYS_SEVEN = 7 SIMILARITY_THRASHOLD = 0.6 HOME_ARTICLE_LIMIT=3 CATEGORY_ARTICLE_LIMIT=10 CATEGORY_SOURCE_LIMIT=15 CATEGORY_VIDEO_LIMIT =10 SIMILAR_ARTICLE_LIMIT=5 DELTA_HOURS_TWELVE = 12 DELTA_HOURS_TWENTY_FOUR = 24 DELTA_HOURS_FOURTY_EIGHT = 48 DELTA_HOURS_ONE_SIXTY_EIGHT = 168 DELTA_HOURS_THREE_SIXTY = 360 MAX_VIDEO_PER_CHANNEL = 10 IBN_PLUS = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" SUMMARY = "Read more" SUMMARY_MARATHI = '???? ????' SUMMARY_HINDI = '???? ?????' MAHARASHTRA_TIMES_AD = 'http://ade.clmbtech.com/' LDPI = "LDPI" MDPI = "MDPI" HDPI = "HDPI" XDPI = "XDPI" TEMP = "Temp" BG = 'BG' videoLangCatList =[] dictEngTop={} dictEngTop['lang'] = 'English' dictEngTop['category'] = 'Top Stories' videoLangCatList.append(dictEngTop) dictEngEnter = {} dictEngEnter['lang'] = 'English' dictEngEnter['category'] = 'Entertainment' videoLangCatList.append(dictEngEnter) dictEngSport={} dictEngSport['lang'] = 'English' dictEngSport['category'] = 'Sports' videoLangCatList.append(dictEngSport) dictMarTop={} dictMarTop['lang'] = 'Marathi' dictMarTop['category'] = 'Top Stories' videoLangCatList.append(dictMarTop) dictMarEnter = {} dictMarEnter['lang'] = 'Marathi' dictMarEnter['category'] = 'Entertainment' videoLangCatList.append(dictMarEnter) dictEng={} dictEng['lang'] = 'English' dictEng['category'] = 'World' videoLangCatList.append(dictEng) dictEng={} dictEng['lang'] = 'English' dictEng['category'] = 'Business' videoLangCatList.append(dictEng) dictEng={} dictEng['lang'] = 'English' dictEng['category'] = 'Lifestyle' videoLangCatList.append(dictEng) dictEng={} dictEng['lang'] = 'English' dictEng['category'] = 'Health' videoLangCatList.append(dictEng) dictEng={} dictEng['lang'] = 'English' dictEng['category'] = 'Fashion' videoLangCatList.append(dictEng) dictEng={} dictEng['lang'] = 'English' dictEng['category'] = 'Technology' videoLangCatList.append(dictEng) dictEng={} dictEng['lang'] = 'English' dictEng['category'] = 'Environment' videoLangCatList.append(dictEng) dictEng={} dictEng['lang'] = 'English' dictEng['category'] = 'Science' videoLangCatList.append(dictEng) dictEng={} dictEng['lang'] = 'English' dictEng['category'] = 'Food' videoLangCatList.append(dictEng) dictEng={} dictEng['lang'] = 'Hindi' dictEng['category'] = 'Top Stories' videoLangCatList.append(dictEng) dictEng={} dictEng['lang'] = 'Hindi' dictEng['category'] = 'Entertainment' videoLangCatList.append(dictEng) dictEng={} dictEng['lang'] = 'Hindi' dictEng['category'] = 'Business' videoLangCatList.append(dictEng) sourceIdForMobileURL = [29,108,51,35,117,153,140,28,131] transcode = [10,39,47,61,63,65,66,67,71,73,76,78,81,84,87,88,96,100,102,109,112,126,137,145] GOOGLEWEBLIGHT = 'http://googleweblight.com/?lite_url=' articleSourceName =[ 'IB Times','Digit','Blog To Bollywood','FilmiBeat','Mid Day', 'ANI','Bold Sky','Travelmasti','News Nation','Travel Daily Media','Firstpost','New Kerela','Cricket Country', 'Daily Climate','Amar Ujala','Bhaskar','Patrika','Jagran Hindi','Navbharat Times','Nai Duniya', 'Rajasthan Patrika','Pratah Kal','Prabhat Khabar','Ranchi Express','DeshBandhu','Jansatta','ABP News', 'Aaj Tak','ZeeNews Hindi','WebDuniya Hindi','Live Hindustan','Zeenews Hindi','Salt Peperica' ]<file_sep>from django.contrib import admin from django.contrib.auth.models import User from django.db import models from django.forms import ModelForm from random import randint from django.utils import timezone # Create your models here. class News_Source(models.Model): Name = models.CharField(max_length=70) def __unicode__(self): return '%s' % (self.Name) class Language(models.Model): Name = models.CharField(max_length=15) def __unicode__(self): return '%s' % (self.Name) class News_Category(models.Model): Name = models.CharField(max_length=20) def __unicode__(self): return '%s' % (self.Name) class News_Feed(models.Model): Language = models.ForeignKey(Language) Category = models.ForeignKey(News_Category) URL = models.URLField(max_length=1000) Source = models.ForeignKey(News_Source) Type = models.CharField(max_length=20,default='JSON') def __unicode__(self): return '%s %s %s %s' % (self.Language,self.Category,self.URL,self.Source) class Video_Source(models.Model): Name = models.CharField(max_length=70) def __unicode__(self): return '%s' % (self.Name) class Video_Channel(models.Model): Language = models.ForeignKey(Language) Category = models.ForeignKey(News_Category) Channel_Id = models.CharField(max_length=100) Source = models.ForeignKey(Video_Source) def __unicode__(self): return '%s %s %s' % (self.Language,self.Category,self.Source) class News_Article_Archive(models.Model): Language = models.ForeignKey(Language,db_index=True) Category = models.ForeignKey(News_Category,db_index=True) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Current_Date=models.DateTimeField() Archive_Date=models.DateTimeField(auto_now_add=True) Is_New = models.BooleanField(default=False) Cluster_Id = models.IntegerField(db_index=True) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Language,self.Category,self.URL) class News_Article(models.Model): Language = models.ForeignKey(Language,db_index=True) Category = models.ForeignKey(News_Category,db_index=True) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Current_Date=models.DateTimeField(auto_now_add=True) Is_New = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Language,self.Category,self.URL) class TopN_News_Article(models.Model): Language = models.ForeignKey(Language) Category = models.ForeignKey(News_Category) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() def __unicode__(self): return '%s %s %s' % (self.Language,self.URL,self.Source,self.Title) class TopN_English(models.Model): Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class TopN_Marathi(models.Model): Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class TopN_Hindi(models.Model): Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class News_Video(models.Model): Language = models.ForeignKey(Language,db_index=True) Category = models.ForeignKey(News_Category,db_index=True) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date= models.DateTimeField() Current_Date = models.DateTimeField(auto_now_add=True) Duration = models.CharField(max_length=50) def __unicode__(self): return '%s %s %s' % (self.Language,self.Category,self.URL) class TopN_English_Video(models.Model): Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class TopN_Marathi_Video(models.Model): Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class TopN_Hindi_Video(models.Model): Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Economy_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s ' % (self.Title,self.URL,self.Source) class English_Sports_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Top_Stories_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_World_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Opinion_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Health_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Lifestyle_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Entertainment_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Technology_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Politics_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s ' % (self.Title,self.URL,self.Source) class English_Environment_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Books_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Travel_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Science_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Business_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Stocks_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Food_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Weekend_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Fashion_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Mumbai_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Pune_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Politics(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s ' % (self.Title,self.URL,self.Source) class English_Economy(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Sports(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Top_Stories(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_World(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Opinion(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Health(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Lifestyle(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Entertainment(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Technology(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Environment(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Books(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Travel(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Science(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Business(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Stocks(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Food(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Weekend(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Fashion(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Mumbai(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Pune(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Top_Stories_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Entertainment_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Sports_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_World_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Business_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Lifestyle_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Health_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Fashion_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Technology_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Environment_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Science_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class English_Food_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Top_Stories_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Entertainment_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Business_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_UttarPradesh(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Uttarakhand(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_HimachalPradesh(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Delhi(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_JammuKashmir(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Punjab(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_MadhyaPradesh(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Jharkhand(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Bihar(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Haryana(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Chattisgarh(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Rajasthan(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_WestBengal(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Orissa(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Gujrat(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Maharashtra(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Lucknow(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Allahabad(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Pratapgarh(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Kanpur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Merath(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Agra(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Noida(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Gaziabad(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Bagpat(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Saharnpur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Bulandshahar(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Varanasi(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Gorakhpur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Jhansi(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Muzaffarnagar(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Sitapur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Jaunpur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Azamgarh(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Moradabad(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Faridabad(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Bareilly(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Balia(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Aligarh(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Mathura(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Bhopal(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Indore(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Gwalior(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Jabalpur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Ujjain(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Ratlam(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Sagar(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Dewas(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Satna(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Rewa(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Patna(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Bhagalpur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Mujaffarpur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Gaya(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Darbhanga(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Poorniya(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Sewan(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Begusarai(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Katihar(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Jaipur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Udaipur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Jodhpur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Ajmer(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Bikaner(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Alwar(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Sikar(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Kota(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Bhilwara(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Bharatpur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Chhatis(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Raipur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Bilaspur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Bhilai(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Rajnandgao(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Raigarh(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Jagdalpur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Korva(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Ranchi(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Dhanbad(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Jamshedpur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Giridihi(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Hazaribagh(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Bokaro(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Dehradun(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Nainitaal(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Haridwaar(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Almorah(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_UddhamSinghNagar(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Simla(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Mandi(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Amritsar(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Jalandhar(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Ludhiana(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Roparh(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Chandigarh(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Rohtak(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Panchkula(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Ambala(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Panipat(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Gurgaon(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Hissar(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Jammu(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Srinagar(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Poonch(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Kolkata(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Jalpaigurhi(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Darjeeling(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Asansol(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Siligurhi(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Bhuvaneshwar(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Puri(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Cuttack(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Ahmedabad(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Surat(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Vadodara(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Mumbai(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Nagpur(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Pune(models.Model): Cluster_Id = models.IntegerField() Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=200) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Economy_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s ' % (self.Title,self.URL,self.Source) class Hindi_Sports_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Top_Stories_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_World_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Opinion_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Health_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Lifestyle_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Entertainment_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Technology_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Politics_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s ' % (self.Title,self.URL,self.Source) class Hindi_Environment_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Travel_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Science_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Business_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Stocks_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Food_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Weekend_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Fashion_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Politics(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s ' % (self.Title,self.URL,self.Source) class Hindi_Economy(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Sports(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Top_Stories(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_World(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Opinion(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Health(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Lifestyle(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Entertainment(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Technology(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Environment(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Books(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Travel(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Science(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Business(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Stocks(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Food(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Weekend(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Fashion(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Crime(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Hindi_Auto(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Economy(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Sports(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Top_Stories(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_World(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Opinion(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Health(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Lifestyle(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Entertainment(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Technology(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Politics(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Environment(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Books(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Travel(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Science(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Business(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Stocks(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Food(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Weekend(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Fashion(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Mumbai(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Pune(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Nagpur(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Nasik(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Aurangabad(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Solapur(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Kolhapur(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Satara(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Sangli(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Akola(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Ahmednagar(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Jalgaon(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Goa(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Chandrapur(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Wardha(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Maharashtra(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Economy_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Sports_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Top_Stories_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_World_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Opinion_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Health_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Lifestyle_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Entertainment_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Technology_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Politics_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Environment_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Books_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Travel_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Science_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Business_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Stocks_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Food_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Weekend_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Fashion_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Mumbai_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Pune_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Nagpur_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Nasik_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Aurangabad_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Solapur_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Kolhapur_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Satara_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Sangli_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Akola_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Ahmednagar_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Jalgaon_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Goa_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Chandrapur_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Wardha_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Maharashtra_Rerun(models.Model): Cluster_Id = models.IntegerField(db_index=True) Article = models.ForeignKey(News_Article) URL = models.URLField(max_length=300) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(News_Source) Published_Date=models.DateTimeField() Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Top_Stories_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Entertainment_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) class Marathi_Sports_Video(models.Model): Cluster_Id = models.IntegerField(db_index=True) Video = models.ForeignKey(News_Video) VideoId = models.CharField(max_length=100) Title = models.CharField(max_length=100) Summary = models.CharField(max_length=300) Thumbnail = models.URLField(max_length=300,null=True,blank=True) Source = models.ForeignKey(Video_Source) Published_Date=models.DateTimeField() Duration = models.CharField(max_length=50) Is_Rep = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s' % (self.Title,self.URL,self.Source) <file_sep>import urllib2 from bs4 import BeautifulSoup import re import requests def scrapeComments(url,sourceId): html = urllib2.urlopen(url, None, 10) soup = BeautifulSoup(html) str1 = 'http://vuukle.com/api.asmx/getCommentCountListByHost?id=' str2 = '&host=' str3 = '&list=' if sourceId == 1: i = soup.find_all("a", {"class":"comment"}) for item in i: finalStr = str(item) urlid = int(finalStr[32:39]) finalDict = { 'website': 'indianexpress.com', 'api' : '2e5a47ef-15f6-4eec-a685-65a6d0ed00d0', 'id': urlid, } urlString = str1 + finalDict['api'] + str2 + finalDict['website'] + str3 + finalDict['id'] return urlString,'yuucle' elif sourceId == 27: website = 'loksatta.com' x= soup(text=re.compile('create_vuukle_platform')) for item in x: y = item.lstrip() z = y.split("'") finalDict = { 'website': website, 'api' : str(z[1]), 'id': int(z[3]), } urlString = str1 + finalDict['api'] + str2 + finalDict['website'] + str3 + finalDict['id'] return urlString,'yuucle' elif sourceId == 107: website = 'bhaskar.com' x= soup(text=re.compile('create_vuukle_platform')) for item in x: y = item.lstrip() z = y.split("'") finalDict = { 'website': website, 'api' : str(z[3]), 'id': int(z[5]), } urlString = str1 + finalDict['api'] + str2 + finalDict['website'] + str3 + finalDict['id'] return urlString,'yuucle' elif sourceId == 35: website = 'indiatvnews.com' x= soup(text=re.compile('UNIQUE_ARTICLE_ID ')) for item in x: y = item.lstrip() z = y.split('"') finalDict = { 'website': website, 'api' : str(z[9]), 'id': str(z[1]), } urlString = str1 + finalDict['api'] + str2 + finalDict['website'] + str3 + finalDict['id'] return urlString,'yuucle' elif sourceId == 131: website = 'amarujala.com' x= soup(text=re.compile('create_vuukle_platform')) for item in x: y = item.lstrip() z = y.split('"') finalDict = { 'website': website, 'api' : str(z[1]), 'id': str(z[3]), } urlString = str1 + finalDict['api'] + str2 + finalDict['website'] + str3 + finalDict['id'] return urlString,'yuucle' elif sourceId == 135: website = 'livehindustan.com' x= soup(text=re.compile('create_vuukle_platform')) for item in x: y = item.lstrip() z = y.split("'") finalDict = { 'website': website, 'api' : str(z[1]), 'id': str(z[3]), } urlString = str1 + finalDict['api'] + str2 + finalDict['website'] + str3 + finalDict['id'] return urlString,'yuucle' elif sourceId == 134: website = 'aajtak.intoday.in' x= soup(text=re.compile('UNIQUE_ARTICLE_ID')) for item in x: y = item.lstrip() z = y.split('"') finalDict = { 'website': website, 'api' : 'dc34b5cc-453d-468a-96ae-075a66cd9eb7', 'id': str(z[1]), } urlString = str1 + finalDict['api'] + str2 + finalDict['website'] + str3 + finalDict['id'] return urlString,'yuucle' elif sourceId == 150: website = 'abpnews.abplive.in' x= soup(text=re.compile('create_vuukle_platform')) for item in x: y = item.lstrip() z = y.split('"') finalDict = { 'website': website, 'api' : '454859d8-ee0d-4f40-a92e-808c968122ea', 'id': str(z[1]), } urlString = str1 + finalDict['api'] + str2 + finalDict['website'] + str3 + finalDict['id'] return urlString,'yuucle' elif sourceId == 32: website = 'abpmajha.abplive.in' x= soup(text=re.compile('create_vuukle_platform')) for item in x: y = item.lstrip() z = y.split('"') finalDict = { 'website': website, 'api' : '454859d8-ee0d-4f40-a92e-808c968122ea', 'id': str(z[1]), } urlString = str1 + finalDict['api'] + str2 + finalDict['website'] + str3 + finalDict['id'] return urlString,'yuucle' elif sourceId == 3: string1 = 'http://disqus.com/embed/comments/?base=default&version=7ff52449a33b7f7845efccc7ceb593f0' string2 = '&f=firstpost' string3 = '&t_i=' #x= soup(text=re.compile('data-disqus-identifier')) x = soup.findAll("a", {"class":"cmntsNum"}) for item in x: string4 = string1 + string2 + string3 + item['data-disqus-identifier'] + '&t_u=' + url return string4,'discus' elif sourceId == 40: string1 = 'http://disqus.com/embed/comments/?base=default&version=7ff52449a33b7f7845efccc7ceb593f0' string2 = '&f=zeenews' string3 = '&t_i=' #x= soup(text=re.compile('data-disqus-identifier')) #print soup x = soup.findAll("a", {"class":"disqus-comment-count"}) for item in x: string4 = string1 + string2 + string3 + item['data-disqus-identifier'] + '&t_u=' + url return string4,'discus' elif sourceId == 114: string1 = 'http://www.hindustantimes.com/fragment/PortalConfig/www.hindustantimes.com/jpt/custom/disqusapi.jpt?thread=' string4 = string1 + url return string4,'yuucle' elif sourceId == 2: x = soup.findAll("iframe", {"id":"article-comment-frame"}) for item in x: y = item['data-original'] string1 = 'http://www.business-standard.com' finalUrl = string1 + y print finalUrl return finalUrl,'iframe' def scrape4comments(url,sourceid): try: urlString,identifier = scrapeComments(url,sourceid) if identifier =='yuucle': r= requests.get(urlString) wjson = r.json() return wjson elif identifier =='discus': html = urllib2.urlopen(urlString, None, 10) soup = BeautifulSoup(html) x= soup(text=re.compile('"total"')) z = x[0].split('"total"')[1].split(":")[1].split(",")[0] return z elif identifier == 'iframe': html = urllib2.urlopen(urlString, None, 10) soup = BeautifulSoup(html) x = soup.findAll("span", {"class":"comment-num"}) for item in x : return item.h2.string except: return 0 <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('newsApp', '0006_auto_20160128_1738'), ] operations = [ migrations.CreateModel( name='News_Feed1', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('URL', models.URLField(max_length=500)), ('Type', models.CharField(default=b'RSS 2.0', max_length=20)), ('Category', models.ForeignKey(to='newsApp.News_Category')), ('Language', models.ForeignKey(to='newsApp.Language')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.AlterField( model_name='news_feed', name='URL', field=models.URLField(max_length=500), ), ] <file_sep>from newsApp.Utils import * from newsApp.youtube import * from newsApp.userConstants import * import logging logger = logging.getLogger('django_crontab') def my_scheduled_job_daily(): try: clusterOnLanguageCategory(MARATHI,TOP_STORIES,DELTA_HOURS_TWELVE) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,TOP_STORIES,DELTA_HOURS_TWELVE) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,MAHARASHTRA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,ENTERTAINMENT,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,ENTERTAINMENT,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,SPORTS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(MARATHI,SPORTS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,OPINION,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(MARATHI,WORLD,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,MUMBAI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,PUNE,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,NAGPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,NASIK,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,AURANGABAD,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,SOLAPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,KOLHAPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,SATARA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,SANGLI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,AKOLA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,AHMEDNAGAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,JALGAON,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,GOA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,CHANDRAPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,WARDHA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,POLITICS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,WORLD,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,ECONOMY,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,HEALTH,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,LIFESTYLE,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,TECHNOLOGY,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,ENVIRONMENT,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,TRAVEL,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,SCIENCE,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,BUSINESS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,STOCKS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(ENGLISH,FOOD,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,FASHION,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,HEALTH,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,LIFESTYLE,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,BUSINESS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(ENGLISH,OPINION,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(ENGLISH,MUMBAI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(ENGLISH,PUNE,DELTA_DAYS_ONE) except Exception, e: logger.exception("You have an exception :%s",e.args) try: socialIndicators(ENGLISH,TOP_STORIES) except Exception, e: logger.exception("You have an exception :%s",e.args) try: socialIndicators(MARATHI,TOP_STORIES) except Exception, e: logger.exception("You have an exception :%s",e.args) try: socialIndicators(HINDI,TOP_STORIES) except Exception, e: logger.exception("You have an exception :%s",e.args) def my_schedule_job_video_daily(): try: getVideoForLanguageCategory(ENGLISH,TOP_STORIES,DELTA_HOURS_TWELVE) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(MARATHI,TOP_STORIES,DELTA_HOURS_TWELVE) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(HINDI,TOP_STORIES,DELTA_HOURS_TWELVE) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(MARATHI,ENTERTAINMENT,DELTA_HOURS_THREE_SIXTY) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(ENGLISH,ENTERTAINMENT,DELTA_HOURS_THREE_SIXTY) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(ENGLISH,SPORTS,DELTA_HOURS_THREE_SIXTY) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(ENGLISH,WORLD,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(ENGLISH,BUSINESS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(ENGLISH,LIFESTYLE,DELTA_HOURS_THREE_SIXTY) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(ENGLISH,HEALTH,DELTA_HOURS_THREE_SIXTY) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(ENGLISH,FASHION,DELTA_HOURS_THREE_SIXTY) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(ENGLISH,TECHNOLOGY,DELTA_HOURS_THREE_SIXTY) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(ENGLISH,ENVIRONMENT,DELTA_HOURS_THREE_SIXTY) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(ENGLISH,SCIENCE,DELTA_HOURS_THREE_SIXTY) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(ENGLISH,FOOD,DELTA_HOURS_THREE_SIXTY) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(HINDI,ENTERTAINMENT,DELTA_HOURS_THREE_SIXTY) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(HINDI,BUSINESS,DELTA_HOURS_THREE_SIXTY) except Exception, e: logger.exception("You have an exception :%s",e.args) def my_scheduled_job_hourly(): try: clusterWithNewDocument(ENGLISH,STOCKS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(ENGLISH,BUSINESS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(ENGLISH,ENTERTAINMENT,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,ENTERTAINMENT,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,MAHARASHTRA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(MARATHI,SPORTS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(MARATHI,WORLD,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(ENGLISH,POLITICS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(ENGLISH,WORLD,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(ENGLISH,ECONOMY,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(ENGLISH,SPORTS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(ENGLISH,OPINION,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,OPINION,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(ENGLISH,HEALTH,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(ENGLISH,LIFESTYLE,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(ENGLISH,TECHNOLOGY,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(ENGLISH,ENVIRONMENT,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(ENGLISH,TRAVEL,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(ENGLISH,SCIENCE,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(ENGLISH,FOOD,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterWithNewDocument(ENGLISH,FASHION,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,HEALTH,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,LIFESTYLE,DELTA_HOURS_FOURTY_EIGHT) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,BUSINESS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(ENGLISH,MUMBAI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(ENGLISH,PUNE,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,MUMBAI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,PUNE,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,NAGPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,NASIK,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,AURANGABAD,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,SOLAPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,KOLHAPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,SATARA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,SANGLI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,AKOLA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,AHMEDNAGAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,JALGAON,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,GOA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,CHANDRAPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(MARATHI,WARDHA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) def my_scheduled_job_TopN(): try: createTopN(MARATHI) except Exception, e: logger.exception("You have an exception :%s",e.args) try: createTopN(ENGLISH) except Exception, e: logger.exception("You have an exception :%s",e.args) try: createTopN(HINDI) except Exception, e: logger.exception("You have an exception :%s",e.args) def my_scheduled_job_delete_TopN(): try: deleteLangCategoryTable(ENGLISH, TOPN) except Exception, e: logger.exception("You have an exception :%s",e.args) try: deleteLangCategoryTable(MARATHI, TOPN) except Exception, e: logger.exception("You have an exception :%s",e.args) def my_scheduled_job_delete_article(): try: deleteArticleTable(DELTA_DAYS_SEVEN) except Exception, e: logger.exception("You have an exception :%s",e.args) def my_scheduled_job_Top_News(): try: clusterOnLanguageCategory(MARATHI,TOP_STORIES,DELTA_HOURS_TWELVE) except Exception, e: logger.exception("You have an exception :%s",e.args) try: sortForRep(MARATHI,TOP_STORIES) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(ENGLISH,TOP_STORIES,DELTA_HOURS_TWELVE) except Exception, e: logger.exception("You have an exception :%s",e.args) try: sortForRep(ENGLISH,TOP_STORIES) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(HINDI,TOP_STORIES,DELTA_HOURS_TWELVE) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(ENGLISH,TOP_STORIES,DELTA_HOURS_TWELVE) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(MARATHI,TOP_STORIES,DELTA_HOURS_TWELVE) except Exception, e: logger.exception("You have an exception :%s",e.args) try: getVideoForLanguageCategory(HINDI,TOP_STORIES,DELTA_HOURS_TWELVE) except Exception, e: logger.exception("You have an exception :%s",e.args) try: socialIndicators(ENGLISH,TOP_STORIES) except Exception, e: logger.exception("You have an exception :%s",e.args) try: socialIndicators(MARATHI,TOP_STORIES) except Exception, e: logger.exception("You have an exception :%s",e.args) try: socialIndicators(HINDI,TOP_STORIES) except Exception, e: logger.exception("You have an exception :%s",e.args) def my_scheduled_job_Hindi(): try: clusterOnLanguageCategory(HINDI,SPORTS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(HINDI,WORLD,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,OPINION,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,HEALTH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,LIFESTYLE,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,ENTERTAINMENT,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,TECHNOLOGY,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,AUTO,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,POLITICS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,TRAVEL,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,SCIENCE,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BUSINESS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: clusterOnLanguageCategory(HINDI,FASHION,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,CRIME,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,UTTARPRADESH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,UTTARAKHAND,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,HIMACHALPRADESH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,DELHI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,JAMMUKASHMIR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,PUNJAB,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,MADHYAPRADESH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,JHARKHAND,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BIHAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,HARYANA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,CHATTISGARH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,RAJASTHAN,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,WESTBENGAL,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,ORISSA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,GUJRAT,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,MAHARASHTRA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,LUCKNOW,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,ALLAHABAD,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,PRATAPGARH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,KANPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,MERATH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,AGRA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,NOIDA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,GAZIABAD,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BAGPAT,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,SAHARNPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BULANDSHAHAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,VARANASI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,GORAKHPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,JHANSI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,MUZAFFARNAGAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,SITAPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,JAUNPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,AZAMGARH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,MORADABAD,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BAREILLY,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BALIA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,ALIGARH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,MATHURA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BHOPAL,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,INDORE,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,GWALIOR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,JABALPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,UJJAIN,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,RATLAM,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,SAGAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,DEWAS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,SATNA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,REWA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,PATNA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BHAGALPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,MUJAFFARPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,GAYA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,DARBHANGA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,POORNIYA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,SEWAN,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BEGUSARAI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,KATIHAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,JAIPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,UDAIPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,JODHPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,AJMER,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BIKANER,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,ALWAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,SIKAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,KOTA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BHILWARA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BHARATPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,CHHATIS,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,RAIPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BHILAI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,RAJNANDGAO,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,RAIGARH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,JAGDALPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,KORVA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,RANCHI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,DHANBAD,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,JAMSHEDPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,GIRIDIHI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,HAZARIBAGH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BOKARO,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,DEHRADUN,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,NAINITAAL,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,HARIDWAAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,ALMORAH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,UDDHAMSINGHNAGAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,SIMLA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,MANDI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BILASPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,AMRITSAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,JALANDHAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,LUDHIANA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,ROPARH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,CHANDIGARH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,ROHTAK,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,PANCHKULA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,AMBALA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,PANIPAT,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,GURGAON,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,HISSAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,JAMMU,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,SRINAGAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,POONCH,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,KOLKATA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,JALPAIGURHI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,DARJEELING,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,ASANSOL,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,SILIGURHI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,BHUVANESHWAR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,PURI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,CUTTACK,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,AHMEDABAD,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,SURAT,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,VADODARA,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,MUMBAI,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,NAGPUR,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,PUNE,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) try: insertWithoutClustering(HINDI,FARIDABAD,DELTA_HOURS_TWENTY_FOUR) except Exception, e: logger.exception("You have an exception :%s",e.args) <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('newsApp', '0009_auto_20160204_1319'), ] operations = [ migrations.CreateModel( name='Hindi_Agra', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Ahmedabad', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Ajmer', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Aligarh', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Allahabad', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Almorah', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Alwar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Ambala', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Amritsar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Asansol', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Azamgarh', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Bagpat', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Balia', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Bareilly', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Begusarai', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Bhagalpur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Bharatpur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Bhilai', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Bhilwara', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Bhopal', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Bhuvaneshwar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Bihar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Bikaner', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Bilaspur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Bokaro', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Books', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Bulandshahar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Business', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Business_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Chandigarh', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Chattisgarh', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Chhatis', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Cuttack', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Darbhanga', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Darjeeling', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Dehradun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Delhi', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Dewas', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Dhanbad', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Economy', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Economy_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Entertainment', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Entertainment_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Environment', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Environment_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Fashion', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Fashion_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Food', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Food_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Gaya', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Gaziabad', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Giridihi', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Gorakhpur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Gujrat', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Gurgaon', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Gwalior', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Haridwaar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Haryana', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Hazaribagh', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Health', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Health_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_HimachalPradesh', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Hissar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Indore', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Jabalpur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Jagdalpur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Jaipur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Jalandhar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Jalpaigurhi', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Jammu', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_JammuKashmir', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Jamshedpur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Jaunpur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Jhansi', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Jharkhand', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Jodhpur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Kanpur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Katihar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Kolkata', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Korva', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Kota', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Lifestyle', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Lifestyle_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Lucknow', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Ludhiana', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_MadhyaPradesh', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Maharashtra', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Mandi', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Mathura', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Merath', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Moradabad', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Mujaffarpur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Mumbai', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Muzaffarnagar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Nagpur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Nainitaal', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Noida', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Opinion', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Opinion_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Orissa', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Panchkula', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Panipat', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Patna', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Politics', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Politics_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Poonch', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Poorniya', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Pratapgarh', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Pune', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Punjab', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Puri', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Raigarh', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Raipur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Rajasthan', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Rajnandgao', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Ranchi', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Ratlam', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Rewa', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Rohtak', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Roparh', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Sagar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Saharnpur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Satna', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Science', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Science_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Sewan', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Sikar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Siligurhi', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Simla', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Sitapur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Sports', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Sports_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Srinagar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Stocks', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Stocks_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Surat', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Technology', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Technology_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Top_Stories_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Travel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Travel_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Udaipur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_UddhamSinghNagar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Ujjain', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Uttarakhand', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_UttarPradesh', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Vadodara', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Varanasi', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Weekend', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_Weekend_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_WestBengal', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField()), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=200)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_World', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Hindi_World_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), ] <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='English_Books', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Books_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Business', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Business_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Economy', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Economy_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Entertainment', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Entertainment_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Entertainment_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.DateTimeField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Environment', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Environment_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Fashion', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Fashion_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Food', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Food_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Health', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Health_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Lifestyle', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Lifestyle_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Mumbai', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Mumbai_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Opinion', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Opinion_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Politics', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Politics_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Pune', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Pune_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Science', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Science_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Sports', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Sports_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Sports_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.DateTimeField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Stocks', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Stocks_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Technology', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Technology_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Top_Stories', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Top_Stories_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Top_Stories_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.DateTimeField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Travel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Travel_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Weekend', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_Weekend_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_World', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='English_World_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Language', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Name', models.CharField(max_length=15)), ], ), migrations.CreateModel( name='Marathi_Ahmednagar', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Ahmednagar_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Akola', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Akola_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Aurangabad', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Aurangabad_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Books', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Books_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Business', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Business_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Chandrapur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Chandrapur_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Economy', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Economy_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Entertainment', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Entertainment_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Entertainment_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.DateTimeField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Environment', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Environment_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Fashion', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Fashion_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Food', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Food_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Goa', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Goa_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Health', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Health_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Jalgaon', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Jalgaon_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Kolhapur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Kolhapur_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Lifestyle', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Lifestyle_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Maharashtra', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Maharashtra_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Mumbai', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Mumbai_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Nagpur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Nagpur_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Nasik', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Nasik_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Opinion', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Opinion_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Politics', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Politics_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Pune', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Pune_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Sangli', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Sangli_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Satara', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Satara_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Science', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Science_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Solapur', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Solapur_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Sports', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Sports_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Sports_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.DateTimeField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Stocks', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Stocks_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Technology', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Technology_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Top_Stories', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Top_Stories_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Top_Stories_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.DateTimeField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Travel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Travel_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Wardha', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Wardha_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Weekend', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_Weekend_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_World', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Marathi_World_Rerun', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='News_Article', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Current_Date', models.DateTimeField(auto_now_add=True)), ('Is_New', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='News_Article_Archive', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Current_Date', models.DateTimeField()), ('Archive_Date', models.DateTimeField(auto_now_add=True)), ('Is_New', models.BooleanField(default=False)), ('Cluster_Id', models.IntegerField(db_index=True)), ('Is_Rep', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='News_Category', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Name', models.CharField(max_length=20)), ], ), migrations.CreateModel( name='News_Feed', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('URL', models.URLField(max_length=300)), ('Type', models.CharField(default=b'RSS 2.0', max_length=20)), ('Category', models.ForeignKey(to='newsApp.News_Category')), ('Language', models.ForeignKey(to='newsApp.Language')), ], ), migrations.CreateModel( name='News_Source', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Name', models.CharField(max_length=70)), ], ), migrations.CreateModel( name='News_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Current_Date', models.DateTimeField(auto_now_add=True)), ('Duration', models.DateTimeField(max_length=50)), ('Category', models.ForeignKey(to='newsApp.News_Category')), ('Language', models.ForeignKey(to='newsApp.Language')), ], ), migrations.CreateModel( name='TopN_English', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='TopN_Marathi', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='TopN_News_Article', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Category', models.ForeignKey(to='newsApp.News_Category')), ('Language', models.ForeignKey(to='newsApp.Language')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), migrations.CreateModel( name='Video_Channel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Channel_Id', models.CharField(max_length=100)), ('Category', models.ForeignKey(to='newsApp.News_Category')), ('Language', models.ForeignKey(to='newsApp.Language')), ], ), migrations.CreateModel( name='Video_Source', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Name', models.CharField(max_length=70)), ], ), migrations.AddField( model_name='video_channel', name='Source', field=models.ForeignKey(to='newsApp.Video_Source'), ), migrations.AddField( model_name='news_video', name='Source', field=models.ForeignKey(to='newsApp.Video_Source'), ), migrations.AddField( model_name='news_feed', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='news_article_archive', name='Category', field=models.ForeignKey(to='newsApp.News_Category'), ), migrations.AddField( model_name='news_article_archive', name='Language', field=models.ForeignKey(to='newsApp.Language'), ), migrations.AddField( model_name='news_article_archive', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='news_article', name='Category', field=models.ForeignKey(to='newsApp.News_Category'), ), migrations.AddField( model_name='news_article', name='Language', field=models.ForeignKey(to='newsApp.Language'), ), migrations.AddField( model_name='news_article', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_world_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_world_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_world', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_world', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_weekend_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_weekend_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_weekend', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_weekend', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_wardha_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_wardha_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_wardha', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_wardha', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_travel_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_travel_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_travel', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_travel', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_top_stories_video', name='Source', field=models.ForeignKey(to='newsApp.Video_Source'), ), migrations.AddField( model_name='marathi_top_stories_video', name='Video', field=models.ForeignKey(to='newsApp.News_Video'), ), migrations.AddField( model_name='marathi_top_stories_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_top_stories_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_top_stories', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_top_stories', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_technology_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_technology_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_technology', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_technology', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_stocks_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_stocks_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_stocks', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_stocks', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_sports_video', name='Source', field=models.ForeignKey(to='newsApp.Video_Source'), ), migrations.AddField( model_name='marathi_sports_video', name='Video', field=models.ForeignKey(to='newsApp.News_Video'), ), migrations.AddField( model_name='marathi_sports_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_sports_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_sports', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_sports', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_solapur_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_solapur_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_solapur', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_solapur', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_science_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_science_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_science', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_science', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_satara_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_satara_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_satara', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_satara', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_sangli_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_sangli_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_sangli', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_sangli', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_pune_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_pune_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_pune', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_pune', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_politics_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_politics_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_politics', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_politics', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_opinion_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_opinion_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_opinion', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_opinion', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_nasik_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_nasik_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_nasik', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_nasik', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_nagpur_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_nagpur_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_nagpur', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_nagpur', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_mumbai_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_mumbai_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_mumbai', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_mumbai', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_maharashtra_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_maharashtra_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_maharashtra', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_maharashtra', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_lifestyle_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_lifestyle_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_lifestyle', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_lifestyle', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_kolhapur_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_kolhapur_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_kolhapur', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_kolhapur', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_jalgaon_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_jalgaon_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_jalgaon', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_jalgaon', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_health_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_health_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_health', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_health', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_goa_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_goa_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_goa', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_goa', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_food_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_food_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_food', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_food', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_fashion_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_fashion_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_fashion', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_fashion', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_environment_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_environment_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_environment', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_environment', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_entertainment_video', name='Source', field=models.ForeignKey(to='newsApp.Video_Source'), ), migrations.AddField( model_name='marathi_entertainment_video', name='Video', field=models.ForeignKey(to='newsApp.News_Video'), ), migrations.AddField( model_name='marathi_entertainment_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_entertainment_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_entertainment', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_entertainment', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_economy_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_economy_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_economy', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_economy', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_chandrapur_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_chandrapur_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_chandrapur', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_chandrapur', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_business_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_business_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_business', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_business', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_books_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_books_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_books', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_books', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_aurangabad_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_aurangabad_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_aurangabad', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_aurangabad', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_akola_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_akola_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_akola', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_akola', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_ahmednagar_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_ahmednagar_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='marathi_ahmednagar', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='marathi_ahmednagar', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_world_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_world_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_world', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_world', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_weekend_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_weekend_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_weekend', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_weekend', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_travel_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_travel_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_travel', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_travel', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_top_stories_video', name='Source', field=models.ForeignKey(to='newsApp.Video_Source'), ), migrations.AddField( model_name='english_top_stories_video', name='Video', field=models.ForeignKey(to='newsApp.News_Video'), ), migrations.AddField( model_name='english_top_stories_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_top_stories_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_top_stories', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_top_stories', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_technology_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_technology_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_technology', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_technology', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_stocks_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_stocks_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_stocks', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_stocks', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_sports_video', name='Source', field=models.ForeignKey(to='newsApp.Video_Source'), ), migrations.AddField( model_name='english_sports_video', name='Video', field=models.ForeignKey(to='newsApp.News_Video'), ), migrations.AddField( model_name='english_sports_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_sports_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_sports', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_sports', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_science_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_science_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_science', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_science', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_pune_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_pune_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_pune', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_pune', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_politics_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_politics_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_politics', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_politics', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_opinion_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_opinion_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_opinion', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_opinion', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_mumbai_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_mumbai_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_mumbai', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_mumbai', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_lifestyle_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_lifestyle_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_lifestyle', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_lifestyle', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_health_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_health_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_health', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_health', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_food_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_food_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_food', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_food', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_fashion_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_fashion_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_fashion', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_fashion', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_environment_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_environment_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_environment', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_environment', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_entertainment_video', name='Source', field=models.ForeignKey(to='newsApp.Video_Source'), ), migrations.AddField( model_name='english_entertainment_video', name='Video', field=models.ForeignKey(to='newsApp.News_Video'), ), migrations.AddField( model_name='english_entertainment_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_entertainment_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_entertainment', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_entertainment', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_economy_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_economy_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_economy', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_economy', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_business_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_business_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_business', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_business', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_books_rerun', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_books_rerun', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), migrations.AddField( model_name='english_books', name='Article', field=models.ForeignKey(to='newsApp.News_Article'), ), migrations.AddField( model_name='english_books', name='Source', field=models.ForeignKey(to='newsApp.News_Source'), ), ] <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('newsApp', '0001_initial'), ] operations = [ migrations.AlterField( model_name='english_entertainment_video', name='Duration', field=models.CharField(max_length=50), ), migrations.AlterField( model_name='english_sports_video', name='Duration', field=models.CharField(max_length=50), ), migrations.AlterField( model_name='english_top_stories_video', name='Duration', field=models.CharField(max_length=50), ), migrations.AlterField( model_name='marathi_entertainment_video', name='Duration', field=models.CharField(max_length=50), ), migrations.AlterField( model_name='marathi_sports_video', name='Duration', field=models.CharField(max_length=50), ), migrations.AlterField( model_name='marathi_top_stories_video', name='Duration', field=models.CharField(max_length=50), ), migrations.AlterField( model_name='news_video', name='Duration', field=models.CharField(max_length=50), ), ] <file_sep># -*- coding: utf-8 -*- from collections import defaultdict from HTMLParser import HTMLParser import codecs import os import feedparser from dateutil import parser from nltk.stem.lancaster import LancasterStemmer from nltk.corpus import stopwords from gensim import corpora,similarities import gensim from scipy import cluster import requests from scrapeImage import * from tableQuery import * from scrapeComment import * logger = logging.getLogger('django') def getFeeds(lang, category): logger.info("Entered getFeeds ") feedsList = [] langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) feedsObj = News_Feed.objects.filter(Language=langObj, Category=categoryObj) for i in feedsObj: feedsDict = {} feedsDict['URL'] = i.URL feedsDict['Source'] = i.Source_id feedsDict['Type'] = i.Type feedsList.append(feedsDict) logger.info("Exited getFeeds ") return feedsList def getRSS2FeedParserData(lang, category, feedsDict): #logger.info("Entered getRSS2FeedParserData ") feed = feedparser.parse(feedsDict['URL']) #if sys.stdout.encoding != 'cp850': # sys.stdout = codecs.getwriter('cp850')(sys.stdout, 'xmlcharrefreplace') #if sys.stderr.encoding != 'cp850': # sys.stderr = codecs.getwriter('cp850')(sys.stderr, 'xmlcharrefreplace') newsDictList = [] inc = 0 langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) for post in feed.entries: newsDict = {} newsDict['Language_id'] = langObj newsDict['Category_id'] = categoryObj newsDict['smallImage'] = "" newsDict['title'] = "" newsDict['summary'] = "" newsDict['link'] = "" newsDict['published'] = "" newsDict['Source_id'] = feedsDict['Source'] if 'media_content' in post.keys(): dc_thumbnailDictList = post['media_content'] dc_thumbnailDict = dc_thumbnailDictList[0] if 'url' in dc_thumbnailDict.keys(): newsDict['smallImage'] = dc_thumbnailDict['url'] elif 'media_thumbnail' in post.keys(): dc_thumbnailDictList = post['media_thumbnail'] dc_thumbnailDict = dc_thumbnailDictList[0] if 'url' in dc_thumbnailDict.keys(): newsDict['smallImage'] = dc_thumbnailDict['url'] elif 'postimage' in post.keys(): dc_thumbnailDict = post['postimage'] newsDict['smallImage'] = dc_thumbnailDict elif 'dc_thumbnail' in post.keys(): dc_thumbnailDict = post['dc_thumbnail'] if 'url' in dc_thumbnailDict.keys(): newsDict['smallImage'] = dc_thumbnailDict['url'] if not newsDict['smallImage']: # this means that we have come across a news feed which doesn't have small image # now either 1. the news feed doesn't provide image at all OR # the image is in summary field. So to explore the second possibility, pass on the summary to the function #if post.summary: if 'summary' in post.keys(): summDict = returnImageURL(post.summary) if summDict['imageURLList']: newsDict['smallImage'] = summDict['imageURLList'][0] if 'title' in post.keys(): newsDict['title'] = post.title if 'summary' in post.keys(): # we need to take sumary directly from the feed only when 1. there is no existing summary already present if not newsDict['summary']: summDict = returnData(post.summary) if summDict['summaryData']: sumFinal = " ".join(summDict['summaryData']) if len(sumFinal) > 295: sumFinal = sumFinal[0:295].rsplit(' ', 1)[0] else: sumFinal = sumFinal.rsplit(' ', 1)[0] summaryFinal = trailingDots(sumFinal) newsDict['summary'] = summaryFinal if 'link' in post.keys(): newsDict['link'] = post.link if 'published' in post.keys(): if post.published: newsDict['published'] = post.published newsDictList.insert(inc, newsDict) inc += 1 #logger.info("Exited getRSS2FeedParserData ") return newsDictList def getAPI2ParserData(lang,category,feedsDict): newsList=[] langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) r = requests.get(feedsDict['URL']) try: wjson = r.json() for dict in wjson['results']: newsDict={} newsDict['Language_id'] = langObj newsDict['Category_id'] = categoryObj newsDict['link'] = dict['link'] newsDict['title'] = dict['title/_text'] newsDict['smallImage'] = "" newsDict['summary'] = "" newsDict['published'] = "" newsDict['Source_id'] = feedsDict['Source'] if 'summary' in dict.keys(): sumFinal = dict['summary'] if len(sumFinal) > 295: sumFinal = sumFinal[0:295].rsplit(' ', 1)[0] else: sumFinal = sumFinal.rsplit(' ', 1)[0] newsDict['summary'] = trailingDots(sumFinal) else: newsDict['summary'] = '' newsList.append(newsDict) except: pass return newsList def insertNewsArticle(newsDictList,deltaHours,isNew): #logger.info("Entered insertNewsArticle ") #deltaDate = datetime.date.today() - datetime.timedelta(days=deltaDays) #deltaDate = timezone.localtime(timezone.now()).date() - datetime.timedelta(days=deltaDays) deltaDate = datetime.datetime.now() - datetime.timedelta(hours=deltaHours) newsArticleObj = News_Article.objects.all() for newsDict in newsDictList: sourceObj = News_Source.objects.get(id=newsDict['Source_id']) if newsDict['published']: dt = parser.parse(newsDict['published']) else: #date = datetime.datetime.now(pytz.timezone('Asia/Kolkata')).strftime("%a, %d. %B %Y %H:%M:%S") #date = timezone.datetime.today().strftime("%a, %d. %B %Y %H:%M:%S") date = datetime.datetime.today().strftime("%a, %d. %B %Y %H:%M:%S") dt = parser.parse(date) logger.info(newsDict['link']) logger.info(dt) dtNaive = dt.replace(tzinfo=None) if dtNaive >= deltaDate: found = 0 for item in newsArticleObj: if item.URL.lower() == newsDict['link'].lower(): found = 1 if newsDict['Source_id'] == 30: if newsDict['link'][0:24] == MAHARASHTRA_TIMES_AD: found = 1 if not found: if newsDict['Source_id'] == 3: newsDict['smallImage'] = scrapeArticleForImage(newsDict['link'],newsDict['Source_id']) if newsDict['Source_id'] == 28: if newsDict['summary'].partition(' ')[0] == IBN_PLUS: newsDict['summary'] = '' if not newsDict['smallImage']: newsDict['smallImage'] = scrapeArticleForImage(newsDict['link'],newsDict['Source_id']) if newsDict['smallImage']: isUrl = isUrlanImage(newsDict['smallImage']) if not isUrl: newsDict['smallImage'] = '' article = News_Article(Language=newsDict['Language_id'], Category=newsDict['Category_id'], URL=newsDict['link'], Title=newsDict['title'], Summary=newsDict['summary'], Thumbnail=newsDict['smallImage'], Source=sourceObj, Published_Date=dt, Is_New=isNew) article.save() #logger.info("Exited insertNewsArticle ") def bagOfWords(lang, category, isNew,deltaHours): logger.info("Entered bagOfWords ") corpusList = [] titles = [] langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) #deltaDate = datetime.date.today() - datetime.timedelta(days=deltaDays) #deltaDate = timezone.localtime(timezone.now()).date() - datetime.timedelta(days=deltaDays) deltaDate = datetime.datetime.now() - datetime.timedelta(hours=deltaHours) articleObj = News_Article.objects.filter(Language=langObj, Category=categoryObj, Is_New=isNew, Published_Date__gt=deltaDate).order_by('-Published_Date') for article in articleObj: soup = article.Title if lang.lower() == MARATHI.lower(): soup = translateTitle(soup, GOOGLE_MR, GOOGLE_EN) elif lang.lower() == HINDI.lower(): soup = translateTitle(soup, GOOGLE_HI, GOOGLE_EN) letters_only = re.sub("[^a-zA-Z]", # The pattern to search for " ", # The pattern to replace it with soup) # Source lower_case = letters_only.lower() wordList2 = lower_case.split() st = LancasterStemmer() wordList3 = [st.stem(w) for w in wordList2] stops = set(stopwords.words("english")) finalWordlist = [w for w in wordList3 if not w in stops] corpusList.append(finalWordlist) string = str(article.id) + ' ' + str(letters_only) titles.append(string) resultDict = {} resultDict['corpusList'] = corpusList resultDict['titles'] = titles logger.info("Exited bagOfWords ") return resultDict def convertCorpustoDict(corpusList, path_dict, path_dict_mm): logger.info("Entered convertCorpustoDict ") frequency = defaultdict(int) # remove words that appear only once for text in corpusList: for token in text: frequency[token] += 1 corpus = [[token for token in text if frequency[token] > 1] for text in corpusList] dictionary = corpora.Dictionary(corpus) dictionary.save(path_dict) # store the dictionary, for future reference corpus = [dictionary.doc2bow(text) for text in corpus] #convert tokenized documents to vectors corpora.MmCorpus.serialize(path_dict_mm, corpus) # store to disk, for later use logger.info("Exited convertCorpustoDict ") def transformationsTFIDF(corpus): logger.info("Entered transformationsTFIDF ") # training the corpus #training consists simply of going through the tfidf = gensim.models.TfidfModel(corpus) # supplied corpus once and computing document # frequencies of all its features corpus_tfidf = tfidf[corpus] # apply a transformation to a whole corpus logger.info("Exited transformationsTFIDF ") return corpus_tfidf def transformationsLSI(corpus_tfidf, dictionary): logger.info("Entered transformationsLSI ") lsi = gensim.models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=50) # initialize an LSI transformation corpus_lsi = lsi[corpus_tfidf] # both bow->tfidf and tfidf->lsi transformations logger.info("Exited transformationsLSI ") return corpus_lsi def similarityMatrx(corpus_lsi): logger.info("Entered similarityMatrx ") index = similarities.MatrixSimilarity(corpus_lsi) logger.info("Exited similarityMatrx ") return index def extract_clusters(Z, threshold, n): logger.info("Entered extract_clusters ") clusters = {} ct = n for row in Z: if row[2] < threshold: n1 = int(row[0]) n2 = int(row[1]) if n1 >= n: l1 = clusters[n1] del (clusters[n1]) else: l1 = [n1] if n2 >= n: l2 = clusters[n2] del (clusters[n2]) else: l2 = [n2] l1.extend(l2) clusters[ct] = l1 ct += 1 else: logger.info("Exited extract_clusters ") return clusters def insertCategory(lang, category, cluster_file, outlier_file): logger.info("Entered insertCategory ") maxDict = getMaxClusterId(lang, category) if maxDict['Cluster_Id__max']: maxClusterId = maxDict['Cluster_Id__max'] + 1 else: maxClusterId = 1 deleteLangCategoryTable(lang, category) try: f = open(cluster_file, 'r') clusterIdPrev = -1 for line in f: clusterId = int(line.split()[0]) key1 = line.split()[1] articleObj = News_Article.objects.get(id=int(key1)) if clusterIdPrev == -1: # For the first line of the file insertLangCategoryTable(int(key1), lang, category, articleObj, maxClusterId, isRep=1) else: if clusterId == clusterIdPrev: # When articles of same Cluster insertLangCategoryTable(int(key1), lang, category, articleObj, maxClusterId, isRep=0) else: maxClusterId += 1 # When articles of different Cluster insertLangCategoryTable(int(key1), lang, category, articleObj, maxClusterId, isRep=1) clusterIdPrev = clusterId f.close() maxDict = getMaxClusterId(lang, category) if maxDict['Cluster_Id__max']: maxClusterId = maxDict['Cluster_Id__max'] + 1 else: maxClusterId = 1 except Exception,e: logger.error("You have an exception :",e.args) try: f2 = open(outlier_file, 'r') for line in f2: key1 = line.split()[1] articleObj = News_Article.objects.get(id=int(key1)) insertLangCategoryTable(int(key1), lang, category, articleObj, maxClusterId, isRep=True) maxClusterId += 1 f2.close() except Exception,e: logger.error("You have an exception :",e.args) logger.info("Exited insertCategory ") def returnImageURL(tag): # create a subclass and override the handler methods summDict = {} summDict['imageURLList'] = [] class MyHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.dataList = [] self.imgURLList = [] def handle_starttag(self, tag, attrs): if tag == 'img': # some NYT articles contain ads in form of images so check them via # RE and filter them for name, value in attrs: if name == "src": if value: pattern1 = ".feedsportal.com" pattern2 = '[^ ].*?(gif)' pattern3 = 'big.assets.huffingtonpost.com' matchObj2 = re.search(pattern1, value, re.I) # skip this image as it is an ad image from NYT if not matchObj2: # check for p2 matchObj2 = re.search(pattern2, value, re.I) if not matchObj2: matchObj2 = re.search(pattern3, value, re.I) if not matchObj2: # this means that the current image is OK to proceed as it does not match the above 3 patterns self.imgURLList.append(value) def handle_endtag(self, tag): if tag == 'img': summDict['imageURLList'] = self.imgURLList def handle_data(self, data): pass # instantiate the parser and feed it the summary parser = MyHTMLParser() parser.feed(tag) return summDict def returnData(tag): # create a subclass and override the handler methods summDict = {} summDict['summaryData'] = [] class MyHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.dataList = [] self.imgURLList = [] def handle_starttag(self, tag, attrs): pass def handle_endtag(self, tag): pass def handle_data(self, data): self.dataList.append(data) summDict['summaryData'] = self.dataList # instantiate the parser and feed it the summary parser = MyHTMLParser() parser.feed(tag) return summDict def isInClusteredIdsList(i, clusteredIdsList): #logger.info("Entered isInClusteredIdsList ") if i in clusteredIdsList: #logger.info("Exited isInClusteredIdsList ") return 1 else: #logger.info("Exited isInClusteredIdsList ") return 0 def getTitlesFromTables(clusterLanguage): # Hit tables of all categories and get all Titles #logger.info("Entered getTitlesFromTables ") titlesList = [] langObj = Language.objects.get(Name=clusterLanguage) #deltaDate = datetime.date.today() - datetime.timedelta(days=1) deltaDate = timezone.localtime(timezone.now()).date() - datetime.timedelta(days=1) articleObj = News_Article.objects.filter(Language = langObj, Published_Date__gt=deltaDate).order_by('id') for article in articleObj: titlesDict = {} titlesDict['Article'] = article titlesDict['title'] = article.Title titlesDict['id'] = article.id titlesDict['URL'] = article.URL titlesDict['Source'] = article.Source titlesDict['Summary'] = article.Summary titlesDict['Thumbnail'] = article.Thumbnail titlesDict['Published_Date'] = article.Published_Date titlesList.append(titlesDict) #logger.info("Exited getTitlesFromTables ") return titlesList def preProcessTitles(titlesList): #logger.info("Entered preProcessTitles ") corpusList = [] for titleDict in titlesList: soup = titleDict['title'] letters_only = re.sub("[^a-zA-Z]", # The pattern to search for " ", # The pattern to replace it with soup) # Source lower_case = letters_only.lower() wordList2 = lower_case.split() st = LancasterStemmer() wordList3 = [st.stem(w) for w in wordList2] stops = set(stopwords.words("english")) finalWordlist = [w for w in wordList3 if not w in stops] corpusList.append(finalWordlist) #logger.info("Exited preProcessTitles ") return corpusList def insertTopNewsArticle(newsDictList): logger.info("Entered insertTopNewsArticle ") deltaDate = datetime.date.today() - datetime.timedelta(days=1) #deltaDate = timezone.localtime(timezone.now()).date() - datetime.timedelta(days=1) newsArticleObj = TopN_News_Article.objects.all() for newsDict in newsDictList: sourceObj = News_Source.objects.get(id=newsDict['Source_id']) if newsDict['published']: dt = parser.parse(newsDict['published']) else: date = datetime.datetime.today().strftime("%a, %d. %B %Y %H:%M:%S") #date = timezone.datetime.today().strftime("%a, %d. %B %Y %H:%M:%S") dt = parser.parse(date) if dt.date() > deltaDate: found = 0 for item in newsArticleObj: if item.URL == newsDict['link']: found = 1 if not found: article = TopN_News_Article(Language=newsDict['Language_id'], Category=newsDict['Category_id'], URL=newsDict['link'], Title=newsDict['title'], Summary=newsDict['summary'], Thumbnail=newsDict['smallImage'], Source=sourceObj, Published_Date=dt) article.save() logger.info("Exited insertTopNewsArticle ") def convertCorpustoDict4NewDoc(corpusList, path_dict, path_dict_mm): #logger.info("Entered convertCorpustoDict4NewDoc ") frequency = defaultdict(int) # remove words that appear only once for text in corpusList: for token in text: frequency[token] += 1 corpus = [[token for token in text] # if frequency[token] > 1] for text in corpusList] oldDictionary = corpora.Dictionary.load(path_dict) oldDictionary.add_documents(corpus) corpus = [oldDictionary.doc2bow(text) for text in corpus] # convert tokenized documents to vectors oldCorpus = corpora.MmCorpus(path_dict_mm) oldCorpus = list(oldCorpus) for text in corpus: oldCorpus.append(text) corpora.MmCorpus.serialize(path_dict_mm, oldCorpus) # store to disk, for later use oldDictionary.save(path_dict) # store the dictionary, for future reference #logger.info("Exited convertCorpustoDict4NewDoc ") def translateTitle(query, srcLang, dstLang): #logger.info("Entered translateTitle ") if srcLang == GOOGLE_MR: sanitisedquery = returnSanitisedTitleString(WORDLIST_MARATHI, query) sanitisedquery = returnSanitisedTtileString1(sanitisedquery) sanitisedquery = returnSlicedTitle(sanitisedquery) if srcLang == GOOGLE_HI: sanitisedquery = query sanitisedquery = re.sub(r'[?|$|.|!@|#|%|^|&|*|_]', r'', sanitisedquery) r = requests.get( 'https://www.googleapis.com/language/translate/v2?key=<KEY>&source=' + srcLang + '&target=' + dstLang + '&q=' + sanitisedquery) wjson = r.json() #logger.info("Exited translateTitle ") return wjson['data']['translations'][0]['translatedText'] def returnSanitisedTitleString(fileName, title): sanitisedtitleList = [] whiteSpace = " " titleList = title.split() for word in titleList: sanitisedWord = returnMarathiRootWord(fileName, word) sanitisedtitleList.append(sanitisedWord) return whiteSpace.join(sanitisedtitleList) def returnSanitisedTtileString1(title): titleList = title.split() newTitleList = [] whiteSpace = " " for titleWord in titleList: newTitleWord = returnSanitisedTitleWord(titleWord) newTitleList.append(newTitleWord) return whiteSpace.join(newTitleList) def returnSanitisedTitleWord(titleWord): word = {} word['2'] = "प्रमाणेच" word['4'] = "मुळे" word['8'] = "प्रमाणे" word['12'] = "मध्येही" word['13'] = "मध्ये" word['14'] = "सुद्धा" for key in word: try: if word[key] in titleWord: sanitisedWord = titleWord.replace(word[key], " ") return sanitisedWord else: sanitisedWord = titleWord except: sanitisedWord = titleWord return sanitisedWord def returnMarathiRootWord(fileName, token): with codecs.open(fileName, 'r', encoding='utf-8') as f: for lines in f: if token in lines: strArray = lines.split('[') custStrArr = strArray[1].split('-') if (custStrArr[0]): return custStrArr[0] if not (custStrArr[0]): # check p3 strArray = lines.split('{') custStrArr = strArray[1].split('|') return custStrArr[0] return token def returnSlicedTitle(title): #logger.info("Entered returnSlicedTitle ") newWordList = [] for word in title.split(): slicedWord = returnSlicedWord(word) if slicedWord: newWordList.append(slicedWord) else: newWordList.append(word) #logger.info("Exited returnSlicedTitle ") return " ".join(newWordList) def returnSlicedWord(word): #logger.info("Entered returnSlicedWord ") sliceWord = {} sliceWord['1'] = "प्रकरणी" sliceWord['2'] = "विरुद्ध" sliceWord['3'] = "कडे" sliceWord['4'] = "वर" sliceWord['5'] = "कडून" sliceWord['6'] = "करिता" sliceWord['7'] = "वरून" sliceWord['8'] = "खालुन" sliceWord['9'] = "खालून" sliceWord['10'] = "साठी" sliceWord['11'] = "देखील" sliceWord['12'] = "सह" sliceWord['13'] = "हुन" sliceWord['14'] = "हून" sliceWord['15'] = "जवळ" sliceWord['16'] = "चे" sliceWord['17'] = "च्या" sliceWord['18'] = "ची" sliceWord['19'] = "तील" sliceWord['20'] = "मागे" sliceWord['21'] = "पुढे" sliceWord['22'] = "चा" sliceWord['23'] = "मुक्त" sliceWord['24'] = "टंचाई" sliceWord['25'] = "मधील" sliceWord['26'] = "वाद" sliceWord['27'] = "प्रकरणा" sliceWord['28'] = "भेद" sliceWord['29'] = "विरोधात" sliceWord['30'] = "द्वारे" sliceWord['31'] = "युक्त" sliceWord['32'] = "बरोबर" sliceWord['33'] = "ही" sliceWord['34'] = "पर्यंत" sliceWord['35'] = "खाली" sliceWord['36'] = "ऐवजी" sliceWord['37'] = "पूर्ती" slicedWordList = [] try: for key in sliceWord: if sliceWord[key] in word: newSlicedWord = " " + sliceWord[key] sanitisedWord = word.replace(sliceWord[key], newSlicedWord) slicedWordList.append(sanitisedWord) break except: return " ".join(slicedWordList) #logger.info("Exited returnSlicedWord ") return " ".join(slicedWordList) def trailingDots(string): try : string = string.rstrip() lastword = string.rsplit(' ', 1)[1] if lastword.endswith('...'): lastword = lastword[:-3] elif lastword.endswith('..'): lastword = lastword[:-2] elif lastword.endswith('.'): lastword = lastword[:-1] summary = string.rsplit(' ', 1)[0] +' ' + lastword + "..." return summary except: logger.info("Exited trailingDots ") return string def findMaxListIndex(list): #logger.info("Entered findMaxListIndex ") count = 0 for item in list: if item == max(list): #logger.info("Exited findMaxListIndex ") return count else : count +=1 #logger.info("Exited findMaxListIndex ") return -1 def insertTopNLanguage(language,articleDict): #logger.info("Entered insertTopNLanguage ") if language == ENGLISH: langTopNObj = TopN_English(Article=articleDict['Article'], URL=articleDict['URL'], Title=articleDict['title'], Summary=articleDict['Summary'], Thumbnail=articleDict['Thumbnail'], Source=articleDict['Source'], Published_Date=articleDict['Published_Date']) langTopNObj.save() if language == MARATHI: langTopNObj = TopN_Marathi(Article=articleDict['Article'], URL=articleDict['URL'], Title=articleDict['title'], Summary=articleDict['Summary'], Thumbnail=articleDict['Thumbnail'], Source=articleDict['Source'], Published_Date=articleDict['Published_Date']) langTopNObj.save() #logger.info("Exited insertTopNLanguage ") def deleteFiles(folder): for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception, e: logger.error("You have an exception :",e.args) def clusterOnLanguageCategory(clusterLanguage,clusterCategory,deltaHours): #This function does the following #1) Deletes the following files a)Cluster File b) Outlier File c)Titles-Dictionary File d)Titles dictionary MM serialized File e)All Titles file #2) Gets the feeds for respective language and categories #3) Parses those feeds to get the required data of the articles in the feeds like the titles, summary, photos etc #4) Inserts them into article table #5) Retrieves all the articles for article table and creates bag of words, Also writes the titles in All Titles file #6) If total number of articles are less than 5 all are considered outliers and written in the Outlier files #7) If the total number of articles are more than 5 than Take the bag og words convert them in to corpus of words with freq more than 1 #8) Write this corpus into titles dictionary file #9) Convert and write the Dictionary into MM serialized dictionary #10)load the corpus from MM serialized dictionary #11)transform the corpus into TFIDF corpus #12)transform the corpus into LSI corpus #13)extract clusters from this LSI corpus #14) insert these clusters into lang category table logger.info("Entered clusterOnLanguageCategory ") logger.info("%s,%s" %(clusterLanguage,clusterCategory)) langCatFilesPath = PATH + "/" + clusterLanguage + "/" + clusterCategory cluster_file = PATH + "/" + clusterLanguage + "/" + clusterCategory + "/" + CLUSTER_FILE outlier_file = PATH + "/" + clusterLanguage + "/" + clusterCategory + "/" + OUTLIER_FILE path_dict = PATH + "/" + clusterLanguage + "/" + clusterCategory + "/" + TITLES_DICT path_dict_mm = PATH + "/" + clusterLanguage + "/" + clusterCategory + "/" + TITLES_DICT_MM titles_all = PATH + "/" + clusterLanguage + "/" + clusterCategory + "/" + TITLES_ALL deleteFiles(langCatFilesPath) isNew = 0 feedsList = getFeeds(clusterLanguage,clusterCategory) for feedsDict in feedsList: if str(feedsDict['Type']) == 'RSS 2.0': newsDictList = getRSS2FeedParserData(clusterLanguage,clusterCategory,feedsDict) else: newsDictList = getAPI2ParserData(clusterLanguage,clusterCategory,feedsDict) insertNewsArticle(newsDictList,deltaHours,isNew) resultDict = bagOfWords(clusterLanguage,clusterCategory,isNew,deltaHours) corpusList = resultDict['corpusList'] titles = resultDict['titles'] f = open(titles_all, 'w') cnt = -1 for item in titles: cnt += 1 string = str(cnt) + " " + item + "\n" f.write(string) f.close() if cnt == -1: logger.info("Total articles : %s" % (cnt + 1)) elif cnt >- 1 and cnt<5: i=0 countOutliers = 0 f2 = open(outlier_file, 'w') while i <= cnt: string = str(i) + ' ' + str(titles[i]) + '\n' f2.write(string) countOutliers+=1 i+=1 f2.close() logger.info("Total Outlier articles : %s" % countOutliers) insertArchive(clusterLanguage,clusterCategory) insertCategory(clusterLanguage,clusterCategory,cluster_file,outlier_file) else: logger.info("Total Outlier articles : %s" % (cnt + 1)) convertCorpustoDict(corpusList,path_dict,path_dict_mm) dictionary = corpora.Dictionary.load(path_dict) corpus = corpora.MmCorpus(path_dict_mm) corpus_tfidf=transformationsTFIDF(corpus) corpus_lsi = transformationsLSI(corpus_tfidf,dictionary) index=similarityMatrx(corpus_lsi) mat = [] for doc in index: list = [] for d in doc: list.append(d) mat.append(list) t = 1.2 n = len(mat[0]) Z = cluster.hierarchy.linkage(mat, 'single') clusters = extract_clusters(Z,t,n) clusteredIdsList = [] f = open(cluster_file, 'w') count = 0 for key in clusters: for id in clusters[key]: string = str(key) + ' ' + str(titles[id]) + '\n' f.write(string) count +=1 clusteredIdsList.append(id) f.close() logger.info("Total clustered articles : %s" % count) i=0 countOutliers = 0 f2 = open(outlier_file, 'w') while i < len(titles): result = isInClusteredIdsList(i,clusteredIdsList) if result == False: string = str(i) + ' ' + str(titles[i]) + '\n' f2.write(string) countOutliers+=1 i+=1 f2.close() logger.info("Total Outlier articles : %s" % countOutliers) insertArchive(clusterLanguage,clusterCategory) insertCategory(clusterLanguage,clusterCategory,cluster_file,outlier_file) logger.info("%s,%s" %(clusterLanguage,clusterCategory)) logger.info("Exited clusterOnLanguageCategory ") def clusterWithNewDocument(clusterLanguage,clusterCategory,deltaHours): logger.info("Entered clusterWithNewDocument ") logger.info("%s,%s" %(clusterLanguage,clusterCategory)) cluster_file = PATH + "/" + clusterLanguage + "/" + clusterCategory + "/" + CLUSTER_FILE outlier_file = PATH + "/" + clusterLanguage + "/" + clusterCategory + "/" + OUTLIER_FILE path_dict = PATH + "/" + clusterLanguage + "/" + clusterCategory + "/" + TITLES_DICT path_dict_mm = PATH + "/" + clusterLanguage + "/" + clusterCategory + "/" + TITLES_DICT_MM titles_all = PATH + "/" + clusterLanguage + "/" + clusterCategory + "/" + TITLES_ALL isNew = 1 feedsList = getFeeds(clusterLanguage,clusterCategory) for feedsDict in feedsList: if str(feedsDict['Type']) == 'RSS 2.0': newsDictList = getRSS2FeedParserData(clusterLanguage,clusterCategory,feedsDict) else: newsDictList = getAPI2ParserData(clusterLanguage,clusterCategory,feedsDict) insertNewsArticle(newsDictList,deltaHours,isNew) resultDict = bagOfWords(clusterLanguage,clusterCategory,isNew,deltaHours) corpusList = resultDict['corpusList'] titles = resultDict['titles'] if titles: try: f = open(titles_all, 'a') except: f = open(titles_all, 'w') cnt = -1 for item in titles: cnt += 1 string = str(cnt) + " " + item + "\n" f.write(string) f.close() logger.info("Total new articles : %s" % (cnt + 1)) convertCorpustoDict4NewDoc(corpusList,path_dict,path_dict_mm) dictionary = corpora.Dictionary.load(path_dict) corpus = corpora.MmCorpus(path_dict_mm) corpus_tfidf=transformationsTFIDF(corpus) corpus_lsi = transformationsLSI(corpus_tfidf,dictionary) index=similarityMatrx(corpus_lsi) mat = [] for doc in index: list = [] for d in doc: list.append(d) mat.append(list) t = 1.2 n = len(mat[0]) Z = cluster.hierarchy.linkage(mat, 'single') clusters = extract_clusters(Z,t,n) clusteredIdsList = [] finalTitle = [] fTitle = open(titles_all, 'r') for line in fTitle: finalTitle.append(line.split()[1]) fTitle.close() f = open(cluster_file, 'w') count = 0 for key in clusters: for id in clusters[key]: string = str(key) + ' ' + str(finalTitle[id]) + '\n' f.write(string) count +=1 clusteredIdsList.append(id) f.close() logger.info("Total clustered articles : %s" % count) i=0 countOutliers = 0 f2 = open(outlier_file, 'w') while i < len(finalTitle): result = isInClusteredIdsList(i,clusteredIdsList) if result == 0: string = str(i) + ' ' + str(finalTitle[i]) + '\n' f2.write(string) countOutliers+=1 i+=1 f2.close() logger.info("Total Outlier articles : %s" % countOutliers) insertCategoryNewDoc(clusterLanguage,clusterCategory,cluster_file,outlier_file) deleteLangCategoryTable(clusterLanguage,clusterCategory) langCategotyAll = selectRerunTable(clusterLanguage,clusterCategory) for articleObj in langCategotyAll: insertLangCategoryFromRerunTable(clusterLanguage,clusterCategory,articleObj) updateArticleTable(clusterLanguage,clusterCategory) logger.info("Exited clusterWithNewDocument ") def insertWithoutClustering(clusterLanguage,clusterCategory,deltaHours): logger.info("Entered insertWithoutClustering ") logger.info("%s,%s" %(clusterLanguage,clusterCategory)) isNew = 0 langObj = Language.objects.get(Name=clusterLanguage) categoryObj = News_Category.objects.get(Name=clusterCategory) maxDict = getMaxClusterId(clusterLanguage,clusterCategory) if maxDict['Cluster_Id__max'] : maxClusterId = maxDict['Cluster_Id__max'] + 1 else : maxClusterId = 1 #deltaDate = datetime.date.today() - datetime.timedelta(days=deltaDays) #deltaDate = timezone.localtime(timezone.now()).date() - datetime.timedelta(days=deltaDays) deltaDate = datetime.datetime.now() - datetime.timedelta(hours=deltaHours) feedsList = getFeeds(clusterLanguage,clusterCategory) for feedsDict in feedsList: if str(feedsDict['Type']) == 'RSS 2.0': newsDictList = getRSS2FeedParserData(clusterLanguage,clusterCategory,feedsDict) else: newsDictList = getAPI2ParserData(clusterLanguage,clusterCategory,feedsDict) insertNewsArticle(newsDictList,deltaHours,isNew) articleObj = News_Article.objects.filter(Language = langObj,Category = categoryObj).order_by('Published_Date') deleteLangCategoryTable(clusterLanguage, clusterCategory) cnt = 0 for article in articleObj: #if article.Published_Date.date() >= deltaDate: dtNaive = article.Published_Date.replace(tzinfo=None) if dtNaive >= deltaDate: newsArticleObjFound = selectLangCategoryTable(clusterLanguage,clusterCategory,article.URL) if not newsArticleObjFound: cnt+=1 insertLangCategoryTable(article.id,clusterLanguage,clusterCategory,article,maxClusterId,isRep=True) maxClusterId+=1 logger.info("Number of inserted articles : %s" %cnt) logger.info("%s,%s" %(clusterLanguage,clusterCategory)) logger.info("Exited insertWithoutClustering ") def insertCategoryNewDoc(lang, category, cluster_file, outlier_file): logger.info("Entered insertCategoryNewDoc ") maxDict = getMaxClusterId(lang, category) if maxDict['Cluster_Id__max']: maxClusterId = maxDict['Cluster_Id__max'] + 1 else: maxClusterId = 1 maxDict = getMaxClusterIdForRerun(lang, category) if maxDict['Cluster_Id__max']: maxClusterIdForRerun = maxDict['Cluster_Id__max'] + 1 else: maxClusterIdForRerun = 1 deleteRerunTable(lang, category) f = open(cluster_file, 'r') clusterIdPrev = -1 for line in f: clusterId = int(line.split()[0]) key = line.split()[1] articleObj = News_Article.objects.get(id=int(key)) if clusterIdPrev == -1: # For the first line of the file insertLangCategoryRerunTable(int(key),lang, category, articleObj, maxClusterId, isRep=1) else: if clusterId == clusterIdPrev: # When articles of same Cluster insertLangCategoryRerunTable(int(key),lang, category, articleObj, maxClusterId, isRep=0) else: maxClusterId += 1 # When articles of different Cluster insertLangCategoryRerunTable(int(key),lang, category, articleObj, maxClusterId, isRep=1) clusterIdPrev = clusterId f.close() maxDict = getMaxClusterIdForRerun(lang, category) if maxDict['Cluster_Id__max']: maxClusterId = maxDict['Cluster_Id__max'] + 1 else: maxClusterId = maxClusterIdForRerun f2 = open(outlier_file, 'r') for line in f2: key = line.split()[1] articleObj = News_Article.objects.get(id=int(key)) insertLangCategoryRerunTable(int(key),lang, category, articleObj, maxClusterId, isRep=1) maxClusterId += 1 f2.close() logger.info("Exited insertCategoryNewDoc ") def sortForRep(lang, category): langCategotyAll = [] if lang.lower() == ENGLISH.lower(): if category.lower() == TOP_STORIES.lower(): langCategotyAll = English_Top_Stories.objects.all().order_by('Cluster_Id','-Published_Date') if lang.lower() == MARATHI.lower(): if category.lower() == TOP_STORIES.lower(): langCategotyAll = Marathi_Top_Stories.objects.all().order_by('Cluster_Id','-Published_Date') prevClusterId = -1 isRepFound = False isRepIds =[] cnt = 0 for langCatObj in langCategotyAll: if prevClusterId != langCatObj.Cluster_Id: isRepIds.insert(cnt,langCatObj.id) prevClusterId = langCatObj.Cluster_Id cnt +=1 for langCatObj in langCategotyAll: for ids in isRepIds: if langCatObj.id == ids: isRepFound = True if isRepFound == True: updateRep(lang,category,langCatObj,isRep=True) else : updateRep(lang,category,langCatObj,isRep=False) isRepFound = False def socialIndicators(lang, category): langCategotyAll = [] if lang.lower() == ENGLISH.lower(): if category.lower() == TOP_STORIES.lower(): langCategoty = English_Top_Stories.objects.all().order_by('Cluster_Id')[:1] minClusterId = getMinClusterId(langCategoty) maxClusterId = minClusterId + 11 langCategotyAll = English_Top_Stories.objects.filter(Cluster_Id__lt = maxClusterId).order_by('Cluster_Id','-Is_Rep') elif lang.lower() == MARATHI.lower(): if category.lower() == TOP_STORIES.lower(): langCategoty = Marathi_Top_Stories.objects.all().order_by('Cluster_Id')[:1] minClusterId = getMinClusterId(langCategoty) maxClusterId = minClusterId + 11 langCategotyAll = Marathi_Top_Stories.objects.filter(Cluster_Id__lt = maxClusterId).order_by('Cluster_Id','-Is_Rep') elif lang.lower() == HINDI.lower(): if category.lower() == TOP_STORIES.lower(): langCategoty = Hindi_Top_Stories.objects.all().order_by('Cluster_Id')[:1] minClusterId = getMinClusterId(langCategoty) maxClusterId = minClusterId + 11 langCategotyAll = Hindi_Top_Stories.objects.filter(Cluster_Id__lt = maxClusterId).order_by('Cluster_Id','-Is_Rep') prevClusterId = -1 socialAPI = "https://graph.facebook.com/fql?q=SELECT%20url,%20normalized_url,%20share_count,%20like_count,%20comment_count,%20total_count,%20commentsbox_count,%20comments_fbid,%20click_count%20FROM%20link_stat%20WHERE%20url='" clusterSocialList = [] '''if lang.lower() == ENGLISH.lower(): f= open(SOCIAL_URL_FILE_ENG,'a') elif lang.lower() == MARATHI.lower(): f= open(SOCIAL_URL_FILE_MAR,'a') elif lang.lower() == HINDI.lower(): f= open(SOCIAL_URL_FILE_HIN,'a')''' for langCatObj in langCategotyAll: socialAPIURL = socialAPI + langCatObj.URL + "'" try: r = requests.get(socialAPIURL) wjson = r.json() except: wjson['facebook']['total_count'] = 0 if prevClusterId == langCatObj.Cluster_Id: commentCount = scrape4comments(langCatObj.URL,langCatObj.Source_id) clusterSocialDict['fbShareCount'] = clusterSocialDict['fbShareCount'] + wjson['data'][0]['total_count'] + int(commentCount) else: if prevClusterId != -1: clusterSocialList.append(clusterSocialDict) clusterSocialDict = {} clusterSocialDict['Cluster_id'] = langCatObj.Cluster_Id clusterSocialDict['repTitle'] = langCatObj.Title clusterSocialDict['fbShareCount'] = 0 commentCount = scrape4comments(langCatObj.URL,langCatObj.Source_id) clusterSocialDict['fbShareCount'] = clusterSocialDict['fbShareCount'] + wjson['data'][0]['total_count'] + int(commentCount) prevClusterId = langCatObj.Cluster_Id string = '\n' + '\n' '''f.write(string) string = str(datetime.datetime.now()) + '\n' f.write(string) for dict in clusterSocialList: string = str(dict['Cluster_id']) + ' ' + dict['repTitle'].encode('utf-8') + '\n' f.write(string)''' clusterSocialList2 = bubleSort(clusterSocialList) #string = '\n' + '\n' #f.write(string) newClusterid = minClusterId for dict1 in clusterSocialList2: dict1['Cluster_id_new'] = newClusterid newClusterid +=1 #string = str(dict1['Cluster_id']) + ' ' + dict1['repTitle'].encode('utf-8') + '\n' #f.write(string) #f.close() for dict3 in clusterSocialList2: for langCategotyObj in langCategotyAll: if langCategotyObj.Cluster_Id == dict3['Cluster_id']: TopStories = English_Top_Stories.objects.filter(id = langCategotyObj.id) for TopStoriesObj in TopStories: TopStoriesObj.Cluster_Id = dict3['Cluster_id_new'] TopStoriesObj.save() def bubleSort(clusterSocialList): swapped = True while swapped == True: swapped = False total = len(clusterSocialList) cnt =0 for index, item in enumerate(clusterSocialList): cnt+=1 next = index + 1 if cnt < total: if clusterSocialList[index]['fbShareCount'] < clusterSocialList[next]['fbShareCount']: clusterSocialList[index],clusterSocialList[next] = swap(clusterSocialList[index], clusterSocialList[next]) swapped = True return clusterSocialList def swap(dict1,dict2): dict3 = dict1 dict1 = dict2 return dict1,dict3 def getMinClusterId(langCategotyAll): for langCatObj in langCategotyAll: return langCatObj.Cluster_Id def isUrlanImage(URL): #logger.info("Entered isUrlanImage ") try: response= urllib2.urlopen(HeadRequest(URL)) maintype= response.headers['Content-Type'].split(';')[0].lower() if maintype not in ('image/png', 'image/jpeg', 'image/gif'): #logger.info("Exited isUrlanImage ") return False else: #logger.info("Exited isUrlanImage ") return True except : #logger.info("Exited isUrlanImage ") return False class HeadRequest(urllib2.Request): logger.info("Entered HeadRequest ") def get_method(self): return 'HEAD' logger.info("Exited HeadRequest ") def createTopN(clusterLanguage): logger.info("Entered createTopN ") deleteLangCategoryTable(clusterLanguage, TOPN) langObj = Language.objects.get(Name=clusterLanguage) categoryObj = News_Category.objects.get(Name=TOP_STORIES) #f=open(SUMMARY_MARATHI_FILE,'r') #for line in f: # SUMMARY_MARATHI = line #f.close() #SUMMARY_MARATHI = SUMMARY_MARATHI.split('= ')[1] try: if clusterLanguage.lower()==ENGLISH.lower(): englsihCategoryObj = English_Top_Stories.objects.filter(Is_Rep = 1).order_by('Cluster_Id') cnt = 0 for catObj in englsihCategoryObj: if cnt < 1: if catObj.Thumbnail: articleObj = News_Article.objects.get(id = catObj.Article.id, Language = langObj, Category = categoryObj) topNObject = TopN_English(Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = SUMMARY, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date) topNObject.save() cnt+=1 except Exception, e: logger.info("No data in English_Top_Stories Table") try: if clusterLanguage.lower()==MARATHI.lower(): marathiCategoryObj = Marathi_Top_Stories.objects.filter(Is_Rep = 1).order_by('Cluster_Id') cnt = 0 for catObj in marathiCategoryObj: if cnt < 1: if catObj.Thumbnail: articleObj = News_Article.objects.get(id = catObj.Article.id, Language = langObj, Category = categoryObj) topNObject = TopN_Marathi(Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = SUMMARY_MARATHI, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date) topNObject.save() cnt+=1 except Exception, e: logger.info("No data in Marathi_Top_Stories Table") if clusterLanguage.lower()==HINDI.lower(): hindiCategoryObj = Hindi_Top_Stories.objects.filter(Is_Rep = 1).order_by('Cluster_Id') cnt = 0 for catObj in hindiCategoryObj: if cnt < 1: if catObj.Thumbnail: articleObj = News_Article.objects.get(id = catObj.Article.id, Language = langObj, Category = categoryObj) topNObject = TopN_Hindi(Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = SUMMARY_HINDI, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date) topNObject.save() cnt+=1 logger.info("Exited createTopN ") <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('newsApp', '0002_auto_20151001_1819'), ] operations = [ migrations.CreateModel( name='English_Business_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.CharField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ('Source', models.ForeignKey(to='newsApp.Video_Source')), ('Video', models.ForeignKey(to='newsApp.News_Video')), ], ), migrations.CreateModel( name='English_Environment_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.CharField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ('Source', models.ForeignKey(to='newsApp.Video_Source')), ('Video', models.ForeignKey(to='newsApp.News_Video')), ], ), migrations.CreateModel( name='English_Fashion_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.CharField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ('Source', models.ForeignKey(to='newsApp.Video_Source')), ('Video', models.ForeignKey(to='newsApp.News_Video')), ], ), migrations.CreateModel( name='English_Food_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.CharField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ('Source', models.ForeignKey(to='newsApp.Video_Source')), ('Video', models.ForeignKey(to='newsApp.News_Video')), ], ), migrations.CreateModel( name='English_Health_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.CharField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ('Source', models.ForeignKey(to='newsApp.Video_Source')), ('Video', models.ForeignKey(to='newsApp.News_Video')), ], ), migrations.CreateModel( name='English_Lifestyle_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.CharField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ('Source', models.ForeignKey(to='newsApp.Video_Source')), ('Video', models.ForeignKey(to='newsApp.News_Video')), ], ), migrations.CreateModel( name='English_Science_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.CharField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ('Source', models.ForeignKey(to='newsApp.Video_Source')), ('Video', models.ForeignKey(to='newsApp.News_Video')), ], ), migrations.CreateModel( name='English_Technology_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.CharField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ('Source', models.ForeignKey(to='newsApp.Video_Source')), ('Video', models.ForeignKey(to='newsApp.News_Video')), ], ), migrations.CreateModel( name='English_World_Video', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('Cluster_Id', models.IntegerField(db_index=True)), ('VideoId', models.CharField(max_length=100)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Duration', models.CharField(max_length=50)), ('Is_Rep', models.BooleanField(default=False)), ('Source', models.ForeignKey(to='newsApp.Video_Source')), ('Video', models.ForeignKey(to='newsApp.News_Video')), ], ), ] <file_sep>from bs4 import BeautifulSoup import urllib2 from models import * from newspaper import Article import re import logging import socket from userConstants import articleSourceName logger = logging.getLogger('django') def scrapeArticleForImage(url,sourceId): #logger.info("Entered scrapeArticleForImage ") try: html = urllib2.urlopen(url, None, 10) soup = BeautifulSoup(html) sourceObj = News_Source.objects.get(id=sourceId) sourceName = sourceObj.Name if sourceName == "ABP Majha": imgs = soup.find_all("img", {"class":"media "}) for img in imgs: return img['src'] if sourceName == 'IBN Lokmat': imgs = soup.find_all('img', class_=re.compile('aligncenter')) for img in imgs: return img['src'] else: imgs = soup.find_all('img', class_=re.compile('alignleft')) for img in imgs: return img['src'] if sourceName == 'Lokmat': imgs = soup.findAll("img", {"style":"max-width:320px;margin-top:7px;"}) for img in imgs: return img['src'] if sourceName == 'Zeenews': imgs = soup.findAll("div", {"class":"field-item even"}) for imglink in imgs: return imglink.img['src'] if sourceName == 'Webdunia': imgs = soup.findAll("img", {"class":"imgCont"}) for img in imgs: return img['src'] if sourceName == "Business Standard": imgs = soup.findAll("img", {"class":"imgCont"}) for img in imgs: return img['src'] if sourceName == "The Statesman": imgs = soup.findAll("img", {"alt":"title="}) for img in imgs: return img['src'] if sourceName == "Business Wire": imgs = soup.findAll("div", {"id":"bwbodyimg"}) for imglink in imgs: return imglink.img['src'] if sourceName == "Financial Express" : imgs = soup.findAll("div", {"class":"storypic"}) for imglink in imgs: return imglink.img['src'] if sourceName == "Jagran" : imgs = soup.findAll("div", {"class":"stryimg"}) for imglink in imgs: return imglink.img['data-src'] if sourceName == "De<NAME>" : imgs = soup.findAll("img", {"class":"floatLeftImg"}) for imglink in imgs: return imglink['src'] if sourceName == "Asian Age" : imgs = soup.findAll("img", {"class":"image image-content_image "}) for imglink in imgs: return imglink['src'] if sourceName == "Economy Watch" : imgs = soup.findAll("div", {"class":"field-item odd"}) for imglink in imgs: return imglink.img['src'] if sourceName == "Filmfare" : imgs = soup.findAll("div", {"class":"upperBlk"}) for imglink in imgs: return imglink.figure.img['src'] if sourceName == "Techtree" : imgs = soup.findAll("div", {"class":"preview-img"}) for imglink in imgs: return imglink.img['src'] if sourceName == "BGR" : imgs = soup.findAll("div", {"class":"post-img-wrap bgr-style-normal"}) for imglink in imgs: return imglink.img['src'] if sourceName == "EurekAlert" : imgs = soup.findAll("div", {"class":"img-wrapper"}) for imglink in imgs: return imglink.img['src'] if sourceName == "Travelmasti" : imgs = soup.findAll("img", {"id":"myPicture"}) for imglink in imgs: return imglink['src'] if sourceName == "Huffington Post" : imgs = soup.findAll("div", {"class":"main-visual group embedded-image"}) for imglink in imgs: if imglink.span : return imglink.span.img['src'] else: return imglink.img['src'] if sourceName == "Indian Express" : imgs = soup.findAll("span", {"class":"custom-caption"}) for imglink in imgs: if imglink.img: return imglink.img['src'] if sourceName == "India TV" : imgs = soup.findAll("div", {"class":"mad-first-img"}) for imglink in imgs: return imglink.img['src'] if sourceName == "<NAME>" : imgs = soup.findAll("div", {"class":"featured"}) for imglink in imgs: return imglink.div.a.img['src'] if sourceName == "Maharashtra Times" : imgs = soup.findAll("div", {"class":"thumbImage"}) for imglink in imgs: return imglink.img['src'] if sourceName == "<NAME>" : imgs = soup.findAll("img", {"class":"lazy"}) for imglink in imgs: return imglink['data-href'] if sourceName == "Samna": imgs = soup.findAll("div", {"class":"col-lg-3 col-xs-12 pic-newslist"}) for imglink in imgs: return imglink.img['src'] if sourceName == "Elle" : imgs = soup.findAll("div", {"class":"embedded-image--inner"}) for imglink in imgs: return imglink.img['data-src'] if sourceName == "Loksatta" : imgs = soup.findAll("div", {"class":"imgholder"}) for imglink in imgs: return imglink.img['src'] if sourceName == "IBNLive" : imgs = soup.findAll("figure", {"class":"article_img"}) for imglink in imgs: return imglink.img['src'] if sourceName == "Hindustan Times" : imgs = soup.findAll("div", {"class":"news_photo"}) for imglink in imgs: imageUrl = 'http://www.hindustantimes.com' + imglink.img['src'] return imageUrl if sourceName == "The Hindu Business Line" : imgs = soup.findAll("div", {"id":"hcenter"}) for imglink in imgs: return imglink.img['src'] if sourceName == "BBC" : imgs = soup.findAll("span", {"id":"image-and-copyright-container"}) for imglink in imgs: return imglink.img['src'] if sourceName == "tecake" : imgs = soup.findAll("div", {"class":"td-post-featured-image"}) for imglink in imgs: return imglink.img['src'] if sourceName == "India" : imgs = soup.findAll("section", {"class":"content-wrap eventtracker"}) for imglink in imgs: return imglink.div.img['src'] if sourceName == "Cricket Country" : imgs = soup.findAll("div", {"class":"wp-caption aligncenter"}) for imglink in imgs: return imglink.img['src'] if sourceName == 'Nationnal Duniya': imgs = soup.findAll("div", {"align":"center"}) for imglink in imgs: return imglink.img['src'] if sourceName == 'Haribhoomi': imgs = soup.findAll("div", {"class":"entry-img featured-img"}) for imglink in imgs: return imglink.img['src'] for articleSource in articleSourceName: if sourceName == articleSource: article = Article(url) article.download() article.parse() if article.top_image: return article.top_image logger.info("For %s , image not found" %url) except socket.timeout: logger.info("For %s , timed out error!!!!!!" %url) except Exception, e: logger.info("For %s , image not found" %url) #logger.info("Exited scrapeArticleForImage ") <file_sep>"""Django18project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from .views import * from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^TopN/$', TopN), url(r'^insertLanguageCategory/$', insertLanguageCategory), url(r'^home/', loadNewsForHome,name="loadNewsForHome"), url(r'^cat/', loadNewsForCategory,name="loadNewsForCategory"), url(r'^similar/', loadSimilarNews,name="loadSimilarNews"), url(r'^loadTopN/', loadTopN,name="loadTopN"), url(r'^loadTopNVideo/', loadTopNVideo,name="loadTopNVideo"), url(r'^insertVideoLanguageCategory/$', insertVideoLanguageCategory), url(r'^videoCat/', loadVideoForCategory,name="loadVideoForCategory"), url(r'^isVideoAvailable/', isVideoAvailable,name="isVideoAvailable"), url(r'^catNew/', loadNewsForCategoryNew,name="loadNewsForCategoryNew"), url(r'^similarNew/', loadSimilarNewsNew,name="loadSimilarNewsNew"), url(r'^sourceNews/', sourceNews,name="sourceNews"), url(r'^socialIndicator/$', socialIndicator), ] <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('newsApp', '0012_hindi_faridabad'), ] operations = [ migrations.CreateModel( name='TopN_Hindi', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('URL', models.URLField(max_length=300)), ('Title', models.CharField(max_length=100)), ('Summary', models.CharField(max_length=300)), ('Thumbnail', models.URLField(max_length=300, null=True, blank=True)), ('Published_Date', models.DateTimeField()), ('Article', models.ForeignKey(to='newsApp.News_Article')), ('Source', models.ForeignKey(to='newsApp.News_Source')), ], ), ] <file_sep>from django.contrib import admin from .models import * admin.site.register(News_Article) admin.site.register(English_Politics) admin.site.register(Language) admin.site.register(News_Category) admin.site.register(News_Feed) admin.site.register(News_Source) admin.site.register(Video_Source) admin.site.register(Video_Channel)<file_sep>from models import * from userConstants import * from django.db.models import Max from django.db import connection import datetime def getMaxClusterId(lang, category): #logger.info("Entered getMaxClusterId ") if lang.lower() == HINDI.lower(): if category.lower() == SPORTS.lower(): maxDict = Hindi_Sports.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == TOP_STORIES.lower(): maxDict = Hindi_Top_Stories.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == WORLD.lower(): maxDict = Hindi_World.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == OPINION.lower(): maxDict = Hindi_Opinion.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == HEALTH.lower(): maxDict = Hindi_Health.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == LIFESTYLE.lower(): maxDict = Hindi_Lifestyle.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ENTERTAINMENT.lower(): maxDict = Hindi_Entertainment.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == TECHNOLOGY.lower(): maxDict = Hindi_Technology.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == POLITICS.lower(): maxDict = Hindi_Politics.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ENVIRONMENT.lower(): maxDict = Hindi_Environment.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BOOKS.lower(): maxDict = Hindi_Books.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == TRAVEL.lower(): maxDict = Hindi_Travel.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SCIENCE.lower(): maxDict = Hindi_Science.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BUSINESS.lower(): maxDict = Hindi_Business.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == STOCKS.lower(): maxDict = Hindi_Stocks.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == FOOD.lower(): maxDict = Hindi_Food.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == WEEKEND.lower(): maxDict = Hindi_Weekend.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == FASHION.lower(): maxDict = Hindi_Fashion.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == UTTARPRADESH.lower(): maxDict = Hindi_UttarPradesh.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == UTTARAKHAND.lower(): maxDict = Hindi_Uttarakhand.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == HIMACHALPRADESH.lower(): maxDict = Hindi_HimachalPradesh.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == DELHI.lower(): maxDict = Hindi_Delhi.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == JAMMUKASHMIR.lower(): maxDict = Hindi_JammuKashmir.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == PUNJAB.lower(): maxDict = Hindi_Punjab.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == MADHYAPRADESH.lower(): maxDict = Hindi_MadhyaPradesh.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == JHARKHAND.lower(): maxDict = Hindi_Jharkhand.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BIHAR.lower(): maxDict = Hindi_Bihar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == HARYANA.lower(): maxDict = Hindi_Haryana.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == CHATTISGARH.lower(): maxDict = Hindi_Chattisgarh.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == RAJASTHAN.lower(): maxDict = Hindi_Rajasthan.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == WESTBENGAL.lower(): maxDict = Hindi_WestBengal.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ORISSA.lower(): maxDict = Hindi_Orissa.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == GUJRAT.lower(): maxDict = Hindi_Gujrat.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == MAHARASHTRA.lower(): maxDict = Hindi_Maharashtra.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == LUCKNOW.lower(): maxDict = Hindi_Lucknow.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ALLAHABAD.lower(): maxDict = Hindi_Allahabad.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == PRATAPGARH.lower(): maxDict = Hindi_Pratapgarh.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == KANPUR.lower(): maxDict = Hindi_Kanpur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == MERATH.lower(): maxDict = Hindi_Merath.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == AGRA.lower(): maxDict = Hindi_Agra.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == NOIDA.lower(): maxDict = Hindi_Noida.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == GAZIABAD.lower(): maxDict = Hindi_Gaziabad.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BAGPAT.lower(): maxDict = Hindi_Bagpat.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SAHARNPUR.lower(): maxDict = Hindi_Saharnpur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BULANDSHAHAR.lower(): maxDict = Hindi_Bulandshahar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == VARANASI.lower(): maxDict = Hindi_Varanasi.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == GORAKHPUR.lower(): maxDict = Hindi_Gorakhpur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == JHANSI.lower(): maxDict = Hindi_Jhansi.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == MUZAFFARNAGAR.lower(): maxDict = Hindi_Muzaffarnagar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SITAPUR.lower(): maxDict = Hindi_Sitapur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == JAUNPUR.lower(): maxDict = Hindi_Jaunpur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == AZAMGARH.lower(): maxDict = Hindi_Azamgarh.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == MORADABAD.lower(): maxDict = Hindi_Moradabad.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BAREILLY.lower(): maxDict = Hindi_Bareilly.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BALIA.lower(): maxDict = Hindi_Balia.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ALIGARH.lower(): maxDict = Hindi_Aligarh.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == MATHURA.lower(): maxDict = Hindi_Mathura.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BHOPAL.lower(): maxDict = Hindi_Bhopal.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == INDORE.lower(): maxDict = Hindi_Indore.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == GWALIOR.lower(): maxDict = Hindi_Gwalior.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == JABALPUR.lower(): maxDict = Hindi_Jabalpur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == UJJAIN.lower(): maxDict = Hindi_Ujjain.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == RATLAM.lower(): maxDict = Hindi_Ratlam.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SAGAR.lower(): maxDict = Hindi_Sagar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == DEWAS.lower(): maxDict = Hindi_Dewas.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SATNA.lower(): maxDict = Hindi_Satna.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == REWA.lower(): maxDict = Hindi_Rewa.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == PATNA.lower(): maxDict = Hindi_Patna.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BHAGALPUR.lower(): maxDict = Hindi_Bhagalpur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == MUJAFFARPUR.lower(): maxDict = Hindi_Mujaffarpur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == GAYA.lower(): maxDict = Hindi_Gaya.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == DARBHANGA.lower(): maxDict = Hindi_Darbhanga.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == POORNIYA.lower(): maxDict = Hindi_Poorniya.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SEWAN.lower(): maxDict = Hindi_Sewan.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BEGUSARAI.lower(): maxDict = Hindi_Begusarai.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == KATIHAR.lower(): maxDict = Hindi_Katihar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == JAIPUR.lower(): maxDict = Hindi_Jaipur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == UDAIPUR.lower(): maxDict = Hindi_Udaipur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == JODHPUR.lower(): maxDict = Hindi_Jodhpur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == AJMER.lower(): maxDict = Hindi_Ajmer.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BIKANER.lower(): maxDict = Hindi_Bikaner.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ALWAR.lower(): maxDict = Hindi_Alwar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SIKAR.lower(): maxDict = Hindi_Sikar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == KOTA.lower(): maxDict = Hindi_Kota.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BHILWARA.lower(): maxDict = Hindi_Bhilwara.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BHARATPUR.lower(): maxDict = Hindi_Bharatpur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == CHHATIS.lower(): maxDict = Hindi_Chhatis.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == RAIPUR.lower(): maxDict = Hindi_Raipur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BILASPUR.lower(): maxDict = Hindi_Bilaspur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BHILAI.lower(): maxDict = Hindi_Bhilai.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == RAJNANDGAO.lower(): maxDict = Hindi_Rajnandgao.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == RAIGARH.lower(): maxDict = Hindi_Raigarh.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == JAGDALPUR.lower(): maxDict = Hindi_Jagdalpur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == KORVA.lower(): maxDict = Hindi_Korva.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == RANCHI.lower(): maxDict = Hindi_Ranchi.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == DHANBAD.lower(): maxDict = Hindi_Dhanbad.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == JAMSHEDPUR.lower(): maxDict = Hindi_Jamshedpur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == GIRIDIHI.lower(): maxDict = Hindi_Giridihi.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == HAZARIBAGH.lower(): maxDict = Hindi_Hazaribagh.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BOKARO.lower(): maxDict = Hindi_Bokaro.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == DEHRADUN.lower(): maxDict = Hindi_Dehradun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == NAINITAAL.lower(): maxDict = Hindi_Nainitaal.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == HARIDWAAR.lower(): maxDict = Hindi_Haridwaar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ALMORAH.lower(): maxDict = Hindi_Almorah.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == UDDHAMSINGHNAGAR.lower(): maxDict = Hindi_UddhamSinghNagar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SIMLA.lower(): maxDict = Hindi_Simla.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == MANDI.lower(): maxDict = Hindi_Mandi.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == AMRITSAR.lower(): maxDict = Hindi_Amritsar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == JALANDHAR.lower(): maxDict = Hindi_Jalandhar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == LUDHIANA.lower(): maxDict = Hindi_Ludhiana.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ROPARH.lower(): maxDict = Hindi_Roparh.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == CHANDIGARH.lower(): maxDict = Hindi_Chandigarh.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ROHTAK.lower(): maxDict = Hindi_Rohtak.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == PANCHKULA.lower(): maxDict = Hindi_Panchkula.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == AMBALA.lower(): maxDict = Hindi_Ambala.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == PANIPAT.lower(): maxDict = Hindi_Panipat.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == GURGAON.lower(): maxDict = Hindi_Gurgaon.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == HISSAR.lower(): maxDict = Hindi_Hissar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == JAMMU.lower(): maxDict = Hindi_Jammu.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SRINAGAR.lower(): maxDict = Hindi_Srinagar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == POONCH.lower(): maxDict = Hindi_Poonch.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == KOLKATA.lower(): maxDict = Hindi_Kolkata.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == JALPAIGURHI.lower(): maxDict = Hindi_Jalpaigurhi.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == DARJEELING.lower(): maxDict = Hindi_Darjeeling.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ASANSOL.lower(): maxDict = Hindi_Asansol.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SILIGURHI.lower(): maxDict = Hindi_Siligurhi.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BHUVANESHWAR.lower(): maxDict = Hindi_Bhuvaneshwar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == PURI.lower(): maxDict = Hindi_Puri.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == CUTTACK.lower(): maxDict = Hindi_Cuttack.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == AHMEDABAD.lower(): maxDict = Hindi_Ahmedabad.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SURAT.lower(): maxDict = Hindi_Surat.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == VADODARA.lower(): maxDict = Hindi_Vadodara.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == MUMBAI.lower(): maxDict = Hindi_Mumbai.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == NAGPUR.lower(): maxDict = Hindi_Nagpur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == PUNE.lower(): maxDict = Hindi_Pune.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == AUTO.lower(): maxDict = Hindi_Auto.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == CRIME.lower(): maxDict = Hindi_Crime.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == FARIDABAD.lower(): maxDict = Hindi_Faridabad.objects.all().aggregate(Max('Cluster_Id')) elif lang == ENGLISH: if category.lower() == ECONOMY.lower(): maxDict = English_Economy.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SPORTS.lower(): maxDict = English_Sports.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == TOP_STORIES.lower(): maxDict = English_Top_Stories.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == WORLD.lower(): maxDict = English_World.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == OPINION.lower(): maxDict = English_Opinion.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == HEALTH.lower(): maxDict = English_Health.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == LIFESTYLE.lower(): maxDict = English_Lifestyle.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ENTERTAINMENT.lower(): maxDict = English_Entertainment.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == TECHNOLOGY.lower(): maxDict = English_Technology.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == POLITICS.lower(): maxDict = English_Politics.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ENVIRONMENT.lower(): maxDict = English_Environment.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == TRAVEL.lower(): maxDict = English_Travel.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SCIENCE.lower(): maxDict = English_Science.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BUSINESS.lower(): maxDict = English_Business.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == STOCKS.lower(): maxDict = English_Stocks.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == FOOD.lower(): maxDict = English_Food.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == FASHION.lower(): maxDict = English_Fashion.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == MUMBAI.lower(): maxDict = English_Mumbai.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == PUNE.lower(): maxDict = English_Pune.objects.all().aggregate(Max('Cluster_Id')) elif lang.lower() == MARATHI.lower(): if category.lower() == SPORTS.lower(): maxDict = Marathi_Sports.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == TOP_STORIES.lower(): maxDict = Marathi_Top_Stories.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == MAHARASHTRA.lower(): maxDict = Marathi_Maharashtra.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == WORLD.lower(): maxDict = Marathi_World.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == OPINION.lower(): maxDict = Marathi_Opinion.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == HEALTH.lower(): maxDict = Marathi_Health.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == LIFESTYLE.lower(): maxDict = Marathi_Lifestyle.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ENTERTAINMENT.lower(): maxDict = Marathi_Entertainment.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == POLITICS.lower(): maxDict = Marathi_Politics.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ENVIRONMENT.lower(): maxDict = Marathi_Environment.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == TRAVEL.lower(): maxDict = Marathi_Travel.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SCIENCE.lower(): maxDict = Marathi_Science.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BUSINESS.lower(): maxDict = Marathi_Business.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == STOCKS.lower(): maxDict = Marathi_Stocks.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == FASHION.lower(): maxDict = Marathi_Fashion.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == MUMBAI.lower(): maxDict = Marathi_Mumbai.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == PUNE.lower(): maxDict = Marathi_Pune.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == NAGPUR.lower(): maxDict = Marathi_Nagpur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == NASIK.lower(): maxDict = Marathi_Nasik.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == AURANGABAD.lower(): maxDict = Marathi_Aurangabad.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SOLAPUR.lower(): maxDict = Marathi_Solapur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == KOLHAPUR.lower(): maxDict = Marathi_Kolhapur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SATARA.lower(): maxDict = Marathi_Satara.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SANGLI.lower(): maxDict = Marathi_Sangli.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == AKOLA.lower(): maxDict = Marathi_Akola.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == AHMEDNAGAR.lower(): maxDict = Marathi_Ahmednagar.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == JALGAON.lower(): maxDict = Marathi_Jalgaon.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == GOA.lower(): maxDict = Marathi_Goa.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == CHANDRAPUR.lower(): maxDict = Marathi_Chandrapur.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == WARDHA.lower(): maxDict = Marathi_Wardha.objects.all().aggregate(Max('Cluster_Id')) #logger.info("Exited getMaxClusterId ") return maxDict def insertLangCategoryTable(key, lang, category, articleObj, maxClusterId, isRep): #logger.info("Entered insertLangCategoryTable ") if lang.lower() == HINDI.lower(): if category.lower() == SPORTS.lower(): langCategoryObj = Hindi_Sports( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = Hindi_Top_Stories( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == WORLD.lower(): langCategoryObj = Hindi_World( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == OPINION.lower(): langCategoryObj = Hindi_Opinion( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == HEALTH.lower(): langCategoryObj = Hindi_Health( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == LIFESTYLE.lower(): langCategoryObj = Hindi_Lifestyle( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategoryObj = Hindi_Entertainment( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == TECHNOLOGY.lower(): langCategoryObj = Hindi_Technology( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == POLITICS.lower(): langCategoryObj = Hindi_Politics( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ENVIRONMENT.lower(): langCategoryObj = Hindi_Environment( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BOOKS.lower(): langCategoryObj = Hindi_Books( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == TRAVEL.lower(): langCategoryObj = Hindi_Travel( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == SCIENCE.lower(): langCategoryObj = Hindi_Science( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BUSINESS.lower(): langCategoryObj = Hindi_Business( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == STOCKS.lower(): langCategoryObj = Hindi_Stocks( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == FOOD.lower(): langCategoryObj = Hindi_Food( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == WEEKEND.lower(): langCategoryObj = Hindi_Weekend( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == FASHION.lower(): langCategoryObj = Hindi_Fashion( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == AUTO.lower(): langCategoryObj = Hindi_Auto( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == CRIME.lower(): langCategoryObj = Hindi_Crime( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == UTTARPRADESH.lower(): langCategoryObj = Hindi_UttarPradesh( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == UTTARAKHAND.lower(): langCategoryObj = Hindi_Uttarakhand( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == HIMACHALPRADESH.lower(): langCategoryObj = Hindi_HimachalPradesh( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == DELHI.lower(): langCategoryObj = Hindi_Delhi( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == JAMMUKASHMIR.lower(): langCategoryObj = Hindi_JammuKashmir( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == PUNJAB.lower(): langCategoryObj = Hindi_Punjab( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == MADHYAPRADESH.lower(): langCategoryObj = Hindi_MadhyaPradesh( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == JHARKHAND.lower(): langCategoryObj = Hindi_Jharkhand( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BIHAR.lower(): langCategoryObj = Hindi_Bihar( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == HARYANA.lower(): langCategoryObj = Hindi_Haryana( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == CHATTISGARH.lower(): langCategoryObj = Hindi_Chattisgarh( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == RAJASTHAN.lower(): langCategoryObj = Hindi_Rajasthan( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == WESTBENGAL.lower(): langCategoryObj = Hindi_WestBengal( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ORISSA.lower(): langCategoryObj = Hindi_Orissa( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == GUJRAT.lower(): langCategoryObj = Hindi_Gujrat( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == MAHARASHTRA.lower(): langCategoryObj = Hindi_Maharashtra( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == LUCKNOW.lower(): langCategoryObj = Hindi_Lucknow( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ALLAHABAD.lower(): langCategoryObj = Hindi_Allahabad( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == PRATAPGARH.lower(): langCategoryObj = Hindi_Pratapgarh( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == KANPUR.lower(): langCategoryObj = Hindi_Kanpur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == MERATH.lower(): langCategoryObj = Hindi_Merath( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == AGRA.lower(): langCategoryObj = Hindi_Agra( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == NOIDA.lower(): langCategoryObj = Hindi_Noida( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == GAZIABAD.lower(): langCategoryObj = Hindi_Gaziabad( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BAGPAT.lower(): langCategoryObj = Hindi_Bagpat( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == SAHARNPUR.lower(): langCategoryObj = Hindi_Saharnpur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BULANDSHAHAR.lower(): langCategoryObj = Hindi_Bulandshahar( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == VARANASI.lower(): langCategoryObj = Hindi_Varanasi( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == GORAKHPUR.lower(): langCategoryObj = Hindi_Gorakhpur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == JHANSI.lower(): langCategoryObj = Hindi_Jhansi( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == MUZAFFARNAGAR.lower(): langCategoryObj = Hindi_Muzaffarnagar( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == SITAPUR.lower(): langCategoryObj = Hindi_Sitapur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == JAUNPUR.lower(): langCategoryObj = Hindi_Jaunpur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == AZAMGARH.lower(): langCategoryObj = Hindi_Azamgarh( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == MORADABAD.lower(): langCategoryObj = Hindi_Moradabad( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BAREILLY.lower(): langCategoryObj = Hindi_Bareilly( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BALIA.lower(): langCategoryObj = Hindi_Balia( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ALIGARH.lower(): langCategoryObj = Hindi_Aligarh( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == MATHURA.lower(): langCategoryObj = Hindi_Mathura( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BHOPAL.lower(): langCategoryObj = Hindi_Bhopal( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == INDORE.lower(): langCategoryObj = Hindi_Indore( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == GWALIOR.lower(): langCategoryObj = Hindi_Gwalior( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == JABALPUR.lower(): langCategoryObj = Hindi_Jabalpur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == UJJAIN.lower(): langCategoryObj = Hindi_Ujjain( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == RATLAM.lower(): langCategoryObj = Hindi_Ratlam( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == SAGAR.lower(): langCategoryObj = Hindi_Sagar( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == DEWAS.lower(): langCategoryObj = Hindi_Dewas( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == SATNA.lower(): langCategoryObj = Hindi_Satna( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == REWA.lower(): langCategoryObj = Hindi_Rewa( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == PATNA.lower(): langCategoryObj = Hindi_Patna( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BHAGALPUR.lower(): langCategoryObj = Hindi_Bhagalpur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == MUJAFFARPUR.lower(): langCategoryObj = Hindi_Mujaffarpur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == GAYA.lower(): langCategoryObj = Hindi_Gaya( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == DARBHANGA.lower(): langCategoryObj = Hindi_Darbhanga( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == POORNIYA.lower(): langCategoryObj = Hindi_Poorniya( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == SEWAN.lower(): langCategoryObj = Hindi_Sewan( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BEGUSARAI.lower(): langCategoryObj = Hindi_Begusarai( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == KATIHAR.lower(): langCategoryObj = Hindi_Katihar( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == JAIPUR.lower(): langCategoryObj = Hindi_Jaipur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == UDAIPUR.lower(): langCategoryObj = Hindi_Udaipur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == JODHPUR.lower(): langCategoryObj = Hindi_Jodhpur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == AJMER.lower(): langCategoryObj = Hindi_Ajmer( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BIKANER.lower(): langCategoryObj = Hindi_Bikaner( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ALWAR.lower(): langCategoryObj = Hindi_Alwar( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == SIKAR.lower(): langCategoryObj = Hindi_Sikar( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == KOTA.lower(): langCategoryObj = Hindi_Kota( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BHILWARA.lower(): langCategoryObj = Hindi_Bhilwara( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BHARATPUR.lower(): langCategoryObj = Hindi_Bharatpur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == CHHATIS.lower(): langCategoryObj = Hindi_Chhatis( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == RAIPUR.lower(): langCategoryObj = Hindi_Raipur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BHILAI.lower(): langCategoryObj = Hindi_Bhilai( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == RAJNANDGAO.lower(): langCategoryObj = Hindi_Rajnandgao( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == RAIGARH.lower(): langCategoryObj = Hindi_Raigarh( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == JAGDALPUR.lower(): langCategoryObj = Hindi_Jagdalpur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == KORVA.lower(): langCategoryObj = Hindi_Korva( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == RANCHI.lower(): langCategoryObj = Hindi_Ranchi( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == DHANBAD.lower(): langCategoryObj = Hindi_Dhanbad( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == JAMSHEDPUR.lower(): langCategoryObj = Hindi_Jamshedpur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == GIRIDIHI.lower(): langCategoryObj = Hindi_Giridihi( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == HAZARIBAGH.lower(): langCategoryObj = Hindi_Hazaribagh( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BOKARO.lower(): langCategoryObj = Hindi_Bokaro( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == DEHRADUN.lower(): langCategoryObj = Hindi_Dehradun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == NAINITAAL.lower(): langCategoryObj = Hindi_Nainitaal( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == HARIDWAAR.lower(): langCategoryObj = Hindi_Haridwaar( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ALMORAH.lower(): langCategoryObj = Hindi_Almorah( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == UDDHAMSINGHNAGAR.lower(): langCategoryObj = Hindi_UddhamSinghNagar( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == SIMLA.lower(): langCategoryObj = Hindi_Simla( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == MANDI.lower(): langCategoryObj = Hindi_Mandi( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BILASPUR.lower(): langCategoryObj = Hindi_Bilaspur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == AMRITSAR.lower(): langCategoryObj = Hindi_Amritsar( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == JALANDHAR.lower(): langCategoryObj = Hindi_Jalandhar( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == LUDHIANA.lower(): langCategoryObj = Hindi_Ludhiana( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ROPARH.lower(): langCategoryObj = Hindi_Roparh( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == CHANDIGARH.lower(): langCategoryObj = Hindi_Chandigarh( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ROHTAK.lower(): langCategoryObj = Hindi_Rohtak( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == PANCHKULA.lower(): langCategoryObj = Hindi_Panchkula( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == AMBALA.lower(): langCategoryObj = Hindi_Ambala( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == PANIPAT.lower(): langCategoryObj = Hindi_Panipat( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == GURGAON.lower(): langCategoryObj = Hindi_Gurgaon( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == HISSAR.lower(): langCategoryObj = Hindi_Hissar( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == JAMMU.lower(): langCategoryObj = Hindi_Jammu( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == SRINAGAR.lower(): langCategoryObj = Hindi_Srinagar( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == POONCH.lower(): langCategoryObj = Hindi_Poonch( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == KOLKATA.lower(): langCategoryObj = Hindi_Kolkata( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == JALPAIGURHI.lower(): langCategoryObj = Hindi_Jalpaigurhi( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == DARJEELING.lower(): langCategoryObj = Hindi_Darjeeling( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ASANSOL.lower(): langCategoryObj = Hindi_Asansol( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == SILIGURHI.lower(): langCategoryObj = Hindi_Siligurhi( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BHUVANESHWAR.lower(): langCategoryObj = Hindi_Bhuvaneshwar( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == PURI.lower(): langCategoryObj = Hindi_Puri( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == CUTTACK.lower(): langCategoryObj = Hindi_Cuttack( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == AHMEDABAD.lower(): langCategoryObj = Hindi_Ahmedabad( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == SURAT.lower(): langCategoryObj = Hindi_Surat( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == VADODARA.lower(): langCategoryObj = Hindi_Vadodara( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == MUMBAI.lower(): langCategoryObj = Hindi_Mumbai( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == NAGPUR.lower(): langCategoryObj = Hindi_Nagpur( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == PUNE.lower(): langCategoryObj = Hindi_Pune( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == ECONOMY.lower(): langCategoryObj = English_Economy(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == SPORTS.lower(): langCategoryObj = English_Sports(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = English_Top_Stories(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == WORLD.lower(): langCategoryObj = English_World(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == OPINION.lower(): langCategoryObj = English_Opinion(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == HEALTH.lower(): langCategoryObj = English_Health(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == LIFESTYLE.lower(): langCategoryObj = English_Lifestyle(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategoryObj = English_Entertainment(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == TECHNOLOGY.lower(): langCategoryObj = English_Technology(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == POLITICS.lower(): langCategoryObj = English_Politics(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == ENVIRONMENT.lower(): langCategoryObj = English_Environment(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == BOOKS.lower(): langCategoryObj = English_Books(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == TRAVEL.lower(): langCategoryObj = English_Travel(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == SCIENCE.lower(): langCategoryObj = English_Science(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == BUSINESS.lower(): langCategoryObj = English_Business(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == STOCKS.lower(): langCategoryObj = English_Stocks(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == FOOD.lower(): langCategoryObj = English_Food(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == WEEKEND.lower(): langCategoryObj = English_Weekend(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == FASHION.lower(): langCategoryObj = English_Fashion(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == MUMBAI.lower(): langCategoryObj = English_Mumbai(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == PUNE.lower(): langCategoryObj = English_Pune(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == MARATHI.lower(): if category.lower() == ECONOMY.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_economy (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == SPORTS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_sports (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == TOP_STORIES.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_top_stories (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == MAHARASHTRA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_maharashtra (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == WORLD.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_world (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == OPINION.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_opinion (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == HEALTH.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_health (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == LIFESTYLE.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_lifestyle (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == ENTERTAINMENT.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_entertainment (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == TECHNOLOGY.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_technology (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == POLITICS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_politics (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == ENVIRONMENT.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_environment (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == BOOKS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_books (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == TRAVEL.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_travel (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == SCIENCE.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_science (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == BUSINESS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_business (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == STOCKS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_stocks (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == FOOD.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_food (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == WEEKEND.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_weekend (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == FASHION.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_fashion (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == MUMBAI.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_mumbai (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == PUNE.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_pune (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == NAGPUR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_nagpur (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == NASIK.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_nasik (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == AURANGABAD.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_aurangabad (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == SOLAPUR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_solapur (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == KOLHAPUR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_kolhapur (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == SATARA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_satara (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == SANGLI.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_sangli (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == AKOLA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_akola (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == AHMEDNAGAR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_ahmednagar (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == JALGAON.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_jalgaon (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == GOA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_goa (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == CHANDRAPUR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_chandrapur (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) if lang.lower() == MARATHI.lower(): if category.lower() == WARDHA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_wardha (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''', [maxClusterId, isRep, langObj.id, categoryObj.id, key]) #logger.info("Exited insertLangCategoryTable ") def insertLangCategoryRerunTable(key, lang, category, articleObj, maxClusterId, isRep): #logger.info("Entered insertLangCategoryRerunTable ") if lang.lower() == HINDI.lower(): if category.lower() == SPORTS.lower(): langCategoryObj = Hindi_Sports_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = Hindi_Top_Stories_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == WORLD.lower(): langCategoryObj = Hindi_World_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == OPINION.lower(): langCategoryObj = Hindi_Opinion_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == HEALTH.lower(): langCategoryObj = Hindi_Health_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == LIFESTYLE.lower(): langCategoryObj = Hindi_Lifestyle_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategoryObj = Hindi_Entertainment_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == TECHNOLOGY.lower(): langCategoryObj = Hindi_Technology_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == POLITICS.lower(): langCategoryObj = Hindi_Politics_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ENVIRONMENT.lower(): langCategoryObj = Hindi_Environment_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == TRAVEL.lower(): langCategoryObj = Hindi_Travel_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == SCIENCE.lower(): langCategoryObj = Hindi_Science_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BUSINESS.lower(): langCategoryObj = Hindi_Business_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == STOCKS.lower(): langCategoryObj = Hindi_Stocks_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == FOOD.lower(): langCategoryObj = Hindi_Food_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == WEEKEND.lower(): langCategoryObj = Hindi_Weekend_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == FASHION.lower(): langCategoryObj = Hindi_Fashion_Rerun( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = maxClusterId, Is_Rep = isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == ECONOMY.lower(): langCategoryObj = English_Economy_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == SPORTS.lower(): langCategoryObj = English_Sports_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = English_Top_Stories_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == WORLD.lower(): langCategoryObj = English_World_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == OPINION.lower(): langCategoryObj = English_Opinion_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == HEALTH.lower(): langCategoryObj = English_Health_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == LIFESTYLE.lower(): langCategoryObj = English_Lifestyle_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategoryObj = English_Entertainment_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == TECHNOLOGY.lower(): langCategoryObj = English_Technology_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == POLITICS.lower(): langCategoryObj = English_Politics_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == ENVIRONMENT.lower(): langCategoryObj = English_Environment_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == BOOKS.lower(): langCategoryObj = English_Books_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == TRAVEL.lower(): langCategoryObj = English_Travel_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == SCIENCE.lower(): langCategoryObj = English_Science_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == BUSINESS.lower(): langCategoryObj = English_Business_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == STOCKS.lower(): langCategoryObj = English_Stocks_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == FOOD.lower(): langCategoryObj = English_Food_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == WEEKEND.lower(): langCategoryObj = English_Weekend_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == FASHION.lower(): langCategoryObj = English_Fashion_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == MUMBAI.lower(): langCategoryObj = English_Mumbai_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == PUNE.lower(): langCategoryObj = English_Pune_Rerun(Article=articleObj, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=maxClusterId, Is_Rep=isRep) langCategoryObj.save() if lang.lower() == MARATHI.lower(): if category.lower() == ECONOMY.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_economy_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == SPORTS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_sports_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == TOP_STORIES.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_top_stories_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == WORLD.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_world_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == OPINION.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_opinion_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == HEALTH.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_health_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == LIFESTYLE.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_lifestyle_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == ENTERTAINMENT.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_entertainment_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == TECHNOLOGY.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_technology_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == POLITICS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_politics_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == ENVIRONMENT.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_environment_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == BOOKS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_books_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == TRAVEL.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_travel_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == SCIENCE.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_science_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == BUSINESS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_business_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == STOCKS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_stocks_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == FOOD.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_food_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == WEEKEND.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_weekend_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == FASHION.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_fashion_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == MUMBAI.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_mumbai_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == PUNE.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_pune_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == NAGPUR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_nagpur_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == NASIK.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_nasik_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == AURANGABAD.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_aurangabad_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == SOLAPUR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_solapur_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == KOLHAPUR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_kolhapur_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == SATARA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_satara_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == SANGLI.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_sangli_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == AKOLA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_akola_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == AHMEDNAGAR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_ahmednagar_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == JALGAON.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_jalgaon_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == GOA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_goa_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == CHANDRAPUR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_chandrapur_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == WARDHA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_wardha_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) if lang.lower() == MARATHI.lower(): if category.lower() == MAHARASHTRA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_maharashtra_rerun (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,TITLE,SUMMARY,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[maxClusterId,isRep,langObj.id,categoryObj.id,key]) #logger.info("Exited insertLangCategoryRerunTable ") def selectLangCategoryTable(lang, category, URL): #logger.info("Entered selectLangCategoryTable ") if lang.lower() == ENGLISH.lower(): if category.lower() == ECONOMY.lower(): try: langCategoryObj = English_Economy.objects.get(URL=URL) return 1 except English_Economy.DoesNotExist: return 0 elif category.lower() == SPORTS.lower(): try: langCategoryObj = English_Sports.objects.get(URL=URL) return 1 except English_Sports.DoesNotExist: return 0 elif category.lower() == TOP_STORIES.lower(): try: langCategoryObj = English_Top_Stories.objects.get(URL=URL) return 1 except English_Top_Stories.DoesNotExist: return 0 elif category.lower() == WORLD.lower(): try: langCategoryObj = English_World.objects.get(URL=URL) return 1 except English_World.DoesNotExist: return 0 elif category.lower() == OPINION.lower(): try: langCategoryObj = English_Opinion.objects.get(URL=URL) return 1 except English_Opinion.DoesNotExist: return 0 elif category.lower() == HEALTH.lower(): try: langCategoryObj = English_Health.objects.get(URL=URL) return 1 except English_Health.DoesNotExist: return 0 elif category.lower() == LIFESTYLE.lower(): try: langCategoryObj = English_Lifestyle.objects.get(URL=URL) return 1 except English_Lifestyle.DoesNotExist: return 0 elif category.lower() == ENTERTAINMENT.lower(): try: langCategoryObj = English_Entertainment.objects.get(URL=URL) return 1 except English_Entertainment.DoesNotExist: return 0 elif category.lower() == TECHNOLOGY.lower(): try: langCategoryObj = English_Technology.objects.get(URL=URL) return 1 except English_Technology.DoesNotExist: return 0 elif category.lower() == POLITICS.lower(): try: langCategoryObj = English_Politics.objects.get(URL=URL) return 1 except English_Politics.DoesNotExist: return 0 elif category.lower() == ENVIRONMENT.lower(): try: langCategoryObj = English_Environment.objects.get(URL=URL) return 1 except English_Environment.DoesNotExist: return 0 elif category.lower() == BOOKS.lower(): try: langCategoryObj = English_Books.objects.get(URL=URL) return 1 except English_Books.DoesNotExist: return 0 elif category.lower() == TRAVEL.lower(): try: langCategoryObj = English_Travel.objects.get(URL=URL) return 1 except English_Travel.DoesNotExist: return 0 elif category.lower() == SCIENCE.lower(): try: langCategoryObj = English_Science.objects.get(URL=URL) return 1 except English_Science.DoesNotExist: return 0 elif category.lower() == BUSINESS.lower(): try: langCategoryObj = English_Business.objects.get(URL=URL) return 1 except English_Business.DoesNotExist: return 0 elif category.lower() == STOCKS.lower(): try: langCategoryObj = English_Stocks.objects.get(URL=URL) return 1 except English_Stocks.DoesNotExist: return 0 elif category.lower() == FOOD.lower(): try: langCategoryObj = English_Food.objects.get(URL=URL) return 1 except English_Food.DoesNotExist: return 0 elif category.lower() == FASHION.lower(): try: langCategoryObj = English_Fashion.objects.get(URL=URL) return 1 except English_Fashion.DoesNotExist: return 0 elif category.lower() == MUMBAI.lower(): try: langCategoryObj = English_Mumbai.objects.get(URL=URL) return 1 except English_Mumbai.DoesNotExist: return 0 elif category.lower() == PUNE.lower(): try: langCategoryObj = English_Pune.objects.get(URL=URL) return 1 except English_Pune.DoesNotExist: return 0 elif lang.lower() == MARATHI.lower(): if category.lower() == ECONOMY.lower(): try: langCategoryObj = Marathi_Economy.objects.get(URL=URL) return 1 except Marathi_Economy.DoesNotExist: return 0 elif category.lower() == SPORTS.lower(): try: langCategoryObj = Marathi_Sports.objects.get(URL=URL) return 1 except Marathi_Sports.DoesNotExist: return 0 elif category.lower() == TOP_STORIES.lower(): try: langCategoryObj = Marathi_Top_Stories.objects.get(URL=URL) return 1 except Marathi_Top_Stories.DoesNotExist: return 0 elif category.lower() == MAHARASHTRA.lower(): try: langCategoryObj = Marathi_Maharashtra.objects.get(URL=URL) return 1 except Marathi_Maharashtra.DoesNotExist: return 0 elif category.lower() == WORLD.lower(): try: langCategoryObj = Marathi_World.objects.get(URL=URL) return 1 except Marathi_World.DoesNotExist: return 0 elif category.lower() == OPINION.lower(): try: langCategoryObj = Marathi_Opinion.objects.get(URL=URL) return 1 except Marathi_Opinion.DoesNotExist: return 0 elif category.lower() == HEALTH.lower(): try: langCategoryObj = Marathi_Health.objects.get(URL=URL) return 1 except Marathi_Health.DoesNotExist: return 0 elif category.lower() == LIFESTYLE.lower(): try: langCategoryObj = Marathi_Lifestyle.objects.get(URL=URL) return 1 except Marathi_Lifestyle.DoesNotExist: return 0 elif category.lower() == ENTERTAINMENT.lower(): try: langCategoryObj = Marathi_Entertainment.objects.get(URL=URL) return 1 except Marathi_Entertainment.DoesNotExist: return 0 elif category.lower() == TECHNOLOGY.lower(): try: langCategoryObj = Marathi_Technology.objects.get(URL=URL) return 1 except Marathi_Technology.DoesNotExist: return 0 elif category.lower() == POLITICS.lower(): try: langCategoryObj = Marathi_Politics.objects.get(URL=URL) return 1 except Marathi_Politics.DoesNotExist: return 0 elif category.lower() == ENVIRONMENT.lower(): try: langCategoryObj = Marathi_Environment.objects.get(URL=URL) return 1 except Marathi_Environment.DoesNotExist: return 0 elif category.lower() == TRAVEL.lower(): try: langCategoryObj = Marathi_Travel.objects.get(URL=URL) return 1 except Marathi_Travel.DoesNotExist: return 0 elif category.lower() == SCIENCE.lower(): try: langCategoryObj = Marathi_Science.objects.get(URL=URL) return 1 except Marathi_Science.DoesNotExist: return 0 elif category.lower() == BUSINESS.lower(): try: langCategoryObj = Marathi_Business.objects.get(URL=URL) return 1 except Marathi_Business.DoesNotExist: return 0 elif category.lower() == STOCKS.lower(): try: langCategoryObj = Marathi_Stocks.objects.get(URL=URL) return 1 except Marathi_Stocks.DoesNotExist: return 0 elif category.lower() == FOOD.lower(): try: langCategoryObj = Marathi_Food.objects.get(URL=URL) return 1 except Marathi_Food.DoesNotExist: return 0 elif category.lower() == FASHION.lower(): try: langCategoryObj = Marathi_Fashion.objects.get(URL=URL) return 1 except Marathi_Fashion.DoesNotExist: return 0 elif category.lower() == MUMBAI.lower(): try: langCategoryObj = Marathi_Mumbai.objects.get(URL=URL) return 1 except Marathi_Mumbai.DoesNotExist: return 0 elif category.lower() == PUNE.lower(): try: langCategoryObj = Marathi_Pune.objects.get(URL=URL) return 1 except Marathi_Pune.DoesNotExist: return 0 elif category.lower() == NAGPUR.lower(): try: langCategoryObj = Marathi_Nagpur.objects.get(URL=URL) return 1 except Marathi_Nagpur.DoesNotExist: return 0 elif category.lower() == NASIK.lower(): try: langCategoryObj = Marathi_Nasik.objects.get(URL=URL) return 1 except Marathi_Nasik.DoesNotExist: return 0 elif category.lower() == AURANGABAD.lower(): try: langCategoryObj = Marathi_Aurangabad.objects.get(URL=URL) return 1 except Marathi_Aurangabad.DoesNotExist: return 0 elif category.lower() == SOLAPUR.lower(): try: langCategoryObj = Marathi_Solapur.objects.get(URL=URL) return 1 except Marathi_Solapur.DoesNotExist: return 0 elif category.lower() == KOLHAPUR.lower(): try: langCategoryObj = Marathi_Kolhapur.objects.get(URL=URL) return 1 except Marathi_Kolhapur.DoesNotExist: return 0 elif category.lower() == SATARA.lower(): try: langCategoryObj = Marathi_Satara.objects.get(URL=URL) return 1 except Marathi_Satara.DoesNotExist: return 0 elif category.lower() == SANGLI.lower(): try: langCategoryObj = Marathi_Sangli.objects.get(URL=URL) return 1 except Marathi_Sangli.DoesNotExist: return 0 elif category.lower() == AKOLA.lower(): try: langCategoryObj = Marathi_Akola.objects.get(URL=URL) return 1 except Marathi_Akola.DoesNotExist: return 0 elif category.lower() == AHMEDNAGAR.lower(): try: langCategoryObj = Marathi_Ahmednagar.objects.get(URL=URL) return 1 except Marathi_Ahmednagar.DoesNotExist: return 0 elif category.lower() == JALGAON.lower(): try: langCategoryObj = Marathi_Jalgaon.objects.get(URL=URL) return 1 except Marathi_Jalgaon.DoesNotExist: return 0 elif category.lower() == GOA.lower(): try: langCategoryObj = Marathi_Goa.objects.get(URL=URL) return 1 except Marathi_Goa.DoesNotExist: return 0 elif category.lower() == CHANDRAPUR.lower(): try: langCategoryObj = Marathi_Chandrapur.objects.get(URL=URL) return 1 except Marathi_Chandrapur.DoesNotExist: return 0 elif category.lower() == WARDHA.lower(): try: langCategoryObj = Marathi_Wardha.objects.get(URL=URL) return 1 except Marathi_Wardha.DoesNotExist: return 0 elif lang.lower() == HINDI.lower(): if category.lower() == SPORTS.lower(): try: langCategoryObj = Hindi_Sports.objects.get(URL = URL) return True except Hindi_Sports.DoesNotExist: return False if category.lower() == TOP_STORIES.lower(): try: langCategoryObj = Hindi_Top_Stories.objects.get(URL = URL) return True except Hindi_Top_Stories.DoesNotExist: return False if category.lower() == WORLD.lower(): try: langCategoryObj = Hindi_World.objects.get(URL = URL) return True except Hindi_World.DoesNotExist: return False if category.lower() == OPINION.lower(): try: langCategoryObj = Hindi_Opinion.objects.get(URL = URL) return True except Hindi_Opinion.DoesNotExist: return False if category.lower() == HEALTH.lower(): try: langCategoryObj = Hindi_Health.objects.get(URL = URL) return True except Hindi_Health.DoesNotExist: return False if category.lower() == LIFESTYLE.lower(): try: langCategoryObj = Hindi_Lifestyle.objects.get(URL = URL) return True except Hindi_Lifestyle.DoesNotExist: return False if category.lower() == ENTERTAINMENT.lower(): try: langCategoryObj = Hindi_Entertainment.objects.get(URL = URL) return True except Hindi_Entertainment.DoesNotExist: return False if category.lower() == TECHNOLOGY.lower(): try: langCategoryObj = Hindi_Technology.objects.get(URL = URL) return True except Hindi_Technology.DoesNotExist: return False if category.lower() == POLITICS.lower(): try: langCategoryObj = Hindi_Politics.objects.get(URL = URL) return True except Hindi_Politics.DoesNotExist: return False if category.lower() == ENVIRONMENT.lower(): try: langCategoryObj = Hindi_Environment.objects.get(URL = URL) return True except Hindi_Environment.DoesNotExist: return False if category.lower() == BOOKS.lower(): try: langCategoryObj = Hindi_Books.objects.get(URL = URL) return True except Hindi_Books.DoesNotExist: return False if category.lower() == TRAVEL.lower(): try: langCategoryObj = Hindi_Travel.objects.get(URL = URL) return True except Hindi_Travel.DoesNotExist: return False if category.lower() == SCIENCE.lower(): try: langCategoryObj = Hindi_Science.objects.get(URL = URL) return True except Hindi_Science.DoesNotExist: return False if category.lower() == BUSINESS.lower(): try: langCategoryObj = Hindi_Business.objects.get(URL = URL) return True except Hindi_Business.DoesNotExist: return False if category.lower() == STOCKS.lower(): try: langCategoryObj = Hindi_Stocks.objects.get(URL = URL) return True except Hindi_Stocks.DoesNotExist: return False if category.lower() == FOOD.lower(): try: langCategoryObj = Hindi_Food.objects.get(URL = URL) return True except Hindi_Food.DoesNotExist: return False if category.lower() == WEEKEND.lower(): try: langCategoryObj = Hindi_Weekend.objects.get(URL = URL) return True except Hindi_Weekend.DoesNotExist: return False if category.lower() == FASHION.lower(): try: langCategoryObj = Hindi_Fashion.objects.get(URL = URL) return True except Hindi_Fashion.DoesNotExist: return False if category.lower() == CRIME.lower(): try: langCategoryObj = Hindi_Crime.objects.get(URL = URL) return True except Hindi_Crime.DoesNotExist: return False if category.lower() == AUTO.lower(): try: langCategoryObj = Hindi_Auto.objects.get(URL = URL) return True except Hindi_Auto.DoesNotExist: return False if category.lower() == UTTARPRADESH.lower(): try: langCategoryObj = Hindi_UttarPradesh.objects.get(URL = URL) return True except Hindi_UttarPradesh.DoesNotExist: return False if category.lower() == UTTARAKHAND.lower(): try: langCategoryObj = Hindi_Uttarakhand.objects.get(URL = URL) return True except Hindi_Uttarakhand.DoesNotExist: return False if category.lower() == HIMACHALPRADESH.lower(): try: langCategoryObj = Hindi_HimachalPradesh.objects.get(URL = URL) return True except Hindi_HimachalPradesh.DoesNotExist: return False if category.lower() == DELHI.lower(): try: langCategoryObj = Hindi_Delhi.objects.get(URL = URL) return True except Hindi_Delhi.DoesNotExist: return False if category.lower() == JAMMUKASHMIR.lower(): try: langCategoryObj = Hindi_JammuKashmir.objects.get(URL = URL) return True except Hindi_JammuKashmir.DoesNotExist: return False if category.lower() == PUNJAB.lower(): try: langCategoryObj = Hindi_Punjab.objects.get(URL = URL) return True except Hindi_Punjab.DoesNotExist: return False if category.lower() == MADHYAPRADESH.lower(): try: langCategoryObj = Hindi_MadhyaPradesh.objects.get(URL = URL) return True except Hindi_MadhyaPradesh.DoesNotExist: return False if category.lower() == JHARKHAND.lower(): try: langCategoryObj = Hindi_Jharkhand.objects.get(URL = URL) return True except Hindi_Jharkhand.DoesNotExist: return False if category.lower() == BIHAR.lower(): try: langCategoryObj = Hindi_Bihar.objects.get(URL = URL) return True except Hindi_Bihar.DoesNotExist: return False if category.lower() == HARYANA.lower(): try: langCategoryObj = Hindi_Haryana.objects.get(URL = URL) return True except Hindi_Haryana.DoesNotExist: return False if category.lower() == CHATTISGARH.lower(): try: langCategoryObj = Hindi_Chattisgarh.objects.get(URL = URL) return True except Hindi_Chattisgarh.DoesNotExist: return False if category.lower() == RAJASTHAN.lower(): try: langCategoryObj = Hindi_Rajasthan.objects.get(URL = URL) return True except Hindi_Rajasthan.DoesNotExist: return False if category.lower() == WESTBENGAL.lower(): try: langCategoryObj = Hindi_WestBengal.objects.get(URL = URL) return True except Hindi_WestBengal.DoesNotExist: return False if category.lower() == ORISSA.lower(): try: langCategoryObj = Hindi_Orissa.objects.get(URL = URL) return True except Hindi_Orissa.DoesNotExist: return False if category.lower() == GUJRAT.lower(): try: langCategoryObj = Hindi_Gujrat.objects.get(URL = URL) return True except Hindi_Gujrat.DoesNotExist: return False if category.lower() == MAHARASHTRA.lower(): try: langCategoryObj = Hindi_Maharashtra.objects.get(URL = URL) return True except Hindi_Maharashtra.DoesNotExist: return False if category.lower() == LUCKNOW.lower(): try: langCategoryObj = Hindi_Lucknow.objects.get(URL = URL) return True except Hindi_Lucknow.DoesNotExist: return False if category.lower() == ALLAHABAD.lower(): try: langCategoryObj = Hindi_Allahabad.objects.get(URL = URL) return True except Hindi_Allahabad.DoesNotExist: return False if category.lower() == PRATAPGARH.lower(): try: langCategoryObj = Hindi_Pratapgarh.objects.get(URL = URL) return True except Hindi_Pratapgarh.DoesNotExist: return False if category.lower() == KANPUR.lower(): try: langCategoryObj = Hindi_Kanpur.objects.get(URL = URL) return True except Hindi_Kanpur.DoesNotExist: return False if category.lower() == MERATH.lower(): try: langCategoryObj = Hindi_Merath.objects.get(URL = URL) return True except Hindi_Merath.DoesNotExist: return False if category.lower() == AGRA.lower(): try: langCategoryObj = Hindi_Agra.objects.get(URL = URL) return True except Hindi_Agra.DoesNotExist: return False if category.lower() == NOIDA.lower(): try: langCategoryObj = Hindi_Noida.objects.get(URL = URL) return True except Hindi_Noida.DoesNotExist: return False if category.lower() == GAZIABAD.lower(): try: langCategoryObj = Hindi_Gaziabad.objects.get(URL = URL) return True except Hindi_Gaziabad.DoesNotExist: return False if category.lower() == BAGPAT.lower(): try: langCategoryObj = Hindi_Bagpat.objects.get(URL = URL) return True except Hindi_Bagpat.DoesNotExist: return False if category.lower() == SAHARNPUR.lower(): try: langCategoryObj = Hindi_Saharnpur.objects.get(URL = URL) return True except Hindi_Saharnpur.DoesNotExist: return False if category.lower() == BULANDSHAHAR.lower(): try: langCategoryObj = Hindi_Bulandshahar.objects.get(URL = URL) return True except Hindi_Bulandshahar.DoesNotExist: return False if category.lower() == VARANASI.lower(): try: langCategoryObj = Hindi_Varanasi.objects.get(URL = URL) return True except Hindi_Varanasi.DoesNotExist: return False if category.lower() == GORAKHPUR.lower(): try: langCategoryObj = Hindi_Gorakhpur.objects.get(URL = URL) return True except Hindi_Gorakhpur.DoesNotExist: return False if category.lower() == JHANSI.lower(): try: langCategoryObj = Hindi_Jhansi.objects.get(URL = URL) return True except Hindi_Jhansi.DoesNotExist: return False if category.lower() == MUZAFFARNAGAR.lower(): try: langCategoryObj = Hindi_Muzaffarnagar.objects.get(URL = URL) return True except Hindi_Muzaffarnagar.DoesNotExist: return False if category.lower() == SITAPUR.lower(): try: langCategoryObj = Hindi_Sitapur.objects.get(URL = URL) return True except Hindi_Sitapur.DoesNotExist: return False if category.lower() == JAUNPUR.lower(): try: langCategoryObj = Hindi_Jaunpur.objects.get(URL = URL) return True except Hindi_Jaunpur.DoesNotExist: return False if category.lower() == AZAMGARH.lower(): try: langCategoryObj = Hindi_Azamgarh.objects.get(URL = URL) return True except Hindi_Azamgarh.DoesNotExist: return False if category.lower() == MORADABAD.lower(): try: langCategoryObj = Hindi_Moradabad.objects.get(URL = URL) return True except Hindi_Moradabad.DoesNotExist: return False if category.lower() == BAREILLY.lower(): try: langCategoryObj = Hindi_Bareilly.objects.get(URL = URL) return True except Hindi_Bareilly.DoesNotExist: return False if category.lower() == BALIA.lower(): try: langCategoryObj = Hindi_Balia.objects.get(URL = URL) return True except Hindi_Balia.DoesNotExist: return False if category.lower() == ALIGARH.lower(): try: langCategoryObj = Hindi_Aligarh.objects.get(URL = URL) return True except Hindi_Aligarh.DoesNotExist: return False if category.lower() == MATHURA.lower(): try: langCategoryObj = Hindi_Mathura.objects.get(URL = URL) return True except Hindi_Mathura.DoesNotExist: return False if category.lower() == BHOPAL.lower(): try: langCategoryObj = Hindi_Bhopal.objects.get(URL = URL) return True except Hindi_Bhopal.DoesNotExist: return False if category.lower() == INDORE.lower(): try: langCategoryObj = Hindi_Indore.objects.get(URL = URL) return True except Hindi_Indore.DoesNotExist: return False if category.lower() == GWALIOR.lower(): try: langCategoryObj = Hindi_Gwalior.objects.get(URL = URL) return True except Hindi_Gwalior.DoesNotExist: return False if category.lower() == JABALPUR.lower(): try: langCategoryObj = Hindi_Jabalpur.objects.get(URL = URL) return True except Hindi_Jabalpur.DoesNotExist: return False if category.lower() == UJJAIN.lower(): try: langCategoryObj = Hindi_Ujjain.objects.get(URL = URL) return True except Hindi_Ujjain.DoesNotExist: return False if category.lower() == RATLAM.lower(): try: langCategoryObj = Hindi_Ratlam.objects.get(URL = URL) return True except Hindi_Ratlam.DoesNotExist: return False if category.lower() == SAGAR.lower(): try: langCategoryObj = Hindi_Sagar.objects.get(URL = URL) return True except Hindi_Sagar.DoesNotExist: return False if category.lower() == DEWAS.lower(): try: langCategoryObj = Hindi_Dewas.objects.get(URL = URL) return True except Hindi_Dewas.DoesNotExist: return False if category.lower() == SATNA.lower(): try: langCategoryObj = Hindi_Satna.objects.get(URL = URL) return True except Hindi_Satna.DoesNotExist: return False if category.lower() == REWA.lower(): try: langCategoryObj = Hindi_Rewa.objects.get(URL = URL) return True except Hindi_Rewa.DoesNotExist: return False if category.lower() == PATNA.lower(): try: langCategoryObj = Hindi_Patna.objects.get(URL = URL) return True except Hindi_Patna.DoesNotExist: return False if category.lower() == BHAGALPUR.lower(): try: langCategoryObj = Hindi_Bhagalpur.objects.get(URL = URL) return True except Hindi_Bhagalpur.DoesNotExist: return False if category.lower() == MUJAFFARPUR.lower(): try: langCategoryObj = Hindi_Mujaffarpur.objects.get(URL = URL) return True except Hindi_Mujaffarpur.DoesNotExist: return False if category.lower() == GAYA.lower(): try: langCategoryObj = Hindi_Gaya.objects.get(URL = URL) return True except Hindi_Gaya.DoesNotExist: return False if category.lower() == DARBHANGA.lower(): try: langCategoryObj = Hindi_Darbhanga.objects.get(URL = URL) return True except Hindi_Darbhanga.DoesNotExist: return False if category.lower() == POORNIYA.lower(): try: langCategoryObj = Hindi_Poorniya.objects.get(URL = URL) return True except Hindi_Poorniya.DoesNotExist: return False if category.lower() == SEWAN.lower(): try: langCategoryObj = Hindi_Sewan.objects.get(URL = URL) return True except Hindi_Sewan.DoesNotExist: return False if category.lower() == BEGUSARAI.lower(): try: langCategoryObj = Hindi_Begusarai.objects.get(URL = URL) return True except Hindi_Begusarai.DoesNotExist: return False if category.lower() == KATIHAR.lower(): try: langCategoryObj = Hindi_Katihar.objects.get(URL = URL) return True except Hindi_Katihar.DoesNotExist: return False if category.lower() == JAIPUR.lower(): try: langCategoryObj = Hindi_Jaipur.objects.get(URL = URL) return True except Hindi_Jaipur.DoesNotExist: return False if category.lower() == UDAIPUR.lower(): try: langCategoryObj = Hindi_Udaipur.objects.get(URL = URL) return True except Hindi_Udaipur.DoesNotExist: return False if category.lower() == JODHPUR.lower(): try: langCategoryObj = Hindi_Jodhpur.objects.get(URL = URL) return True except Hindi_Jodhpur.DoesNotExist: return False if category.lower() == AJMER.lower(): try: langCategoryObj = Hindi_Ajmer.objects.get(URL = URL) return True except Hindi_Ajmer.DoesNotExist: return False if category.lower() == BIKANER.lower(): try: langCategoryObj = Hindi_Bikaner.objects.get(URL = URL) return True except Hindi_Bikaner.DoesNotExist: return False if category.lower() == ALWAR.lower(): try: langCategoryObj = Hindi_Alwar.objects.get(URL = URL) return True except Hindi_Alwar.DoesNotExist: return False if category.lower() == SIKAR.lower(): try: langCategoryObj = Hindi_Sikar.objects.get(URL = URL) return True except Hindi_Sikar.DoesNotExist: return False if category.lower() == KOTA.lower(): try: langCategoryObj = Hindi_Kota.objects.get(URL = URL) return True except Hindi_Kota.DoesNotExist: return False if category.lower() == BHILWARA.lower(): try: langCategoryObj = Hindi_Bhilwara.objects.get(URL = URL) return True except Hindi_Bhilwara.DoesNotExist: return False if category.lower() == BHARATPUR.lower(): try: langCategoryObj = Hindi_Bharatpur.objects.get(URL = URL) return True except Hindi_Bharatpur.DoesNotExist: return False if category.lower() == CHHATIS.lower(): try: langCategoryObj = Hindi_Chhatis.objects.get(URL = URL) return True except Hindi_Chhatis.DoesNotExist: return False if category.lower() == RAIPUR.lower(): try: langCategoryObj = Hindi_Raipur.objects.get(URL = URL) return True except Hindi_Raipur.DoesNotExist: return False if category.lower() == BHILAI.lower(): try: langCategoryObj = Hindi_Bhilai.objects.get(URL = URL) return True except Hindi_Bhilai.DoesNotExist: return False if category.lower() == RAJNANDGAO.lower(): try: langCategoryObj = Hindi_Rajnandgao.objects.get(URL = URL) return True except Hindi_Rajnandgao.DoesNotExist: return False if category.lower() == RAIGARH.lower(): try: langCategoryObj = Hindi_Raigarh.objects.get(URL = URL) return True except Hindi_Raigarh.DoesNotExist: return False if category.lower() == JAGDALPUR.lower(): try: langCategoryObj = Hindi_Jagdalpur.objects.get(URL = URL) return True except Hindi_Jagdalpur.DoesNotExist: return False if category.lower() == KORVA.lower(): try: langCategoryObj = Hindi_Korva.objects.get(URL = URL) return True except Hindi_Korva.DoesNotExist: return False if category.lower() == RANCHI.lower(): try: langCategoryObj = Hindi_Ranchi.objects.get(URL = URL) return True except Hindi_Ranchi.DoesNotExist: return False if category.lower() == DHANBAD.lower(): try: langCategoryObj = Hindi_Dhanbad.objects.get(URL = URL) return True except Hindi_Dhanbad.DoesNotExist: return False if category.lower() == JAMSHEDPUR.lower(): try: langCategoryObj = Hindi_Jamshedpur.objects.get(URL = URL) return True except Hindi_Jamshedpur.DoesNotExist: return False if category.lower() == GIRIDIHI.lower(): try: langCategoryObj = Hindi_Giridihi.objects.get(URL = URL) return True except Hindi_Giridihi.DoesNotExist: return False if category.lower() == HAZARIBAGH.lower(): try: langCategoryObj = Hindi_Hazaribagh.objects.get(URL = URL) return True except Hindi_Hazaribagh.DoesNotExist: return False if category.lower() == BOKARO.lower(): try: langCategoryObj = Hindi_Bokaro.objects.get(URL = URL) return True except Hindi_Bokaro.DoesNotExist: return False if category.lower() == DEHRADUN.lower(): try: langCategoryObj = Hindi_Dehradun.objects.get(URL = URL) return True except Hindi_Dehradun.DoesNotExist: return False if category.lower() == NAINITAAL.lower(): try: langCategoryObj = Hindi_Nainitaal.objects.get(URL = URL) return True except Hindi_Nainitaal.DoesNotExist: return False if category.lower() == HARIDWAAR.lower(): try: langCategoryObj = Hindi_Haridwaar.objects.get(URL = URL) return True except Hindi_Haridwaar.DoesNotExist: return False if category.lower() == ALMORAH.lower(): try: langCategoryObj = Hindi_Almorah.objects.get(URL = URL) return True except Hindi_Almorah.DoesNotExist: return False if category.lower() == UDDHAMSINGHNAGAR.lower(): try: langCategoryObj = Hindi_UddhamSinghNagar.objects.get(URL = URL) return True except Hindi_UddhamSinghNagar.DoesNotExist: return False if category.lower() == SIMLA.lower(): try: langCategoryObj = Hindi_Simla.objects.get(URL = URL) return True except Hindi_Simla.DoesNotExist: return False if category.lower() == MANDI.lower(): try: langCategoryObj = Hindi_Mandi.objects.get(URL = URL) return True except Hindi_Mandi.DoesNotExist: return False if category.lower() == BILASPUR.lower(): try: langCategoryObj = Hindi_Bilaspur.objects.get(URL = URL) return True except Hindi_Bilaspur.DoesNotExist: return False if category.lower() == AMRITSAR.lower(): try: langCategoryObj = Hindi_Amritsar.objects.get(URL = URL) return True except Hindi_Amritsar.DoesNotExist: return False if category.lower() == JALANDHAR.lower(): try: langCategoryObj = Hindi_Jalandhar.objects.get(URL = URL) return True except Hindi_Jalandhar.DoesNotExist: return False if category.lower() == LUDHIANA.lower(): try: langCategoryObj = Hindi_Ludhiana.objects.get(URL = URL) return True except Hindi_Ludhiana.DoesNotExist: return False if category.lower() == ROPARH.lower(): try: langCategoryObj = Hindi_Roparh.objects.get(URL = URL) return True except Hindi_Roparh.DoesNotExist: return False if category.lower() == CHANDIGARH.lower(): try: langCategoryObj = Hindi_Chandigarh.objects.get(URL = URL) return True except Hindi_Chandigarh.DoesNotExist: return False if category.lower() == ROHTAK.lower(): try: langCategoryObj = Hindi_Rohtak.objects.get(URL = URL) return True except Hindi_Rohtak.DoesNotExist: return False if category.lower() == PANCHKULA.lower(): try: langCategoryObj = Hindi_Panchkula.objects.get(URL = URL) return True except Hindi_Panchkula.DoesNotExist: return False if category.lower() == AMBALA.lower(): try: langCategoryObj = Hindi_Ambala.objects.get(URL = URL) return True except Hindi_Ambala.DoesNotExist: return False if category.lower() == PANIPAT.lower(): try: langCategoryObj = Hindi_Panipat.objects.get(URL = URL) return True except Hindi_Panipat.DoesNotExist: return False if category.lower() == GURGAON.lower(): try: langCategoryObj = Hindi_Gurgaon.objects.get(URL = URL) return True except Hindi_Gurgaon.DoesNotExist: return False if category.lower() == HISSAR.lower(): try: langCategoryObj = Hindi_Hissar.objects.get(URL = URL) return True except Hindi_Hissar.DoesNotExist: return False if category.lower() == JAMMU.lower(): try: langCategoryObj = Hindi_Jammu.objects.get(URL = URL) return True except Hindi_Jammu.DoesNotExist: return False if category.lower() == SRINAGAR.lower(): try: langCategoryObj = Hindi_Srinagar.objects.get(URL = URL) return True except Hindi_Srinagar.DoesNotExist: return False if category.lower() == POONCH.lower(): try: langCategoryObj = Hindi_Poonch.objects.get(URL = URL) return True except Hindi_Poonch.DoesNotExist: return False if category.lower() == KOLKATA.lower(): try: langCategoryObj = Hindi_Kolkata.objects.get(URL = URL) return True except Hindi_Kolkata.DoesNotExist: return False if category.lower() == JALPAIGURHI.lower(): try: langCategoryObj = Hindi_Jalpaigurhi.objects.get(URL = URL) return True except Hindi_Jalpaigurhi.DoesNotExist: return False if category.lower() == DARJEELING.lower(): try: langCategoryObj = Hindi_Darjeeling.objects.get(URL = URL) return True except Hindi_Darjeeling.DoesNotExist: return False if category.lower() == ASANSOL.lower(): try: langCategoryObj = Hindi_Asansol.objects.get(URL = URL) return True except Hindi_Asansol.DoesNotExist: return False if category.lower() == SILIGURHI.lower(): try: langCategoryObj = Hindi_Siligurhi.objects.get(URL = URL) return True except Hindi_Siligurhi.DoesNotExist: return False if category.lower() == BHUVANESHWAR.lower(): try: langCategoryObj = Hindi_Bhuvaneshwar.objects.get(URL = URL) return True except Hindi_Bhuvaneshwar.DoesNotExist: return False if category.lower() == PURI.lower(): try: langCategoryObj = Hindi_Puri.objects.get(URL = URL) return True except Hindi_Puri.DoesNotExist: return False if category.lower() == CUTTACK.lower(): try: langCategoryObj = Hindi_Cuttack.objects.get(URL = URL) return True except Hindi_Cuttack.DoesNotExist: return False if category.lower() == AHMEDABAD.lower(): try: langCategoryObj = Hindi_Ahmedabad.objects.get(URL = URL) return True except Hindi_Ahmedabad.DoesNotExist: return False if category.lower() == SURAT.lower(): try: langCategoryObj = Hindi_Surat.objects.get(URL = URL) return True except Hindi_Surat.DoesNotExist: return False if category.lower() == VADODARA.lower(): try: langCategoryObj = Hindi_Vadodara.objects.get(URL = URL) return True except Hindi_Vadodara.DoesNotExist: return False if category.lower() == MUMBAI.lower(): try: langCategoryObj = Hindi_Mumbai.objects.get(URL = URL) return True except Hindi_Mumbai.DoesNotExist: return False if category.lower() == NAGPUR.lower(): try: langCategoryObj = Hindi_Nagpur.objects.get(URL = URL) return True except Hindi_Nagpur.DoesNotExist: return False if category.lower() == PUNE.lower(): try: langCategoryObj = Hindi_Pune.objects.get(URL = URL) return True except Hindi_Pune.DoesNotExist: return False def getMaxClusterIdForRerun(lang, category): #logger.info("Entered getMaxClusterIdForRerun ") if lang.lower() == ENGLISH.lower(): if category.lower() == ECONOMY.lower(): maxDict = English_Economy_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == SPORTS.lower(): maxDict = English_Sports_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == TOP_STORIES.lower(): maxDict = English_Top_Stories_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == WORLD.lower(): maxDict = English_World_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == OPINION.lower(): maxDict = English_Opinion_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == HEALTH.lower(): maxDict = English_Health_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == LIFESTYLE.lower(): maxDict = English_Lifestyle_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == ENTERTAINMENT.lower(): maxDict = English_Entertainment_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == TECHNOLOGY.lower(): maxDict = English_Technology_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == POLITICS.lower(): maxDict = English_Politics_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == ENVIRONMENT.lower(): maxDict = English_Environment_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == BOOKS.lower(): maxDict = English_Books_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == TRAVEL.lower(): maxDict = English_Travel_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == SCIENCE.lower(): maxDict = English_Science_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == BUSINESS.lower(): maxDict = English_Business_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == STOCKS.lower(): maxDict = English_Stocks_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == FOOD.lower(): maxDict = English_Food_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == WEEKEND.lower(): maxDict = English_Weekend_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == FASHION.lower(): maxDict = English_Fashion_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == MUMBAI.lower(): maxDict = English_Mumbai_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == ENGLISH.lower(): if category.lower() == PUNE.lower(): maxDict = English_Pune_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == ECONOMY.lower(): maxDict = Marathi_Economy_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == SPORTS.lower(): maxDict = Marathi_Sports_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == TOP_STORIES.lower(): maxDict = Marathi_Top_Stories_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == MAHARASHTRA.lower(): maxDict = Marathi_Maharashtra_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == WORLD.lower(): maxDict = Marathi_World_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == OPINION.lower(): maxDict = Marathi_Opinion_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == HEALTH.lower(): maxDict = Marathi_Health_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == LIFESTYLE.lower(): maxDict = Marathi_Lifestyle_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == ENTERTAINMENT.lower(): maxDict = Marathi_Entertainment_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == TECHNOLOGY.lower(): maxDict = Marathi_Technology_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == POLITICS.lower(): maxDict = Marathi_Politics_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == ENVIRONMENT.lower(): maxDict = Marathi_Environment_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == BOOKS.lower(): maxDict = Marathi_Books_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == TRAVEL.lower(): maxDict = Marathi_Travel_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == SCIENCE.lower(): maxDict = Marathi_Science_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == BUSINESS.lower(): maxDict = Marathi_Business_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == STOCKS.lower(): maxDict = Marathi_Stocks_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == FOOD.lower(): maxDict = Marathi_Food_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == WEEKEND.lower(): maxDict = Marathi_Weekend_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == FASHION.lower(): maxDict = Marathi_Fashion_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == MUMBAI.lower(): maxDict = Marathi_Mumbai_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == PUNE.lower(): maxDict = Marathi_Pune_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == NAGPUR.lower(): maxDict = Marathi_Nagpur_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == NASIK.lower(): maxDict = Marathi_Nasik_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == AURANGABAD.lower(): maxDict = Marathi_Aurangabad_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == SOLAPUR.lower(): maxDict = Marathi_Solapur_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == KOLHAPUR.lower(): maxDict = Marathi_Kolhapur_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == SATARA.lower(): maxDict = Marathi_Satara_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == SANGLI.lower(): maxDict = Marathi_Sangli_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == AKOLA.lower(): maxDict = Marathi_Akola_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == AHMEDNAGAR.lower(): maxDict = Marathi_Ahmednagar_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == JALGAON.lower(): maxDict = Marathi_Jalgaon_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == GOA.lower(): maxDict = Marathi_Goa_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == CHANDRAPUR.lower(): maxDict = Marathi_Chandrapur_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == MARATHI.lower(): if category.lower() == WARDHA.lower(): maxDict = Marathi_Wardha_Rerun.objects.all().aggregate(Max('Cluster_Id')) if lang.lower() == HINDI.lower(): if category.lower() == SPORTS.lower(): maxDict = Hindi_Sports_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == TOP_STORIES.lower(): maxDict = Hindi_Top_Stories_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == WORLD.lower(): maxDict = Hindi_World_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == OPINION.lower(): maxDict = Hindi_Opinion_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == HEALTH.lower(): maxDict = Hindi_Health_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == LIFESTYLE.lower(): maxDict = Hindi_Lifestyle_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ENTERTAINMENT.lower(): maxDict = Hindi_Entertainment_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == TECHNOLOGY.lower(): maxDict = Hindi_Technology_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == POLITICS.lower(): maxDict = Hindi_Politics_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == ENVIRONMENT.lower(): maxDict = Hindi_Environment_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == TRAVEL.lower(): maxDict = Hindi_Travel_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == SCIENCE.lower(): maxDict = Hindi_Science_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == BUSINESS.lower(): maxDict = Hindi_Business_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == STOCKS.lower(): maxDict = Hindi_Stocks_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == FOOD.lower(): maxDict = Hindi_Food_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == WEEKEND.lower(): maxDict = Hindi_Weekend_Rerun.objects.all().aggregate(Max('Cluster_Id')) elif category.lower() == FASHION.lower(): maxDict = Hindi_Fashion_Rerun.objects.all().aggregate(Max('Cluster_Id')) #logger.info("Exited selectLangCategoryTable ") return maxDict def deleteRerunTable(lang, category): #logger.info("Entered deleteRerunTable ") if lang.lower() == ENGLISH.lower(): if category.lower() == ECONOMY.lower(): langCategoryObj = English_Economy_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == SPORTS.lower(): langCategoryObj = English_Sports_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = English_Top_Stories_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == WORLD.lower(): langCategoryObj = English_World_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == OPINION.lower(): langCategoryObj = English_Opinion_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == HEALTH.lower(): langCategoryObj = English_Health_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == LIFESTYLE.lower(): langCategoryObj = English_Lifestyle_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategoryObj = English_Entertainment_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == TECHNOLOGY.lower(): langCategoryObj = English_Technology_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == POLITICS.lower(): langCategoryObj = English_Politics_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == ENVIRONMENT.lower(): langCategoryObj = English_Environment_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == BOOKS.lower(): langCategoryObj = English_Books_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == TRAVEL.lower(): langCategoryObj = English_Travel_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == SCIENCE.lower(): langCategoryObj = English_Science_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == BUSINESS.lower(): langCategoryObj = English_Business_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == STOCKS.lower(): langCategoryObj = English_Stocks_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == FOOD.lower(): langCategoryObj = English_Food_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == WEEKEND.lower(): langCategoryObj = English_Weekend_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == FASHION.lower(): langCategoryObj = English_Fashion_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == MUMBAI.lower(): langCategoryObj = English_Mumbai_Rerun.objects.all().delete() if lang.lower() == ENGLISH.lower(): if category.lower() == PUNE.lower(): langCategoryObj = English_Pune_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == ECONOMY.lower(): langCategoryObj = Marathi_Economy_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == SPORTS.lower(): langCategoryObj = Marathi_Sports_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = Marathi_Top_Stories_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == MAHARASHTRA.lower(): langCategoryObj = Marathi_Maharashtra_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == WORLD.lower(): langCategoryObj = Marathi_World_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == OPINION.lower(): langCategoryObj = Marathi_Opinion_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == HEALTH.lower(): langCategoryObj = Marathi_Health_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == LIFESTYLE.lower(): langCategoryObj = Marathi_Lifestyle_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategoryObj = Marathi_Entertainment_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == TECHNOLOGY.lower(): langCategoryObj = Marathi_Technology_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == POLITICS.lower(): langCategoryObj = Marathi_Politics_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == ENVIRONMENT.lower(): langCategoryObj = Marathi_Environment_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == BOOKS.lower(): langCategoryObj = Marathi_Books_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == TRAVEL.lower(): langCategoryObj = Marathi_Travel_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == SCIENCE.lower(): langCategoryObj = Marathi_Science_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == BUSINESS.lower(): langCategoryObj = Marathi_Business_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == STOCKS.lower(): langCategoryObj = Marathi_Stocks_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == FOOD.lower(): langCategoryObj = Marathi_Food_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == WEEKEND.lower(): langCategoryObj = Marathi_Weekend_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == FASHION.lower(): langCategoryObj = Marathi_Fashion_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == MUMBAI.lower(): langCategoryObj = Marathi_Mumbai_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == PUNE.lower(): langCategoryObj = Marathi_Pune_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == NAGPUR.lower(): langCategoryObj = Marathi_Nagpur_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == NASIK.lower(): langCategoryObj = Marathi_Nasik_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == AURANGABAD.lower(): langCategoryObj = Marathi_Aurangabad_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == SOLAPUR.lower(): langCategoryObj = Marathi_Solapur_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == KOLHAPUR.lower(): langCategoryObj = Marathi_Kolhapur_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == SATARA.lower(): langCategoryObj = Marathi_Satara_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == SANGLI.lower(): langCategoryObj = Marathi_Sangli_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == AKOLA.lower(): langCategoryObj = Marathi_Akola_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == AHMEDNAGAR.lower(): langCategoryObj = Marathi_Ahmednagar_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == JALGAON.lower(): langCategoryObj = Marathi_Jalgaon_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == GOA.lower(): langCategoryObj = Marathi_Goa_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == CHANDRAPUR.lower(): langCategoryObj = Marathi_Chandrapur_Rerun.objects.all().delete() if lang.lower() == MARATHI.lower(): if category.lower() == WARDHA.lower(): langCategoryObj = Marathi_Wardha_Rerun.objects.all().delete() if lang.lower() == HINDI.lower(): if category.lower() == SPORTS.lower(): langCategoryObj = Hindi_Sports_Rerun.objects.all().delete() elif category.lower() == TOP_STORIES.lower(): langCategoryObj = Hindi_Top_Stories_Rerun.objects.all().delete() elif category.lower() == WORLD.lower(): langCategoryObj = Hindi_World_Rerun.objects.all().delete() elif category.lower() == OPINION.lower(): langCategoryObj = Hindi_Opinion_Rerun.objects.all().delete() elif category.lower() == HEALTH.lower(): langCategoryObj = Hindi_Health_Rerun.objects.all().delete() elif category.lower() == LIFESTYLE.lower(): langCategoryObj = Hindi_Lifestyle_Rerun.objects.all().delete() elif category.lower() == ENTERTAINMENT.lower(): langCategoryObj = Hindi_Entertainment_Rerun.objects.all().delete() elif category.lower() == TECHNOLOGY.lower(): langCategoryObj = Hindi_Technology_Rerun.objects.all().delete() elif category.lower() == POLITICS.lower(): langCategoryObj = Hindi_Politics_Rerun.objects.all().delete() elif category.lower() == ENVIRONMENT.lower(): langCategoryObj = Hindi_Environment_Rerun.objects.all().delete() elif category.lower() == TRAVEL.lower(): langCategoryObj = Hindi_Travel_Rerun.objects.all().delete() elif category.lower() == SCIENCE.lower(): langCategoryObj = Hindi_Science_Rerun.objects.all().delete() elif category.lower() == BUSINESS.lower(): langCategoryObj = Hindi_Business_Rerun.objects.all().delete() elif category.lower() == STOCKS.lower(): langCategoryObj = Hindi_Stocks_Rerun.objects.all().delete() elif category.lower() == FOOD.lower(): langCategoryObj = Hindi_Food_Rerun.objects.all().delete() elif category.lower() == WEEKEND.lower(): langCategoryObj = Hindi_Weekend_Rerun.objects.all().delete() elif category.lower() == FASHION.lower(): langCategoryObj = Hindi_Fashion_Rerun.objects.all().delete() #logger.info("Exited deleteRerunTable ") def deleteLangCategoryTable(lang, category): #logger.info("Entered deleteLangCategoryTable ") if lang.lower() == ENGLISH.lower(): if category.lower() == ECONOMY.lower(): langCategoryObj = English_Economy.objects.all().delete() elif category.lower() == SPORTS.lower(): langCategoryObj = English_Sports.objects.all().delete() elif category.lower() == TOP_STORIES.lower(): langCategoryObj = English_Top_Stories.objects.all().delete() elif category.lower() == WORLD.lower(): langCategoryObj = English_World.objects.all().delete() elif category.lower() == OPINION.lower(): langCategoryObj = English_Opinion.objects.all().delete() elif category.lower() == HEALTH.lower(): langCategoryObj = English_Health.objects.all().delete() elif category.lower() == LIFESTYLE.lower(): langCategoryObj = English_Lifestyle.objects.all().delete() elif category.lower() == ENTERTAINMENT.lower(): langCategoryObj = English_Entertainment.objects.all().delete() elif category.lower() == TECHNOLOGY.lower(): langCategoryObj = English_Technology.objects.all().delete() elif category.lower() == POLITICS.lower(): langCategoryObj = English_Politics.objects.all().delete() elif category.lower() == ENVIRONMENT.lower(): langCategoryObj = English_Environment.objects.all().delete() elif category.lower() == BOOKS.lower(): langCategoryObj = English_Books.objects.all().delete() elif category.lower() == TRAVEL.lower(): langCategoryObj = English_Travel.objects.all().delete() elif category.lower() == SCIENCE.lower(): langCategoryObj = English_Science.objects.all().delete() elif category.lower() == BUSINESS.lower(): langCategoryObj = English_Business.objects.all().delete() elif category.lower() == TOPN.lower(): langCategoryObj = TopN_English.objects.all().delete() elif category.lower() == STOCKS.lower(): langCategoryObj = English_Stocks.objects.all().delete() elif category.lower() == FOOD.lower(): langCategoryObj = English_Food.objects.all().delete() elif category.lower() == WEEKEND.lower(): langCategoryObj = English_Weekend.objects.all().delete() elif category.lower() == FASHION.lower(): langCategoryObj = English_Fashion.objects.all().delete() elif category.lower() == MUMBAI.lower(): langCategoryObj = English_Mumbai.objects.all().delete() elif category.lower() == PUNE.lower(): langCategoryObj = English_Pune.objects.all().delete() elif lang.lower() == MARATHI.lower(): if category.lower() == ECONOMY.lower(): langCategoryObj = Marathi_Economy.objects.all().delete() elif category.lower() == SPORTS.lower(): langCategoryObj = Marathi_Sports.objects.all().delete() elif category.lower() == TOP_STORIES.lower(): langCategoryObj = Marathi_Top_Stories.objects.all().delete() elif category.lower() == MAHARASHTRA.lower(): langCategoryObj = Marathi_Maharashtra.objects.all().delete() elif category.lower() == WORLD.lower(): langCategoryObj = Marathi_World.objects.all().delete() elif category.lower() == OPINION.lower(): langCategoryObj = Marathi_Opinion.objects.all().delete() elif category.lower() == HEALTH.lower(): langCategoryObj = Marathi_Health.objects.all().delete() elif category.lower() == LIFESTYLE.lower(): langCategoryObj = Marathi_Lifestyle.objects.all().delete() elif category.lower() == ENTERTAINMENT.lower(): langCategoryObj = Marathi_Entertainment.objects.all().delete() elif category.lower() == TECHNOLOGY.lower(): langCategoryObj = Marathi_Technology.objects.all().delete() elif category.lower() == POLITICS.lower(): langCategoryObj = Marathi_Politics.objects.all().delete() elif category.lower() == ENVIRONMENT.lower(): langCategoryObj = Marathi_Environment.objects.all().delete() elif category.lower() == BOOKS.lower(): langCategoryObj = Marathi_Books.objects.all().delete() elif category.lower() == TRAVEL.lower(): langCategoryObj = Marathi_Travel.objects.all().delete() elif category.lower() == SCIENCE.lower(): langCategoryObj = Marathi_Science.objects.all().delete() elif category.lower() == BUSINESS.lower(): langCategoryObj = Marathi_Business.objects.all().delete() elif category.lower() == STOCKS.lower(): langCategoryObj = Marathi_Stocks.objects.all().delete() elif category.lower() == FOOD.lower(): langCategoryObj = Marathi_Food.objects.all().delete() elif category.lower() == WEEKEND.lower(): langCategoryObj = Marathi_Weekend.objects.all().delete() elif category.lower() == FASHION.lower(): langCategoryObj = Marathi_Fashion.objects.all().delete() elif category.lower() == MUMBAI.lower(): langCategoryObj = Marathi_Mumbai.objects.all().delete() elif category.lower() == PUNE.lower(): langCategoryObj = Marathi_Pune.objects.all().delete() elif category.lower() == NAGPUR.lower(): langCategoryObj = Marathi_Nagpur.objects.all().delete() elif category.lower() == NASIK.lower(): langCategoryObj = Marathi_Nasik.objects.all().delete() elif category.lower() == AURANGABAD.lower(): langCategoryObj = Marathi_Aurangabad.objects.all().delete() elif category.lower() == SOLAPUR.lower(): langCategoryObj = Marathi_Solapur.objects.all().delete() elif category.lower() == KOLHAPUR.lower(): langCategoryObj = Marathi_Kolhapur.objects.all().delete() elif category.lower() == SATARA.lower(): langCategoryObj = Marathi_Satara.objects.all().delete() elif category.lower() == SANGLI.lower(): langCategoryObj = Marathi_Sangli.objects.all().delete() elif category.lower() == AKOLA.lower(): langCategoryObj = Marathi_Akola.objects.all().delete() elif category.lower() == AHMEDNAGAR.lower(): langCategoryObj = Marathi_Ahmednagar.objects.all().delete() elif category.lower() == JALGAON.lower(): langCategoryObj = Marathi_Jalgaon.objects.all().delete() elif category.lower() == GOA.lower(): langCategoryObj = Marathi_Goa.objects.all().delete() elif category.lower() == CHANDRAPUR.lower(): langCategoryObj = Marathi_Chandrapur.objects.all().delete() elif category.lower() == WARDHA.lower(): langCategoryObj = Marathi_Wardha.objects.all().delete() elif category.lower() == TOPN.lower(): langCategoryObj = TopN_Marathi.objects.all().delete() elif lang.lower() == HINDI.lower(): if category.lower() == SPORTS.lower(): langCategoryObj = Hindi_Sports.objects.all().delete() elif category.lower() == TOP_STORIES.lower(): langCategoryObj = Hindi_Top_Stories.objects.all().delete() elif category.lower() == WORLD.lower(): langCategoryObj = Hindi_World.objects.all().delete() elif category.lower() == OPINION.lower(): langCategoryObj = Hindi_Opinion.objects.all().delete() elif category.lower() == HEALTH.lower(): langCategoryObj = Hindi_Health.objects.all().delete() elif category.lower() == LIFESTYLE.lower(): langCategoryObj = Hindi_Lifestyle.objects.all().delete() elif category.lower() == ENTERTAINMENT.lower(): langCategoryObj = Hindi_Entertainment.objects.all().delete() elif category.lower() == TECHNOLOGY.lower(): langCategoryObj = Hindi_Technology.objects.all().delete() elif category.lower() == POLITICS.lower(): langCategoryObj = Hindi_Politics.objects.all().delete() elif category.lower() == ENVIRONMENT.lower(): langCategoryObj = Hindi_Environment.objects.all().delete() elif category.lower() == TRAVEL.lower(): langCategoryObj = Hindi_Travel.objects.all().delete() elif category.lower() == SCIENCE.lower(): langCategoryObj = Hindi_Science.objects.all().delete() elif category.lower() == BUSINESS.lower(): langCategoryObj = Hindi_Business.objects.all().delete() elif category.lower() == STOCKS.lower(): langCategoryObj = Hindi_Stocks.objects.all().delete() elif category.lower() == FOOD.lower(): langCategoryObj = Hindi_Food.objects.all().delete() elif category.lower() == WEEKEND.lower(): langCategoryObj = Hindi_Weekend.objects.all().delete() elif category.lower() == FASHION.lower(): langCategoryObj = Hindi_Fashion.objects.all().delete() elif category.lower() == CRIME.lower(): langCategoryObj = Hindi_Crime.objects.all().delete() elif category.lower() == AUTO.lower(): langCategoryObj = Hindi_Auto.objects.all().delete() elif category.lower() == UTTARPRADESH.lower(): langCategoryObj = Hindi_UttarPradesh.objects.all().delete() elif category.lower() == UTTARAKHAND.lower(): langCategoryObj = Hindi_Uttarakhand.objects.all().delete() elif category.lower() == HIMACHALPRADESH.lower(): langCategoryObj = Hindi_HimachalPradesh.objects.all().delete() elif category.lower() == DELHI.lower(): langCategoryObj = Hindi_Delhi.objects.all().delete() elif category.lower() == JAMMUKASHMIR.lower(): langCategoryObj = Hindi_JammuKashmir.objects.all().delete() elif category.lower() == PUNJAB.lower(): langCategoryObj = Hindi_Punjab.objects.all().delete() elif category.lower() == MADHYAPRADESH.lower(): langCategoryObj = Hindi_MadhyaPradesh.objects.all().delete() elif category.lower() == JHARKHAND.lower(): langCategoryObj = Hindi_Jharkhand.objects.all().delete() elif category.lower() == BIHAR.lower(): langCategoryObj = Hindi_Bihar.objects.all().delete() elif category.lower() == HARYANA.lower(): langCategoryObj = Hindi_Haryana.objects.all().delete() elif category.lower() == CHATTISGARH.lower(): langCategoryObj = Hindi_Chattisgarh.objects.all().delete() elif category.lower() == RAJASTHAN.lower(): langCategoryObj = Hindi_Rajasthan.objects.all().delete() elif category.lower() == WESTBENGAL.lower(): langCategoryObj = Hindi_WestBengal.objects.all().delete() elif category.lower() == ORISSA.lower(): langCategoryObj = Hindi_Orissa.objects.all().delete() elif category.lower() == GUJRAT.lower(): langCategoryObj = Hindi_Gujrat.objects.all().delete() elif category.lower() == MAHARASHTRA.lower(): langCategoryObj = Hindi_Maharashtra.objects.all().delete() elif category.lower() == LUCKNOW.lower(): langCategoryObj = Hindi_Lucknow.objects.all().delete() elif category.lower() == ALLAHABAD.lower(): langCategoryObj = Hindi_Allahabad.objects.all().delete() elif category.lower() == PRATAPGARH.lower(): langCategoryObj = Hindi_Pratapgarh.objects.all().delete() elif category.lower() == KANPUR.lower(): langCategoryObj = Hindi_Kanpur.objects.all().delete() elif category.lower() == MERATH.lower(): langCategoryObj = Hindi_Merath.objects.all().delete() elif category.lower() == AGRA.lower(): langCategoryObj = Hindi_Agra.objects.all().delete() elif category.lower() == NOIDA.lower(): langCategoryObj = Hindi_Noida.objects.all().delete() elif category.lower() == GAZIABAD.lower(): langCategoryObj = Hindi_Gaziabad.objects.all().delete() elif category.lower() == BAGPAT.lower(): langCategoryObj = Hindi_Bagpat.objects.all().delete() elif category.lower() == SAHARNPUR.lower(): langCategoryObj = Hindi_Saharnpur.objects.all().delete() elif category.lower() == BULANDSHAHAR.lower(): langCategoryObj = Hindi_Bulandshahar.objects.all().delete() elif category.lower() == VARANASI.lower(): langCategoryObj = Hindi_Varanasi.objects.all().delete() elif category.lower() == GORAKHPUR.lower(): langCategoryObj = Hindi_Gorakhpur.objects.all().delete() elif category.lower() == JHANSI.lower(): langCategoryObj = Hindi_Jhansi.objects.all().delete() elif category.lower() == MUZAFFARNAGAR.lower(): langCategoryObj = Hindi_Muzaffarnagar.objects.all().delete() elif category.lower() == SITAPUR.lower(): langCategoryObj = Hindi_Sitapur.objects.all().delete() elif category.lower() == JAUNPUR.lower(): langCategoryObj = Hindi_Jaunpur.objects.all().delete() elif category.lower() == AZAMGARH.lower(): langCategoryObj = Hindi_Azamgarh.objects.all().delete() elif category.lower() == MORADABAD.lower(): langCategoryObj = Hindi_Moradabad.objects.all().delete() elif category.lower() == BAREILLY.lower(): langCategoryObj = Hindi_Bareilly.objects.all().delete() elif category.lower() == BALIA.lower(): langCategoryObj = Hindi_Balia.objects.all().delete() elif category.lower() == ALIGARH.lower(): langCategoryObj = Hindi_Aligarh.objects.all().delete() elif category.lower() == MATHURA.lower(): langCategoryObj = Hindi_Mathura.objects.all().delete() elif category.lower() == BHOPAL.lower(): langCategoryObj = Hindi_Bhopal.objects.all().delete() elif category.lower() == INDORE.lower(): langCategoryObj = Hindi_Indore.objects.all().delete() elif category.lower() == GWALIOR.lower(): langCategoryObj = Hindi_Gwalior.objects.all().delete() elif category.lower() == JABALPUR.lower(): langCategoryObj = Hindi_Jabalpur.objects.all().delete() elif category.lower() == UJJAIN.lower(): langCategoryObj = Hindi_Ujjain.objects.all().delete() elif category.lower() == RATLAM.lower(): langCategoryObj = Hindi_Ratlam.objects.all().delete() elif category.lower() == SAGAR.lower(): langCategoryObj = Hindi_Sagar.objects.all().delete() elif category.lower() == DEWAS.lower(): langCategoryObj = Hindi_Dewas.objects.all().delete() elif category.lower() == SATNA.lower(): langCategoryObj = Hindi_Satna.objects.all().delete() elif category.lower() == REWA.lower(): langCategoryObj = Hindi_Rewa.objects.all().delete() elif category.lower() == PATNA.lower(): langCategoryObj = Hindi_Patna.objects.all().delete() elif category.lower() == BHAGALPUR.lower(): langCategoryObj = Hindi_Bhagalpur.objects.all().delete() elif category.lower() == MUJAFFARPUR.lower(): langCategoryObj = Hindi_Mujaffarpur.objects.all().delete() elif category.lower() == GAYA.lower(): langCategoryObj = Hindi_Gaya.objects.all().delete() elif category.lower() == DARBHANGA.lower(): langCategoryObj = Hindi_Darbhanga.objects.all().delete() elif category.lower() == POORNIYA.lower(): langCategoryObj = Hindi_Poorniya.objects.all().delete() elif category.lower() == SEWAN.lower(): langCategoryObj = Hindi_Sewan.objects.all().delete() elif category.lower() == BEGUSARAI.lower(): langCategoryObj = Hindi_Begusarai.objects.all().delete() elif category.lower() == KATIHAR.lower(): langCategoryObj = Hindi_Katihar.objects.all().delete() elif category.lower() == JAIPUR.lower(): langCategoryObj = Hindi_Jaipur.objects.all().delete() elif category.lower() == UDAIPUR.lower(): langCategoryObj = Hindi_Udaipur.objects.all().delete() elif category.lower() == JODHPUR.lower(): langCategoryObj = Hindi_Jodhpur.objects.all().delete() elif category.lower() == AJMER.lower(): langCategoryObj = Hindi_Ajmer.objects.all().delete() elif category.lower() == BIKANER.lower(): langCategoryObj = Hindi_Bikaner.objects.all().delete() elif category.lower() == ALWAR.lower(): langCategoryObj = Hindi_Alwar.objects.all().delete() elif category.lower() == SIKAR.lower(): langCategoryObj = Hindi_Sikar.objects.all().delete() elif category.lower() == KOTA.lower(): langCategoryObj = Hindi_Kota.objects.all().delete() elif category.lower() == BHILWARA.lower(): langCategoryObj = Hindi_Bhilwara.objects.all().delete() elif category.lower() == BHARATPUR.lower(): langCategoryObj = Hindi_Bharatpur.objects.all().delete() elif category.lower() == CHHATIS.lower(): langCategoryObj = Hindi_Chhatis.objects.all().delete() elif category.lower() == RAIPUR.lower(): langCategoryObj = Hindi_Raipur.objects.all().delete() elif category.lower() == BHILAI.lower(): langCategoryObj = Hindi_Bhilai.objects.all().delete() elif category.lower() == RAJNANDGAO.lower(): langCategoryObj = Hindi_Rajnandgao.objects.all().delete() elif category.lower() == RAIGARH.lower(): langCategoryObj = Hindi_Raigarh.objects.all().delete() elif category.lower() == JAGDALPUR.lower(): langCategoryObj = Hindi_Jagdalpur.objects.all().delete() elif category.lower() == KORVA.lower(): langCategoryObj = Hindi_Korva.objects.all().delete() elif category.lower() == RANCHI.lower(): langCategoryObj = Hindi_Ranchi.objects.all().delete() elif category.lower() == DHANBAD.lower(): langCategoryObj = Hindi_Dhanbad.objects.all().delete() elif category.lower() == JAMSHEDPUR.lower(): langCategoryObj = Hindi_Jamshedpur.objects.all().delete() elif category.lower() == GIRIDIHI.lower(): langCategoryObj = Hindi_Giridihi.objects.all().delete() elif category.lower() == HAZARIBAGH.lower(): langCategoryObj = Hindi_Hazaribagh.objects.all().delete() elif category.lower() == BOKARO.lower(): langCategoryObj = Hindi_Bokaro.objects.all().delete() elif category.lower() == DEHRADUN.lower(): langCategoryObj = Hindi_Dehradun.objects.all().delete() elif category.lower() == NAINITAAL.lower(): langCategoryObj = Hindi_Nainitaal.objects.all().delete() elif category.lower() == HARIDWAAR.lower(): langCategoryObj = Hindi_Haridwaar.objects.all().delete() elif category.lower() == ALMORAH.lower(): langCategoryObj = Hindi_Almorah.objects.all().delete() elif category.lower() == UDDHAMSINGHNAGAR.lower(): langCategoryObj = Hindi_UddhamSinghNagar.objects.all().delete() elif category.lower() == SIMLA.lower(): langCategoryObj = Hindi_Simla.objects.all().delete() elif category.lower() == MANDI.lower(): langCategoryObj = Hindi_Mandi.objects.all().delete() elif category.lower() == BILASPUR.lower(): langCategoryObj = Hindi_Bilaspur.objects.all().delete() elif category.lower() == AMRITSAR.lower(): langCategoryObj = Hindi_Amritsar.objects.all().delete() elif category.lower() == JALANDHAR.lower(): langCategoryObj = Hindi_Jalandhar.objects.all().delete() elif category.lower() == LUDHIANA.lower(): langCategoryObj = Hindi_Ludhiana.objects.all().delete() elif category.lower() == ROPARH.lower(): langCategoryObj = Hindi_Roparh.objects.all().delete() elif category.lower() == CHANDIGARH.lower(): langCategoryObj = Hindi_Chandigarh.objects.all().delete() elif category.lower() == ROHTAK.lower(): langCategoryObj = Hindi_Rohtak.objects.all().delete() elif category.lower() == PANCHKULA.lower(): langCategoryObj = Hindi_Panchkula.objects.all().delete() elif category.lower() == AMBALA.lower(): langCategoryObj = Hindi_Ambala.objects.all().delete() elif category.lower() == PANIPAT.lower(): langCategoryObj = Hindi_Panipat.objects.all().delete() elif category.lower() == GURGAON.lower(): langCategoryObj = Hindi_Gurgaon.objects.all().delete() elif category.lower() == HISSAR.lower(): langCategoryObj = Hindi_Hissar.objects.all().delete() elif category.lower() == JAMMU.lower(): langCategoryObj = Hindi_Jammu.objects.all().delete() elif category.lower() == SRINAGAR.lower(): langCategoryObj = Hindi_Srinagar.objects.all().delete() elif category.lower() == POONCH.lower(): langCategoryObj = Hindi_Poonch.objects.all().delete() elif category.lower() == KOLKATA.lower(): langCategoryObj = Hindi_Kolkata.objects.all().delete() elif category.lower() == JALPAIGURHI.lower(): langCategoryObj = Hindi_Jalpaigurhi.objects.all().delete() elif category.lower() == DARJEELING.lower(): langCategoryObj = Hindi_Darjeeling.objects.all().delete() elif category.lower() == ASANSOL.lower(): langCategoryObj = Hindi_Asansol.objects.all().delete() elif category.lower() == SILIGURHI.lower(): langCategoryObj = Hindi_Siligurhi.objects.all().delete() elif category.lower() == BHUVANESHWAR.lower(): langCategoryObj = Hindi_Bhuvaneshwar.objects.all().delete() elif category.lower() == PURI.lower(): langCategoryObj = Hindi_Puri.objects.all().delete() elif category.lower() == CUTTACK.lower(): langCategoryObj = Hindi_Cuttack.objects.all().delete() elif category.lower() == AHMEDABAD.lower(): langCategoryObj = Hindi_Ahmedabad.objects.all().delete() elif category.lower() == SURAT.lower(): langCategoryObj = Hindi_Surat.objects.all().delete() elif category.lower() == VADODARA.lower(): langCategoryObj = Hindi_Vadodara.objects.all().delete() elif category.lower() == MUMBAI.lower(): langCategoryObj = Hindi_Mumbai.objects.all().delete() elif category.lower() == NAGPUR.lower(): langCategoryObj = Hindi_Nagpur.objects.all().delete() elif category.lower() == PUNE.lower(): langCategoryObj = Hindi_Pune.objects.all().delete() elif category.lower() == TOPN.lower(): langCategoryObj = TopN_Hindi.objects.all().delete() #logger.info("Exited deleteLangCategoryTable ") def insertLangCategoryFromRerunTable(lang, category, articleObj): #logger.info("Entered insertLangCategoryFromRerunTable ") if lang.lower() == ENGLISH.lower(): if category.lower() == ECONOMY.lower(): langCategoryObj = English_Economy(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == SPORTS.lower(): langCategoryObj = English_Sports(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = English_Top_Stories(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == WORLD.lower(): langCategoryObj = English_World(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == OPINION.lower(): langCategoryObj = English_Opinion(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == HEALTH.lower(): langCategoryObj = English_Health(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == LIFESTYLE.lower(): langCategoryObj = English_Lifestyle(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategoryObj = English_Entertainment(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == TECHNOLOGY.lower(): langCategoryObj = English_Technology(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == POLITICS.lower(): langCategoryObj = English_Politics(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == ENVIRONMENT.lower(): langCategoryObj = English_Environment(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == BOOKS.lower(): langCategoryObj = English_Books(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == TRAVEL.lower(): langCategoryObj = English_Travel(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == SCIENCE.lower(): langCategoryObj = English_Science(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == BUSINESS.lower(): langCategoryObj = English_Business(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == STOCKS.lower(): langCategoryObj = English_Stocks(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == FOOD.lower(): langCategoryObj = English_Food(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == WEEKEND.lower(): langCategoryObj = English_Weekend(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == FASHION.lower(): langCategoryObj = English_Fashion(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == MUMBAI.lower(): langCategoryObj = English_Mumbai(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == ENGLISH.lower(): if category.lower() == PUNE.lower(): langCategoryObj = English_Pune(Article=articleObj.Article, URL=articleObj.URL, Title=articleObj.Title, Summary=articleObj.Summary, Thumbnail=articleObj.Thumbnail, Source=articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id=articleObj.Cluster_Id, Is_Rep=articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == MARATHI.lower(): if category.lower() == ECONOMY.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_economy (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == SPORTS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_sports (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == TOP_STORIES.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_top_stories (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == WORLD.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_world (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == OPINION.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_opinion (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == HEALTH.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_health (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == LIFESTYLE.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_lifestyle (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == ENTERTAINMENT.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_entertainment (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == TECHNOLOGY.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_technology (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == POLITICS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_politics (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == ENVIRONMENT.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_environment (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == BOOKS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_books (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == TRAVEL.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_travel (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == SCIENCE.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_science (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == BUSINESS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_business (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == STOCKS.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_stocks (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == FOOD.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_food (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == WEEKEND.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_weekend (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == FASHION.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_fashion (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == MUMBAI.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_mumbai (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == PUNE.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_pune (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == NAGPUR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_nagpur (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == NASIK.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_nasik (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == AURANGABAD.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_aurangabad (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == SOLAPUR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_solapur (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == KOLHAPUR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_kolhapur (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == SATARA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_satara (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == SANGLI.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_sangli (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == AKOLA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_akola (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == AHMEDNAGAR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_ahmednagar (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == JALGAON.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_jalgaon (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == GOA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_goa (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == CHANDRAPUR.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_chandrapur (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == WARDHA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_wardha (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == MARATHI.lower(): if category.lower() == MAHARASHTRA.lower(): langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name = category) cursor = connection.cursor() cursor.execute('''INSERT INTO news_schema.newsApp_marathi_maharashtra (Cluster_Id,Article_id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,Is_Rep) SELECT %s,id,URL,Title,Summary,Thumbnail,Source_id,Published_Date,%s from news_schema.newsApp_news_article WHERE Language_id = %s and Category_id = %s and id = %s''',[articleObj.Cluster_Id,articleObj.Is_Rep,langObj.id,categoryObj.id,articleObj.Article_id]) if lang.lower() == HINDI.lower(): if category.lower() == SPORTS.lower(): langCategoryObj = Hindi_Sports( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == TOP_STORIES.lower(): langCategoryObj = Hindi_Top_Stories( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == WORLD.lower(): langCategoryObj = Hindi_World( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == OPINION.lower(): langCategoryObj = Hindi_Opinion( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == HEALTH.lower(): langCategoryObj = Hindi_Health( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == LIFESTYLE.lower(): langCategoryObj = Hindi_Lifestyle( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategoryObj = Hindi_Entertainment( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == TECHNOLOGY.lower(): langCategoryObj = Hindi_Technology( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == POLITICS.lower(): langCategoryObj = Hindi_Politics( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == ENVIRONMENT.lower(): langCategoryObj = Hindi_Environment( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == TRAVEL.lower(): langCategoryObj = Hindi_Travel( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == SCIENCE.lower(): langCategoryObj = Hindi_Science( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == BUSINESS.lower(): langCategoryObj = Hindi_Business( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == STOCKS.lower(): langCategoryObj = Hindi_Stocks( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == FOOD.lower(): langCategoryObj = Hindi_Food( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == WEEKEND.lower(): langCategoryObj = Hindi_Weekend( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() if lang.lower() == HINDI.lower(): if category.lower() == FASHION.lower(): langCategoryObj = Hindi_Fashion( Article = articleObj, URL = articleObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Cluster_Id = articleObj.Cluster_Id, Is_Rep = articleObj.Is_Rep) langCategoryObj.save() #logger.info("Exited insertLangCategoryFromRerunTable ") def selectRerunTable(lang, category): #logger.info("Entered selectRerunTable ") if lang.lower() == ENGLISH.lower(): if category.lower() == ECONOMY.lower(): langCategotyAll = English_Economy_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == SPORTS.lower(): langCategotyAll = English_Sports_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == TOP_STORIES.lower(): langCategotyAll = English_Top_Stories_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == WORLD.lower(): langCategotyAll = English_World_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == OPINION.lower(): langCategotyAll = English_Opinion_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == HEALTH.lower(): langCategotyAll = English_Health_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == LIFESTYLE.lower(): langCategotyAll = English_Lifestyle_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategotyAll = English_Entertainment_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == TECHNOLOGY.lower(): langCategotyAll = English_Technology_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == POLITICS.lower(): langCategotyAll = English_Politics_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == ENVIRONMENT.lower(): langCategotyAll = English_Environment_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == BOOKS.lower(): langCategotyAll = English_Books_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == TRAVEL.lower(): langCategotyAll = English_Travel_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == SCIENCE.lower(): langCategotyAll = English_Science_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == BUSINESS.lower(): langCategotyAll = English_Business_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == STOCKS.lower(): langCategotyAll = English_Stocks_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == FOOD.lower(): langCategotyAll = English_Food_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == WEEKEND.lower(): langCategotyAll = English_Weekend_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == FASHION.lower(): langCategotyAll = English_Fashion_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == MUMBAI.lower(): langCategotyAll = English_Mumbai_Rerun.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == PUNE.lower(): langCategotyAll = English_Pune_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == ECONOMY.lower(): langCategotyAll = Marathi_Economy_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == SPORTS.lower(): langCategotyAll = Marathi_Sports_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == TOP_STORIES.lower(): langCategotyAll = Marathi_Top_Stories_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == MAHARASHTRA.lower(): langCategotyAll = Marathi_Maharashtra_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == WORLD.lower(): langCategotyAll = Marathi_World_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == OPINION.lower(): langCategotyAll = Marathi_Opinion_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == HEALTH.lower(): langCategotyAll = Marathi_Health_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == LIFESTYLE.lower(): langCategotyAll = Marathi_Lifestyle_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategotyAll = Marathi_Entertainment_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == TECHNOLOGY.lower(): langCategotyAll = Marathi_Technology_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == POLITICS.lower(): langCategotyAll = Marathi_Politics_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == ENVIRONMENT.lower(): langCategotyAll = Marathi_Environment_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == BOOKS.lower(): langCategotyAll = Marathi_Books_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == TRAVEL.lower(): langCategotyAll = Marathi_Travel_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == SCIENCE.lower(): langCategotyAll = Marathi_Science_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == BUSINESS.lower(): langCategotyAll = Marathi_Business_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == STOCKS.lower(): langCategotyAll = Marathi_Stocks_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == FOOD.lower(): langCategotyAll = Marathi_Food_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == WEEKEND.lower(): langCategotyAll = Marathi_Weekend_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == FASHION.lower(): langCategotyAll = Marathi_Fashion_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == MUMBAI.lower(): langCategotyAll = Marathi_Mumbai_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == PUNE.lower(): langCategotyAll = Marathi_Pune_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == NAGPUR.lower(): langCategotyAll = Marathi_Nagpur_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == NASIK.lower(): langCategotyAll = Marathi_Nasik_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == AURANGABAD.lower(): langCategotyAll = Marathi_Aurangabad_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == SOLAPUR.lower(): langCategotyAll = Marathi_Solapur_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == KOLHAPUR.lower(): langCategotyAll = Marathi_Kolhapur_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == SATARA.lower(): langCategotyAll = Marathi_Satara_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == SANGLI.lower(): langCategotyAll = Marathi_Sangli_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == AKOLA.lower(): langCategotyAll = Marathi_Akola_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == AHMEDNAGAR.lower(): langCategotyAll = Marathi_Ahmednagar_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == JALGAON.lower(): langCategotyAll = Marathi_Jalgaon_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == GOA.lower(): langCategotyAll = Marathi_Goa_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == CHANDRAPUR.lower(): langCategotyAll = Marathi_Chandrapur_Rerun.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == WARDHA.lower(): langCategotyAll = Marathi_Wardha_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == SPORTS.lower(): langCategotyAll = Hindi_Sports_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == TOP_STORIES.lower(): langCategotyAll = Hindi_Top_Stories_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == WORLD.lower(): langCategotyAll = Hindi_World_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == OPINION.lower(): langCategotyAll = Hindi_Opinion_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == HEALTH.lower(): langCategotyAll = Hindi_Health_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == LIFESTYLE.lower(): langCategotyAll = Hindi_Lifestyle_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategotyAll = Hindi_Entertainment_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == TECHNOLOGY.lower(): langCategotyAll = Hindi_Technology_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == POLITICS.lower(): langCategotyAll = Hindi_Politics_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == ENVIRONMENT.lower(): langCategotyAll = Hindi_Environment_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == TRAVEL.lower(): langCategotyAll = Hindi_Travel_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == SCIENCE.lower(): langCategotyAll = Hindi_Science_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BUSINESS.lower(): langCategotyAll = Hindi_Business_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == STOCKS.lower(): langCategotyAll = Hindi_Stocks_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == FOOD.lower(): langCategotyAll = Hindi_Food_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == WEEKEND.lower(): langCategotyAll = Hindi_Weekend_Rerun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == FASHION.lower(): langCategotyAll = Hindi_Fashion_Rerun.objects.all() #logger.info("Exited selectRerunTable ") return langCategotyAll def selectLangCatAll(lang, category): #logger.info("Entered selectLangCatAll ") if lang.lower() == ENGLISH.lower(): if category.lower() == ECONOMY.lower(): langCategotyAll = English_Economy.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == SPORTS.lower(): langCategotyAll = English_Sports.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == TOP_STORIES.lower(): langCategotyAll = English_Top_Stories.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == WORLD.lower(): langCategotyAll = English_World.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == OPINION.lower(): langCategotyAll = English_Opinion.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == HEALTH.lower(): langCategotyAll = English_Health.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == LIFESTYLE.lower(): langCategotyAll = English_Lifestyle.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategotyAll = English_Entertainment.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == TECHNOLOGY.lower(): langCategotyAll = English_Technology.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == POLITICS.lower(): langCategotyAll = English_Politics.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == ENVIRONMENT.lower(): langCategotyAll = English_Environment.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == BOOKS.lower(): langCategotyAll = English_Books.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == TRAVEL.lower(): langCategotyAll = English_Travel.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == SCIENCE.lower(): langCategotyAll = English_Science.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == BUSINESS.lower(): langCategotyAll = English_Business.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == STOCKS.lower(): langCategotyAll = English_Stocks.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == FOOD.lower(): langCategotyAll = English_Food.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == WEEKEND.lower(): langCategotyAll = English_Weekend.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == FASHION.lower(): langCategotyAll = English_Fashion.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == MUMBAI.lower(): langCategotyAll = English_Mumbai.objects.all() if lang.lower() == ENGLISH.lower(): if category.lower() == PUNE.lower(): langCategotyAll = English_Pune.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == ECONOMY.lower(): langCategotyAll = Marathi_Economy.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == SPORTS.lower(): langCategotyAll = Marathi_Sports.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == TOP_STORIES.lower(): langCategotyAll = Marathi_Top_Stories.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == MAHARASHTRA.lower(): langCategotyAll = Marathi_Maharashtra.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == WORLD.lower(): langCategotyAll = Marathi_World.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == OPINION.lower(): langCategotyAll = Marathi_Opinion.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == HEALTH.lower(): langCategotyAll = Marathi_Health.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == LIFESTYLE.lower(): langCategotyAll = Marathi_Lifestyle.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategotyAll = Marathi_Entertainment.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == TECHNOLOGY.lower(): langCategotyAll = Marathi_Technology.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == POLITICS.lower(): langCategotyAll = Marathi_Politics.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == ENVIRONMENT.lower(): langCategotyAll = Marathi_Environment.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == BOOKS.lower(): langCategotyAll = Marathi_Books.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == TRAVEL.lower(): langCategotyAll = Marathi_Travel.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == SCIENCE.lower(): langCategotyAll = Marathi_Science.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == BUSINESS.lower(): langCategotyAll = Marathi_Business.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == STOCKS.lower(): langCategotyAll = Marathi_Stocks.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == FOOD.lower(): langCategotyAll = Marathi_Food.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == WEEKEND.lower(): langCategotyAll = Marathi_Weekend.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == FASHION.lower(): langCategotyAll = Marathi_Fashion.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == MUMBAI.lower(): langCategotyAll = Marathi_Mumbai.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == PUNE.lower(): langCategotyAll = Marathi_Pune.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == NAGPUR.lower(): langCategotyAll = Marathi_Nagpur.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == NASIK.lower(): langCategotyAll = Marathi_Nasik.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == AURANGABAD.lower(): langCategotyAll = Marathi_Aurangabad.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == SOLAPUR.lower(): langCategotyAll = Marathi_Solapur.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == KOLHAPUR.lower(): langCategotyAll = Marathi_Kolhapur.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == SATARA.lower(): langCategotyAll = Marathi_Satara.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == SANGLI.lower(): langCategotyAll = Marathi_Sangli.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == AKOLA.lower(): langCategotyAll = Marathi_Akola.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == AHMEDNAGAR.lower(): langCategotyAll = Marathi_Ahmednagar.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == JALGAON.lower(): langCategotyAll = Marathi_Jalgaon.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == GOA.lower(): langCategotyAll = Marathi_Goa.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == CHANDRAPUR.lower(): langCategotyAll = Marathi_Chandrapur.objects.all() if lang.lower() == MARATHI.lower(): if category.lower() == WARDHA.lower(): langCategotyAll = Marathi_Wardha.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == SPORTS.lower(): langCategotyAll = Hindi_Sports.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == TOP_STORIES.lower(): langCategotyAll = Hindi_Top_Stories.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == WORLD.lower(): langCategotyAll = Hindi_World.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == OPINION.lower(): langCategotyAll = Hindi_Opinion.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == HEALTH.lower(): langCategotyAll = Hindi_Health.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == LIFESTYLE.lower(): langCategotyAll = Hindi_Lifestyle.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == ENTERTAINMENT.lower(): langCategotyAll = Hindi_Entertainment.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == TECHNOLOGY.lower(): langCategotyAll = Hindi_Technology.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == POLITICS.lower(): langCategotyAll = Hindi_Politics.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == ENVIRONMENT.lower(): langCategotyAll = Hindi_Environment.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == TRAVEL.lower(): langCategotyAll = Hindi_Travel.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == SCIENCE.lower(): langCategotyAll = Hindi_Science.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BUSINESS.lower(): langCategotyAll = Hindi_Business.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == STOCKS.lower(): langCategotyAll = Hindi_Stocks.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == FOOD.lower(): langCategotyAll = Hindi_Food.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == WEEKEND.lower(): langCategotyAll = Hindi_Weekend.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == FASHION.lower(): langCategotyAll = Hindi_Fashion.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == AUTO.lower(): langCategotyAll = Hindi_Auto.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == CRIME.lower(): langCategotyAll = Hindi_Crime.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == UTTARPRADESH.lower(): langCategotyAll = Hindi_UttarPradesh.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == UTTARAKHAND.lower(): langCategotyAll = Hindi_Uttarakhand.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == HIMACHALPRADESH.lower(): langCategotyAll = Hindi_HimachalPradesh.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == DELHI.lower(): langCategotyAll = Hindi_Delhi.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == JAMMUKASHMIR.lower(): langCategotyAll = Hindi_JammuKashmir.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == PUNJAB.lower(): langCategotyAll = Hindi_Punjab.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == MADHYAPRADESH.lower(): langCategotyAll = Hindi_MadhyaPradesh.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == JHARKHAND.lower(): langCategotyAll = Hindi_Jharkhand.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BIHAR.lower(): langCategotyAll = Hindi_Bihar.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == HARYANA.lower(): langCategotyAll = Hindi_Haryana.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == CHATTISGARH.lower(): langCategotyAll = Hindi_Chattisgarh.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == RAJASTHAN.lower(): langCategotyAll = Hindi_Rajasthan.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == WESTBENGAL.lower(): langCategotyAll = Hindi_WestBengal.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == ORISSA.lower(): langCategotyAll = Hindi_Orissa.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == GUJRAT.lower(): langCategotyAll = Hindi_Gujrat.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == MAHARASHTRA.lower(): langCategotyAll = Hindi_Maharashtra.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == LUCKNOW.lower(): langCategotyAll = Hindi_Lucknow.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == ALLAHABAD.lower(): langCategotyAll = Hindi_Allahabad.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == PRATAPGARH.lower(): langCategotyAll = Hindi_Pratapgarh.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == KANPUR.lower(): langCategotyAll = Hindi_Kanpur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == MERATH.lower(): langCategotyAll = Hindi_Merath.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == AGRA.lower(): langCategotyAll = Hindi_Agra.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == NOIDA.lower(): langCategotyAll = Hindi_Noida.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == GAZIABAD.lower(): langCategotyAll = Hindi_Gaziabad.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BAGPAT.lower(): langCategotyAll = Hindi_Bagpat.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == SAHARNPUR.lower(): langCategotyAll = Hindi_Saharnpur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BULANDSHAHAR.lower(): langCategotyAll = Hindi_Bulandshahar.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == VARANASI.lower(): langCategotyAll = Hindi_Varanasi.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == GORAKHPUR.lower(): langCategotyAll = Hindi_Gorakhpur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == JHANSI.lower(): langCategotyAll = Hindi_Jhansi.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == MUZAFFARNAGAR.lower(): langCategotyAll = Hindi_Muzaffarnagar.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == SITAPUR.lower(): langCategotyAll = Hindi_Sitapur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == JAUNPUR.lower(): langCategotyAll = Hindi_Jaunpur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == AZAMGARH.lower(): langCategotyAll = Hindi_Azamgarh.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == MORADABAD.lower(): langCategotyAll = Hindi_Moradabad.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BAREILLY.lower(): langCategotyAll = Hindi_Bareilly.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BALIA.lower(): langCategotyAll = Hindi_Balia.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == ALIGARH.lower(): langCategotyAll = Hindi_Aligarh.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == MATHURA.lower(): langCategotyAll = Hindi_Mathura.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BHOPAL.lower(): langCategotyAll = Hindi_Bhopal.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == INDORE.lower(): langCategotyAll = Hindi_Indore.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == GWALIOR.lower(): langCategotyAll = Hindi_Gwalior.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == JABALPUR.lower(): langCategotyAll = Hindi_Jabalpur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == UJJAIN.lower(): langCategotyAll = Hindi_Ujjain.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == RATLAM.lower(): langCategotyAll = Hindi_Ratlam.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == SAGAR.lower(): langCategotyAll = Hindi_Sagar.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == DEWAS.lower(): langCategotyAll = Hindi_Dewas.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == SATNA.lower(): langCategotyAll = Hindi_Satna.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == REWA.lower(): langCategotyAll = Hindi_Rewa.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == PATNA.lower(): langCategotyAll = Hindi_Patna.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BHAGALPUR.lower(): langCategotyAll = Hindi_Bhagalpur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == MUJAFFARPUR.lower(): langCategotyAll = Hindi_Mujaffarpur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == GAYA.lower(): langCategotyAll = Hindi_Gaya.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == DARBHANGA.lower(): langCategotyAll = Hindi_Darbhanga.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == POORNIYA.lower(): langCategotyAll = Hindi_Poorniya.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == SEWAN.lower(): langCategotyAll = Hindi_Sewan.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BEGUSARAI.lower(): langCategotyAll = Hindi_Begusarai.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == KATIHAR.lower(): langCategotyAll = Hindi_Katihar.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == JAIPUR.lower(): langCategotyAll = Hindi_Jaipur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == UDAIPUR.lower(): langCategotyAll = Hindi_Udaipur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == JODHPUR.lower(): langCategotyAll = Hindi_Jodhpur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == AJMER.lower(): langCategotyAll = Hindi_Ajmer.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BIKANER.lower(): langCategotyAll = Hindi_Bikaner.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == ALWAR.lower(): langCategotyAll = Hindi_Alwar.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == SIKAR.lower(): langCategotyAll = Hindi_Sikar.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == KOTA.lower(): langCategotyAll = Hindi_Kota.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BHILWARA.lower(): langCategotyAll = Hindi_Bhilwara.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BHARATPUR.lower(): langCategotyAll = Hindi_Bharatpur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == CHHATIS.lower(): langCategotyAll = Hindi_Chhatis.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == RAIPUR.lower(): langCategotyAll = Hindi_Raipur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BHILAI.lower(): langCategotyAll = Hindi_Bhilai.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == RAJNANDGAO.lower(): langCategotyAll = Hindi_Rajnandgao.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == RAIGARH.lower(): langCategotyAll = Hindi_Raigarh.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == JAGDALPUR.lower(): langCategotyAll = Hindi_Jagdalpur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == KORVA.lower(): langCategotyAll = Hindi_Korva.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == RANCHI.lower(): langCategotyAll = Hindi_Ranchi.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == DHANBAD.lower(): langCategotyAll = Hindi_Dhanbad.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == JAMSHEDPUR.lower(): langCategotyAll = Hindi_Jamshedpur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == GIRIDIHI.lower(): langCategotyAll = Hindi_Giridihi.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == HAZARIBAGH.lower(): langCategotyAll = Hindi_Hazaribagh.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BOKARO.lower(): langCategotyAll = Hindi_Bokaro.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == DEHRADUN.lower(): langCategotyAll = Hindi_Dehradun.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == NAINITAAL.lower(): langCategotyAll = Hindi_Nainitaal.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == HARIDWAAR.lower(): langCategotyAll = Hindi_Haridwaar.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == ALMORAH.lower(): langCategotyAll = Hindi_Almorah.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == UDDHAMSINGHNAGAR.lower(): langCategotyAll = Hindi_UddhamSinghNagar.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == SIMLA.lower(): langCategotyAll = Hindi_Simla.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == MANDI.lower(): langCategotyAll = Hindi_Mandi.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BILASPUR.lower(): langCategotyAll = Hindi_Bilaspur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == AMRITSAR.lower(): langCategotyAll = Hindi_Amritsar.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == JALANDHAR.lower(): langCategotyAll = Hindi_Jalandhar.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == LUDHIANA.lower(): langCategotyAll = Hindi_Ludhiana.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == ROPARH.lower(): langCategotyAll = Hindi_Roparh.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == CHANDIGARH.lower(): langCategotyAll = Hindi_Chandigarh.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == ROHTAK.lower(): langCategotyAll = Hindi_Rohtak.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == PANCHKULA.lower(): langCategotyAll = Hindi_Panchkula.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == AMBALA.lower(): langCategotyAll = Hindi_Ambala.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == PANIPAT.lower(): langCategotyAll = Hindi_Panipat.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == GURGAON.lower(): langCategotyAll = Hindi_Gurgaon.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == HISSAR.lower(): langCategotyAll = Hindi_Hissar.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == JAMMU.lower(): langCategotyAll = Hindi_Jammu.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == SRINAGAR.lower(): langCategotyAll = Hindi_Srinagar.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == POONCH.lower(): langCategotyAll = Hindi_Poonch.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == KOLKATA.lower(): langCategotyAll = Hindi_Kolkata.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == JALPAIGURHI.lower(): langCategotyAll = Hindi_Jalpaigurhi.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == DARJEELING.lower(): langCategotyAll = Hindi_Darjeeling.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == ASANSOL.lower(): langCategotyAll = Hindi_Asansol.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == SILIGURHI.lower(): langCategotyAll = Hindi_Siligurhi.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == BHUVANESHWAR.lower(): langCategotyAll = Hindi_Bhuvaneshwar.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == PURI.lower(): langCategotyAll = Hindi_Puri.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == CUTTACK.lower(): langCategotyAll = Hindi_Cuttack.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == AHMEDABAD.lower(): langCategotyAll = Hindi_Ahmedabad.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == SURAT.lower(): langCategotyAll = Hindi_Surat.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == VADODARA.lower(): langCategotyAll = Hindi_Vadodara.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == MUMBAI.lower(): langCategotyAll = Hindi_Mumbai.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == NAGPUR.lower(): langCategotyAll = Hindi_Nagpur.objects.all() if lang.lower() == HINDI.lower(): if category.lower() == PUNE.lower(): langCategotyAll = Hindi_Pune.objects.all() #logger.info("Exited selectLangCatAll ") return langCategotyAll def updateArticleTable(lang,category): #logger.info("Entered updateArticleTable ") langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=category) articleObjAll = News_Article.objects.filter(Language = langObj, Category = categoryObj, Is_New = True) for articleObj in articleObjAll: articleObj.Is_New = False articleObj.save() #logger.info("Exited updateArticleTable ") def updateRep(lang,cat,langCatObj,isRep): if lang.lower() == ENGLISH.lower(): if cat.lower() == TOP_STORIES.lower(): TopStories = English_Top_Stories.objects.filter(id = langCatObj.id) for TopStoriesObj in TopStories: TopStoriesObj.Is_Rep = isRep TopStoriesObj.save() if lang.lower() == MARATHI.lower(): if cat.lower() == TOP_STORIES.lower(): TopStories = Marathi_Top_Stories.objects.filter(id = langCatObj.id) for TopStoriesObj in TopStories: TopStoriesObj.Is_Rep = isRep TopStoriesObj.save() def insertArchive(lang,cat): #logger.info("Entered insertArchive ") langObj = Language.objects.get(Name=lang) categoryObj = News_Category.objects.get(Name=cat) langCategotyAll = selectLangCatAll(lang,cat) for langCategoryObj in langCategotyAll: articleObj = News_Article.objects.get(id = langCategoryObj.Article.id) archiveObj = News_Article_Archive(Language = langObj, Category = categoryObj, URL = langCategoryObj.URL, Title = articleObj.Title, Summary = articleObj.Summary, Thumbnail = articleObj.Thumbnail, Source = articleObj.Source, Published_Date=articleObj.Published_Date, Current_Date=articleObj.Current_Date, Is_New = articleObj.Is_New, Cluster_Id = langCategoryObj.Cluster_Id, Is_Rep = langCategoryObj.Is_Rep) archiveObj.save() #logger.info("Exited insertArchive ") def deleteArticleTable(deltaDays): deltaDate = datetime.date.today() - datetime.timedelta(days=deltaDays) articleDict = News_Article.objects.filter(Current_Date__lt=deltaDate).delete()
4a3758cee6d15d9b914705959ff5880f55b81d3e
[ "Python" ]
19
Python
vineetl/newsup
d800faa68e0c51de33e5498ff404340864e7d115
779ea5c60706564f4492794846730e1e13e6db83
refs/heads/master
<repo_name>john-f2/2D-Platformer-Prototype<file_sep>/Assets/Scripts/PlayerLife.cs /* * * * Player life script, will contain the player's health * and currently checks if the player has died or not * * * @author johnf2 * * */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class PlayerLife : MonoBehaviour { //player health variable public int playerHealth; //player death boolean public bool hasDied = false; // Use this for initialization void Start () { //initializes the player's health to 1 playerHealth = 1; } // Update is called once per frame //LateUpdate is called at the end of the update cycle void LateUpdate () { //initial implementation of player fall death //if the player position is less than -5, reload the scene if(gameObject.transform.position.y < -10){ SceneManager.LoadScene("PrototypeScene_1"); } } } <file_sep>/Assets/Scripts/EnemyMovement.cs /* * * Enemy gameObject movement class * * * * * @author john * * */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyMovement : MonoBehaviour { //enemy speed variable public int enemySpeed; //this enemy will only move in the x direction //thus we can create a variable to only refer to the x axis public int xMovementDirection; //boolean to see which direction the enemy object is facing //public bool isFacingLeft = false; private bool isTouchingGround = false; //hitDistance is used to see how far away an object before it will be hit public float hitDistance = 0.9f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { //gives the gameObject movement only on the x direction //this will move the enemy object as far are the xMovementDirection //currently i have it where it just moves right the entire time //i added in the gameObject.GetComponent<Rigidbody2D>().velocity.y to make the object fall down a hole correctly BasicEnemyMovement(); } //basic enemy movement function //will move one direction until it hits a wall, then flip and move the other way //called in update() function void BasicEnemyMovement(){ //raycast that will dectect collisions //the object could be a wall or the player RaycastHit2D hitObject = Physics2D.Raycast(transform.position, new Vector2(xMovementDirection, 0)); if(hitObject.distance < hitDistance){ FlipEnemy(); } gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(xMovementDirection, gameObject.GetComponent<Rigidbody2D>().velocity.y) * enemySpeed; } private void FlipEnemy(){ Debug.Log("the enemy has flipped"); //if (xMovementDirection < 0.0f) //{ // GetComponent<SpriteRenderer>().flipX = false; //} //else if (xMovementDirection > 0.0f) //{ // GetComponent<SpriteRenderer>().flipX = true; //} GetComponent<SpriteRenderer>().flipX = false; xMovementDirection *= -1; //we need to transform the localscale (which will flip the polygoncollider2d) //to reflect the sprite change Vector2 localScale = gameObject.transform.localScale; localScale.x *= -1; //seting the localScale of the sprite to the new local scale transform.localScale = localScale; } } <file_sep>/README.md # 2D-Platformer-Prototype My 2D Platformer Prototype ## Purpose and Goals Inspired by playing 2D side-scrolling platformers (specifically Momodora) I wanted to learn more about game development and potentially turn it into a new side programming hobby. I also felt that it was a great way to learn C#. My ultimate goal is to create a metroidvania style game This project will be where I do all my initial learning and prototyping for the game. ## Installation In order to run this project, you need to install Unity and an IDE that will let you edit C# code (MonoDevelop for Mac or VisualStudios for Window) You can then import the project into Unity ## Built with • Unity • C# ## Author John-f2 <file_sep>/Assets/Scripts/PlayerMovement.cs /* * * * PlayerMovement Script * Used to give movement to the player object * * * * @author johnf2 * */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { //public variables for the player characters public int playerSpeed = 5; public int playerJumpPower = 1250; //movement on the X plane private float xMovement; //member variable to know if the player is on the ground public bool isGrounded; // Use this for initialization void Start () { } // Update is called once per frame void Update () { MovePlayer(); } //player movement void MovePlayer(){ //Controls //set the movement on the X plane by getting the input from GetAxis xMovement = Input.GetAxis("Horizontal"); if (Input.GetButtonDown("Jump") && isGrounded) { Jump(); } //Direction //Flips player depending on which direction the player is moving if (xMovement < 0.0f ) { GetComponent<SpriteRenderer>().flipX = true; } else if (xMovement > 0.0f) { GetComponent<SpriteRenderer>().flipX = false; } //allows the player to move left or right gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(xMovement * playerSpeed, gameObject.GetComponent<Rigidbody2D>().velocity.y); } //Jumping function void Jump(){ //this GetComponent function will make the player "jump" GetComponent<Rigidbody2D>().AddForce(Vector2.up * playerJumpPower); isGrounded = false; } //Listener function //when the player gameObject collides with an object this function will call private void OnCollisionEnter2D(Collision2D col) { //simple way to see what the player object has hit Debug.Log("Player has collided with " + col.collider.name); //checks if the object the plaer collided with is, has the ground tag //allows the player to jump again if (col.gameObject.tag == "ground"){ isGrounded = true; } } } <file_sep>/Assets/Scripts/SaveDataManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; //saving the data libraries using System; using System.IO; //this library will convert our data to binary using System.Runtime.Serialization.Formatters.Binary; //using PlayerPrefs //example to use later //PlayerPrefs.SetInt("HighScore", 10); //gets the value //PlayerPrefs.GetInt("HighScore", 10); /** * * * SaveDataManager class * used to save game data * data is represented as a class and is saved as binary to a file * * * @author(johnf2) * */ public class SaveDataManager : MonoBehaviour { //static representation of class public static SaveDataManager dataManager; // Update is called once per frame void Update () { } public void SaveDataToFile(){ } public void LoadDataFromFile(){ } } /** * * GameData class used to * represent the game data which will be saved * this is the class to be stored and loaded on file * * */ class GameData{ //private member variables that will be saved //this will be collectables, lifes, etc. } <file_sep>/Assets/Scripts/CameraScript.cs /* * * Camera Script * Currently only has player tracking (camera will follow the player) * * * @author johnf2 * */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraScript : MonoBehaviour { //reference to the player gameObject private GameObject player; //these variables will "clamp" the camera to a certain position //so it doesnt move off to the side //hence: xMin is the lowest position the camera can move on the x-plane public float xMin; public float xMax; public float yMin; public float yMax; // Use this for initialization void Start () { //on initialization, sets the player gameObject variable with the actual player GameObject player = GameObject.FindGameObjectWithTag("Player"); } // Update is called once per frame // LateUpdate is called at the end of the update cycle void LateUpdate() { //TODO : fix camera tracking when player falls below a certain point later //this is my super ghetto way to track the player when he moves down //there is probably a better way to do this //this is a pretest for camera tracking in a metroidvania game //it works but it is not smooth at all //if(player.transform.position.y < -3f){ // yMin = -20; //} //Mathf is part of the unity library //what clamp does is clamp the value ofthe player's position to be between the min and max float x = Mathf.Clamp(player.transform.position.x, xMin, xMax); float y = Mathf.Clamp(player.transform.position.y, yMin, yMax); //the camera poistion changes based on changes from the playerObject gameObject.transform.position = new Vector3(x, y, gameObject.transform.position.z); } }
3ab8f62182c108e0161fccb0f64128d7f940e3b9
[ "Markdown", "C#" ]
6
C#
john-f2/2D-Platformer-Prototype
88a01a618d187f0d9cbb0cc68bd04fdf7488fce1
5dfb4579834359d9136df7db152ab4695dfbc0c9
refs/heads/master
<repo_name>jangjichang/askcompany<file_sep>/README.md # askcompany repository for heroku deploy # heroku url <file_sep>/askcompany/static/main.js console.log('askcompay/static/main.js loaded'); <file_sep>/shop/views.py from django.http import HttpResponse from django.shortcuts import render, get_object_or_404, redirect from .models import Item from .forms import ItemForm import logging # from urllib.parse import quote # import os, requests # from io import BytesIO # from PIL import Image, ImageDraw, ImageFont logger = logging.getLogger(__name__) # __name__ => "shop.views" def archives_year(request, year): return HttpResponse('{}년도에 대한 내용'.format(year)) def item_list(request): qs = Item.objects.all() q = request.GET.get('q', '') if q: qs = qs.filter(name__icontains=q) logger.debug('query: {}'.format(q)) return render(request, 'shop/item_list.html', { 'item_list': qs, 'q': q, }) def item_detail(request, pk): item = get_object_or_404(Item, pk=pk) return render(request, 'shop/item_detail.html', { 'item': item }) def item_new(request, item=None): if request.method == 'POST': form = ItemForm(request.POST, request.FILES, instance=item) if form.is_valid(): item = form.save() return redirect(item) else: form = ItemForm(instance=item) return render(request, 'shop/item_form.html', { 'form': form, }) def item_edit(request, pk): item = get_object_or_404(Item, pk=pk) return item_new(request, item) # def response_excel(request): # filepath = r'C:\Users\jc\Downloads\test_file.xlsx' # filename = os.path.basename(filepath) # with open(filepath, 'rb') as f: # response = HttpResponse(f, content_type='application/vnd.ms-excel') # encoded_filename = quote(filename) # response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(encoded_filename) # return response # def response_image(request): # ttf_path = r'C:\Windows\Fonts\Gadugi.ttf' # image_url = r'C:\Users\jc\Downloads\jcjang.png' # canvas = Image.open(image_url) # font = ImageFont.truetype(ttf_path, 40) # draw = ImageDraw.Draw(canvas) # text = '<NAME>' # left, top = 10, 10 # margin = 10 # width, height = font.getsize(text) # right = left + width + margin # bottom = top + height + margin # draw.rectangle((left, top, right, bottom), (255, 255,224)) # draw.text((15, 15), text, font=font, fill=(20, 20, 20)) # response = HttpResponse(content_type='image/png') # canvas.save(response, format='PNG') # return response <file_sep>/shop/migrations/0003_auto_20190823_1005.py # Generated by Django 2.1 on 2019-08-23 01:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0002_item_is_publish'), ] operations = [ migrations.AlterModelOptions( name='item', options={'ordering': ['id']}, ), migrations.AddField( model_name='item', name='photo', field=models.ImageField(blank=True, upload_to=''), ), ] <file_sep>/shop/admin.py from django.contrib import admin from .models import Item @admin.register(Item) class ItemAdmin(admin.ModelAdmin): list_display = ['pk', 'name', 'price', 'desc', 'won_price', 'short_desc', 'is_publish'] list_display_links = ['name'] list_filter = ['is_publish', 'updated_at'] search_fields = ['name'] def won_price(self, item): won = str(item.price) comma_won = "" mod = len(won) % 3 for i, v in enumerate(won): comma_won += v if (i+1) % 3 == mod and i != len(won)-1: comma_won += "," return comma_won def short_desc(self, item): return item.desc[:10]
f01a7cccccf0826a887f8deb8155074fb2a733ee
[ "Markdown", "Python", "JavaScript" ]
5
Markdown
jangjichang/askcompany
e8cf7f83e70570b4a7d85aa8d4b686da73f0e904
e1c64132020b845e7a689b4eea7b9eadb24f8fc0
refs/heads/master
<repo_name>yyjazsf/study-angular<file_sep>/src/js/factory_service_provider.js 'use strict'; /* * * Factory vs Service vs Provider * http://www.oschina.net/translate/angularjs-factory-vs-service-vs-provider */ var app = angular.module('app', []); //全局变量 app.constant('fooConfig', [ { name: '首页', url: '/' }, { name: '关于我', url: '/about' }, { name: '博客', url: '/list' } ]); /* * Factory demo */ app.factory('myFactory', function () { var _artlist = [ { name: 'yyj' }, { name: 'zyd' } ], service = {}; service.getArtlist = function () { return _artlist; }; return service; }); /* * service demo */ app.service('myService', function () { var _bookList = [ { name: 'angular 权威指南' }, { name: 'javascript 高级程序设计' } ]; this.getBookList = function () { return _bookList; }; }); //provider demo app.provider('info', function () { var name = "Private"; return { setPrivate: function (newVal) { name = newVal; }, $get: function () { function getInfo() { return name; } return { variable: "This is public variable in provider", getPrivate: getInfo }; } } }); /* * $provide.decorator 不能用于constant * provider在config引用,需要加后缀 Provider,info变成infoProvider */ app.config(function(infoProvider,$provide) { infoProvider.setPrivate('New value from config'); //装横器,修改provider $provide.decorator('info', function($delegate) { //给info provider添加方法 $delegate.greet = function() { return "成功使用 $provide.decorator "; }; return $delegate; }); }); // app.controller('appCtrl', ['$scope', 'myFactory', 'myService','info', function ($scope, myFactory, myService,info) { var vm = $scope.vm = {}; vm.list = myFactory.getArtlist(); vm.books = myService.getBookList(); $scope.info=info; }]); /* * 创建非单例对象 */ // Our class function Person( json ) { angular.extend(this, json); } Person.prototype = { update: function() { // Update it (With real code :P) this.name = "angularjs"; this.country = "Canada"; } }; Person.getById = function( id ) { // Do something to fetch a Person by the id return new Person({ id:id, name: "Jesus", country: "Spain" }); }; // Our factory app.factory('personService', function() { return { getById: Person.getById }; }); app.controller('multitonCtrl', function ($scope,personService) { $scope.aPerson = Person.getById(1); $scope.updateIt = function() { $scope.aPerson.update(); }; }); app.controller('multitonCtrl2', function ($scope,personService) { $scope.aPerson = Person.getById(2); $scope.updateIt = function() { $scope.aPerson.update(); }; });<file_sep>/src/js/provider.js 'use strict'; /* * provider * 唯一可以传递到app.config */ var app = angular.module('app', ['ngMaterial']); app.provider('myProvider', function () { this.thingFromConfig=''; // var service = {}, baseUrl = 'http://itunes.apple.com/search?term=', _artist = '', _finalUrl = ''; // var markUrl = function () { _artist = _artist.split(' ').join('+'); _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'; return _finalUrl; }; this.$get = function ($http, $q) { return { callIturns: function () { var deferred; markUrl(); deferred = $q.defer(); $http({ method: 'JSONP', url: _finalUrl }) .success(deferred.resolve) .error(deferred.reject); return deferred.promise; }, setArtist: function (artist) { _artist = artist; }, getArtist: function () { return _artist; }, thingFromConfig:this.thingFromConfig } } }); app.config(function (myProviderProvider) { myProviderProvider.thingFromConfig='app.config 修改的值'; }); app.controller('appCtrl', ['$scope', 'myProvider', function ($scope, myProvider) { var data = $scope.data = { artist: 'love' }; data.thingFromConfig=myProvider.thingFromConfig; $scope.updateArtist = function () { myProvider.setArtist(data.artist); }; $scope.submitArtist = function () { $scope.updateArtist(); myProvider.callIturns() .then(function (_data) { data.artistData = _data; console.log(_data); }, function (error) { alert(error); console.log(error); }); }; }]);<file_sep>/src/typescript/greeter.ts 'use strict'; /** * Created by yj on 2015/9/18 0018. * http://www.typescriptlang.org/Tutorial * https://github.com/vilic/typescript-guide */ //ts没有undefined //var typeBool:any,这样就不会类型检查了 var typeBool:boolean = false; var typeString:string = ''; var typeNumber:number = 16; var arrayNumber:number[] = [1, 2, 3, 4]; var list:Array<number> = [1, 2, 3]; var normalArray:any[] = [1, true, null, '']; /* * 联合类型 Union Types */ //使用 | var multType:number|string = '1312';// multType = 123; // 使用括号. var arr:(number|Date|RegExp)[] = []; // 隐式声明类型, 但是由于 '...' 是 string, TypeScript 会认为 def 是 string. var def = '...'; //def=123;//错误 function optionalDefault(a = 'some text', b = true):void { return; } optionalDefault(); // 枚举类型实例的值默认由 0 开始. //{0: "Red", 1: "Green", 2: "Blue", Red: 0, Green: 1, Blue: 2} enum Color {Red, Green, Blue} ; //{0: "female", 2: "male", 3: "other", female: 0, male: 2, other: 3} enum sex {female, male = 2, other} ; var demoSex:sex = sex.male;//2 var mySex:string = sex[1];//sex.male是错的 console.log('mySex:string=sex[1] mySex=' + mySex); /* * 限制参数类型 */ function greeter(person:string) { return "Hello, " + person; } var user = 'yingyujia'; document.getElementById('ts01').innerText = greeter(user); /* * 使用接口 */ function printLabel(labelledObj:{label: string}) { console.log(labelledObj.label); } //外部定义 interface Person { firstname:string; lastname?:string;//问号代表可选属性 } function greeter2(person:Person) { return 'hello,' + person.firstname + ' ' + person.lastname; }; var user2 = { firstname: '[yj]', lastname : '[y]' }; document.getElementById('ts02').innerText = greeter2(user2); // interface SquareConfig { color?: string; width?: number; } function createSquare(config:SquareConfig):{color: string; area: number} { var newSquare = {color: "white", area: 100}; if (config.color) { newSquare.color = config.color; // Type-checker can catch the mistyped name here } if (config.width) { newSquare.area = config.width * config.width; } return newSquare; } var mySquare = createSquare({color: "black", width: 20}); console.log(mySquare); /* * 类 */ class Student { fullname:string; constructor(public firstname, public middleinitial, public lastname) { this.fullname = firstname + " " + middleinitial + " " + lastname; } greet() { return '[greet]helllo,' + this.fullname; } } var user3 = new Student("Jane", "M.", "User"); document.getElementById('ts03').innerText = greeter2(user3); document.getElementById('ts04').innerText = user3.greet(); /* * 继承 */ class Animal2 { constructor(private name:string) {} } class Animal { //自动生成 this.name=name; constructor(public name:string) {} say(msg:string) { console.log('Animal.say'); return this.name + ' say ' + msg + '.'; } } class Snake extends Animal { constructor(name:string) { super(name); } say() { console.log('Snake.say'); return super.say('嘶~'); } } var sam = new Snake('Sammy'); var tom:Animal = new Snake('Tom'); document.getElementById('ts05').innerText = sam.say(); /* * 泛型 Generics */ //泛型-interface interface IFace<T> { value: T; } var face:IFace<boolean> = { value: true }; //泛型-function function foo<T>(arg:T):T { return arg; } // TypeScript 会基于参数自动推导 T 为 string. // 进而得知 str 为 string. var str = foo('abc'); //泛型 class class Greeter<T> { greeting:T; constructor(message:T) { this.greeting = message; } greet() { return this.greeting; } } var greeter3 = new Greeter<string>("Hello, world"); //Function Types interface SearchFunc { //参数限制 //返回值限制 (source:string, substring:string):boolean; } var mySearch:SearchFunc; mySearch = function (src:string, sub:string) { var result = src.search(sub);//indexOf <=IE8有兼容问题 search无兼容问题 if (result == -1) { return false; } else { return true; } }; var result = mySearch('小四是笨蛋', '是'); // interface StringArray { [index: number]: string; } var myArray:StringArray; //myArray = ['123', '456'];// // 不同于上面的例子, 常量枚举类型编译后不会保留 SomeConstType 这个对象, 也就不能由值获取实例名称了. const enum SomeConstType { constTypeA, constTypeB } var constType = SomeConstType.constTypeA; console.log(constType); // 输出数字 0. //模块 module MyModule { // 私有方法, 类似于一个闭包中的函数声明. function foo() { console.log('hello, world.'); } // 导出的方法. export function bar():void { foo(); } } MyModule.bar(); //指定了模块系统, 则 TypeScript 中一个文件就可以看做一个模块, 可以直接在文件中写 export //引用其他模块的方式也是类似的, 注意前方的 import 关键字, 最终将会编译为 `var...`. //但如果 TS 文件中写 `var`, `abc` 则会被当做一个类型为 `any` 的普通变量对待. //import abc = require('abc'); // interface ClockInterface { currentTime: Date; setTime(d:Date); } class Clock implements ClockInterface { currentTime:Date; setTime(d:Date) { this.currentTime = d; } constructor(h:number, m:number) { } } //Extending Interfaces interface Shape { color: string; } interface Square extends Shape/* ,other interface*/ { sideLength: number; } var square = <Square>{}; square.color = "blue"; square.sideLength = 10; //ECMAScript 5 var passcode = "<PASSWORD>"; class Employee { private _fullName: string; get fullName(): string { return this._fullName; } set fullName(newName: string) { if (passcode && passcode == "secret passcode") { this._fullName = newName; } else { alert("Error: Unauthorized update of employee!"); } } } var employee = new Employee(); employee.fullName = "<NAME>"; if (employee.fullName) { console.log(employee.fullName); } /* * Static Properties */ class Grid { static origin = {x: 0, y: 0}; calculateDistanceFromOrigin(point: {x: number; y: number;}) { var xDist = (point.x - Grid.origin.x); var yDist = (point.y - Grid.origin.y); return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale; } constructor (public scale: number) { }//放大比例 } var grid0:Grid;//Advanced Techniques grid0=new Grid(2.0); var grid1 = new Grid(1.0); // 1x scale var grid2 = new Grid(2.0); // 5x scale console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 0})); console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10})); /* * 接口继承类 */ class Point {//生成无用js x: number; y: number; } interface Point3d extends Point { z: number; } var point3d: Point3d = {x: 1, y: 2, z: 3}; //大乱入 var lr101 = "2a3b4c5d".replace(/\d/g, "$&x"); // 用$&表示匹配到的字符串,返回"2xa3xb4xc5xd" console.log(lr101); /* * str 匹配到的字符串 * strStart 匹配到的字符串起始位置 * source 整个字符串 */ var lr102 = "2a3b4c5d".replace(/\d/g, function (str, strStart, source) { console.log(str, strStart, source); switch (str) { case '2': return "X"; break; case '3': return "Y"; break; case '4': return "Z"; break; default : return "[未定义]"; break; } }); // 返回 "XaYbZc[未定义]d" console.log(lr102); //Closure function func() { var count = 0; return function () { count++; // 代码执行到这里时,innerFunc的作用域链上除了Local,Gobal之外还会出现一个Closure作用域(里面只有一个count变量),就是我们所说的闭包。 console.log(count); //debugger; // 调试查看Scope,试一试。 //Local Closure(闭包) Global } } var innerFunc = func(); innerFunc(); innerFunc(); //childNodes表示子节点(包括文本节点,元素节点、换行符等,IE67忽略空白的文本节点) children表示子元素(IE67将注释节点识别为元素节点) <file_sep>/src/js/$q.js 'use strict'; /* * */ var app=angular.module('app',[]); app.directive('mdAutocomplete', MdAutocomplete); /* * */ function MdAutocomplete(){ return { template:'<h2>aoto-complete</h2>' } } app.controller('appCtrl', ['$scope','$http','$q',function ($scope,$http,$q) { var vm=$scope.vm={}; $scope.$watch("vm.city",function(newvalue,old){ var deferred = $q.defer(); $http.get('data/data1.json',{py:newvalue}).success(deferred.resolve).error(deferred.reject); deferred.promise.then(function(data) { // 调用 promise API获取数据 .resolve console.log(data.name); }, function(error) { // 处理错误 .reject console.log(error); }); }); }]);<file_sep>/src/js/service.js 'use strict'; /* * service * 和factory类似,不过service 是ng内部new xxx() */ var app = angular.module('app', ['ngMaterial']); app.service('myService', [ '$http', '$q', function ($http, $q) { // var service = {}, baseUrl = 'http://itunes.apple.com/search?term=', _artist = '', _finalUrl = ''; // var markUrl = function () { _artist = _artist.split(' ').join('+'); _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'; return _finalUrl; }; // this.setArtist = function (artist) { _artist = artist; }; // this.getArtist = function () { return _artist; }; // this.callIturns = function () { var deferred; markUrl(); deferred = $q.defer(); $http({ method: 'JSONP', url: _finalUrl }) .success(deferred.resolve) .error(deferred.reject); return deferred.promise; }; //没有return } ]); app.controller('appCtrl', ['$scope','myService', function ($scope,myService) { var data = $scope.data = { artist:'love' }; $scope.updateArtist= function () { myService.setArtist(data.artist); }; $scope.submitArtist= function () { $scope.updateArtist(); myService.callIturns() .then(function (_data) { data.artistData=_data; console.log(_data); }, function (error) { alert(error); console.log(error); }); }; }]);<file_sep>/README.md # study angular1.x angular demo(study angular) ## node 0.12.7(不能用4.0) #### 依次执行 ``` npm install bower install gulp ``` <file_sep>/src/typescript/modules.ts ///<reference path="greeter.ts"/> //webstorm引用文件有效 /** * Created by yj on 2015/9/25 0025. */ interface StringValidator{ isAcceptable(a:string):boolean; } var letterReg=/^[A-Za-z]+$/; var numberReg=/^[0-9]+$/; class LettersOnlyValidator implements StringValidator{ isAcceptable(s:string){ return letterReg.test(s); } } class numOnlyValidator implements StringValidator{ isAcceptable(s:string){ return numberReg.test(s); } } // Some samples to try var strings = ['Hello', '98052', '101']; // Validators to use var validators: { [s: string]: StringValidator; } = {}; validators['ZIP code'] = new numOnlyValidator(); validators['Letters only'] = new LettersOnlyValidator(); // Show whether each string passed each validator strings.forEach(s => { for (var name in validators) { console.log('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches ' : ' does not match ') + name); } }); /* * module */ module Validation { export interface StringValidator { isAcceptable(s: string): boolean; } var lettersRegexp = /^[A-Za-z]+$/; var numberRegexp = /^[0-9]+$/; export class LettersOnlyValidator implements StringValidator { isAcceptable(s: string) { return lettersRegexp.test(s); } } export class ZipCodeValidator implements StringValidator { isAcceptable(s: string) { return s.length === 5 && numberRegexp.test(s); } } } var validators2: { [s: string]: Validation.StringValidator; } = {}; validators2['ZIP code'] = new Validation.ZipCodeValidator(); validators2['Letters only'] = new Validation.LettersOnlyValidator(); // Show whether each string passed each validator strings.forEach(s => { for (var name in validators2) { console.log('"' + s + '" ' + (validators2[name].isAcceptable(s) ? ' matches ' : ' does not match ') + name); } }); <file_sep>/src/js/factory.js 'use strict'; /* * factory * 和service类似,factory 使用 return * http://www.oschina.net/translate/angularjs-factory-vs-service-vs-provider */ var app = angular.module('app', ['ngMaterial']); app.factory('myFactory', [ '$http', '$q', function ($http, $q) { // var service = {}, baseUrl = 'http://itunes.apple.com/search?term=', _artist = '', _finalUrl = ''; // var markUrl = function () { _artist = _artist.split(' ').join('+'); _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'; return _finalUrl; }; // service.setArtist = function (artist) { _artist = artist; }; // service.getArtist = function () { return _artist; }; // service.callIturns = function () { var deferred; markUrl(); deferred = $q.defer(); $http({ method: 'JSONP', url: _finalUrl }) .success(deferred.resolve) .error(deferred.reject); return deferred.promise; }; return service; } ]); app.controller('appCtrl', ['$scope','myFactory', function ($scope,myFactory) { var data = $scope.data = { artist:'love' }; $scope.updateArtist= function () { myFactory.setArtist(data.artist); }; $scope.submitArtist= function () { $scope.updateArtist(); myFactory.callIturns() .then(function (_data) { data.artistData=_data; console.log(_data); }, function (error) { alert(error); console.log(error); }); }; }]);
00c207cf7076bc852b08d4187f6f2adc936f3fb0
[ "JavaScript", "TypeScript", "Markdown" ]
8
JavaScript
yyjazsf/study-angular
fc6ae6e6758b29cfbce9679c9adafb3708e4e260
85edd0598e1cef095733746cae9f0420b7946380
refs/heads/master
<file_sep><?php /** * Unfuddle Repository Callback XMPP Notify * * @link http://unfuddle.com/docs/topics/repository_callbacks * @author 2BJ dev2bj+gmail */ error_reporting(E_ALL ^ E_WARNING); set_time_limit(0); date_default_timezone_get('Europe/Moscow'); // Unfuddle config define('UNFUDDLE_SUBDOMAIN', '<subdomain>'); // recipients $developers = array('<EMAIL>', '<EMAIL>', '<EMAIL>'); // XMPP config define('XMPP_HOST', 'talk.google.com'); define('XMPP_PORT', 5222); define('XMPP_USER', '<bot>'); define('XMPP_PASSWD', <PASSWORD>>'); define('XMPP_RESOURCE', 'xmpphp'); define('XMPP_SERVER', 'talk.google.com'); // or you'r Google Apps for Your Domain // Run.. $commit = (array) simplexml_load_string(file_get_contents('php://input')); if ( ! isset($commit['author-date'])) { exit; } $message = sprintf( "Commit from %s (%s):" . PHP_EOL . "----------" . PHP_EOL . "%s" . PHP_EOL . "----------" . PHP_EOL . "URL: " . sprintf( "http://%s.unfuddle.com/a#/repositories/%d/commit?commit=%s", UNFUDDLE_SUBDOMAIN, $commit['repository-id'], $commit['revision'] ), $commit['committer-name'], date('d.m.Y H:i', strtotime($commit['author-date'])), $commit['message'] ); include 'vendor/XMPPHP/XMPPHP/XMPP.php'; $conn = new XMPPHP_XMPP(XMPP_HOST, XMPP_PORT, XMPP_USER, XMPP_PASSWD, XMPP_RESOURCE, XMPP_SERVER); try { $conn->connect(); $conn->processUntil('session_start'); $conn->presence(); foreach ($developers as $developer) { $conn->message($developer, $message); } $conn->disconnect(); } catch (XMPPHP_Exception $e) { die($e->getMessage()); }
c043b013019d76bd284e876ac4297dfe3591eb14
[ "PHP" ]
1
PHP
2bj/unfuddle-notify
282f1ce9f72b7e21c66bc3af3b37c2d968167bd0
b9f27e3148ad1c3141de4bf8f6b319d4ad635b85
refs/heads/master
<repo_name>dientrinh/robolectric<file_sep>/app/build.gradle apply plugin: 'com.android.application' apply plugin: 'jacoco' android { compileSdkVersion 22 buildToolsVersion '22.0.1' defaultConfig { applicationId "com.example.dientv.robolectricdemo" minSdkVersion 15 targetSdkVersion 22 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false // proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } debug{ // proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' testCoverageEnabled true } } productFlavors { } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.0.0' testCompile 'junit:junit:4.12' testCompile 'org.robolectric:robolectric:3.0' testCompile 'org.robolectric:robolectric:3.0-SNAPSHOT' compile 'org.robolectric:robolectric-shadows:3.0' compile 'org.robolectric:shadows-core:3.0' compile 'org.hamcrest:hamcrest-integration:1.3' compile 'org.hamcrest:hamcrest-core:1.3' compile 'org.hamcrest:hamcrest-library:1.3' compile 'org.mockito:mockito-core:1.10.19' testCompile 'com.google.dexmaker:dexmaker:1.1' testCompile 'org.powermock:powermock-api-mockito:1.6.4' testCompile 'org.powermock:powermock-module-junit4:1.6.4' testCompile 'org.powermock:powermock-core:1.6.4' } task jacocoTestReport(type: JacocoReport, dependsOn: 'testDebugUnitTest') { reports { xml.enabled = true html.enabled = true } jacocoClasspath = configurations['androidJacocoAnt'] def fileFilter = ['**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*', '**/*Test*.*', 'android/**/*.*'] def debugTree = fileTree(dir: "${buildDir}/intermediates/classes/debug", excludes: fileFilter) def mainSrc = "${project.projectDir}/src/main/java" sourceDirectories = files([mainSrc]) classDirectories = files([debugTree]) executionData = files("${buildDir}/jacoco/testDebugUnitTest.exec") } apply plugin: 'pmd' task pmd(type: Pmd) { ignoreFailures = true ruleSetFiles = files("${project.projectDir}/flatform/pmd/pmd-ruleset.xml") ruleSets = [] source 'src' include '**/*.java' exclude '**/gen/**' reports { xml.enabled = true html.enabled = false } } apply plugin: 'checkstyle' task checkstyle(type: Checkstyle) { ignoreFailures = true configFile file("${project.projectDir}/flatform/checkstyle/checkstyle.xml") source 'src' include '**/*.java' exclude '**/gen/**', '**/test/**' classpath = files() } //cpd check duplicated code plugin buildscript { repositories { mavenCentral() } dependencies { classpath 'de.aaschmid.gradle.plugins:gradle-cpd-plugin:0.4' } } apply plugin: 'cpd' cpdCheck { ignoreFailures = true source = files('src/main/java') } <file_sep>/app/src/main/java/com/example/dientv/robolectricdemo/SampleA.java package com.example.dientv.robolectricdemo; /** * Created by dien.tv on 4/12/2016. */ public class SampleA { private SampleB mSampleB; public String getStr() { return mSampleB.sampleb(); } }
983ff463f4f5b9f3a6ec3e024aed803c6e06fd0a
[ "Java", "Gradle" ]
2
Gradle
dientrinh/robolectric
004582d693bde37695466d8215b4ce16a873366e
3aba1b471531ca67dadd2757f938db5d5bc6e64e
refs/heads/master
<repo_name>zigvu/rasbari<file_sep>/engines/setting/test/setting_test.rb require 'test_helper' class SettingTest < ActiveSupport::TestCase test "truth" do assert_kind_of Module, Setting end end <file_sep>/app/authorizers/user_authorizer.rb class UserAuthorizer < ::ApplicationAuthorizer def self.default(adjective, user) # admin has ability to manage users user.role.isAtLeastAdmin? end def self.readable_by?(user) # manager has authority to see users user.role.isAtLeastManager? end end <file_sep>/engines/video/app/workflows/video/capture_workflow/start_vnc_server.rb module Video module CaptureWorkflow class StartVncServer def initialize(capture) @capture = capture end def canSkip false end def serve true end def handle(params) status = false trace = "Couldn't start VNC Server: Ensure remote is reachable" if @capture.stream.state.isAtOrAfterReady? status, trace = @capture.captureClient.startVncServer end return status, trace end end end end <file_sep>/engines/admin/lib/admin.rb require "admin/engine" module Admin def self.files_to_load app = File::expand_path('../../app', __FILE__) templateFolders = ["#{app}/assets", "#{app}/controllers", "#{app}/models", "#{app}/views"] nonTemplateFolders = Dir["#{app}/*"] - templateFolders nonTemplateFiles = [] nonTemplateFolders.each do |ntf| # assume that all files are namespaced Dir["#{ntf}/*/**"].each do |f| next if File.directory?(f) nonTemplateFiles << File.join(File.dirname(f), File.basename(f, ".*")) end end nonTemplateFiles end end <file_sep>/engines/setting/README.rdoc = Setting Setting and configuration manager. <file_sep>/engines/messaging/lib/messaging/engine.rb module Messaging class Engine < ::Rails::Engine isolate_namespace Messaging # Append routes before initialization initializer "messaging", before: :load_config_initializers do |app| Rails.application.routes.append do mount Messaging::Engine, at: "/messaging" end end # Load files after initialization initializer "messaging", after: :load_config_initializers do |app| Messaging.files_to_load.each { |file| require_relative file } end end end <file_sep>/engines/messaging/lib/messaging/connections/clients/storage_client.rb require 'socket' module Messaging module Connections module Clients class StorageClient < Messaging::Connections::GenericClient def initialize(serverHostname) @hostname = Socket.gethostname exchangeName = "#{Messaging.config.storage.exchange}" responseRoutingKey = "#{Messaging.config.storage.routing_keys.nimki.client}.#{@hostname}" machineRoutingKey = "#{Messaging.config.storage.routing_keys.nimki.server}.#{serverHostname}" super(exchangeName, responseRoutingKey, machineRoutingKey) Messaging.logger.info("Start StorageClient for hostname: #{@hostname}") end def setClientDetails header = Messaging::Messages::Header.dataRequest message = Messaging::Messages::Storage::ClientDetails.new(nil) message.type = Messaging::States::Storage::ClientTypes.capture message.hostname = @hostname responseHeader, responseMessage = call(header, message) status = responseHeader.isDataSuccess? return status, responseMessage.trace end def saveFile(clientFilePath, serverFilePath) opType = Messaging::States::Storage::FileOperationTypes.put commonFileOps(clientFilePath, serverFilePath, opType) end def getFile(serverFilePath, clientFilePath) opType = Messaging::States::Storage::FileOperationTypes.get commonFileOps(clientFilePath, serverFilePath, opType) end def delete(serverFilePath) opType = Messaging::States::Storage::FileOperationTypes.delete commonFileOps(nil, serverFilePath, opType) end def closeConnection opType = Messaging::States::Storage::FileOperationTypes.closeConnection commonFileOps(nil, nil, opType) end def commonFileOps(clientFilePath, serverFilePath, opType) header = Messaging::Messages::Header.dataRequest message = Messaging::Messages::Storage::FileOperations.new(nil) message.hostname = @hostname message.type = opType message.clientFilePath = clientFilePath message.serverFilePath = serverFilePath responseHeader, responseMessage = call(header, message) status = responseHeader.isDataSuccess? return status, responseMessage.trace end end # StorageClient end # Clients end # Connections end # Messaging <file_sep>/db/seeds.rb # The first user is Super Admin zigvuAdmin = User.create(first_name: "Zigvu", last_name: "Admin", email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: '<PASSWORD>', zrole: "superAdmin") # Create some stream videoStream = Video::Stream.create(ztype: "webBroadcast", zstate: "stopped", zpriority: "none", name: "FunTube", base_url: "funtube.com") <file_sep>/engines/setting/test/models/setting/machine_test.rb require 'test_helper' module Setting class MachineTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end end <file_sep>/engines/setting/app/models/setting/machine.rb module Setting class Machine < ActiveRecord::Base # authorizer: current_user.can_read?(resource) include Authority::Abilities self.authorizer_name = 'Setting::MachineAuthorizer' # Validations validates :zstate, presence: true validates :ztype, presence: true validates :zcloud, presence: true validates :hostname, presence: true validates :ip, presence: true def state Setting::MachineStates.new(self) end def type Setting::MachineTypes.new(self) end def cloud Setting::CloudTypes.new(self) end end end <file_sep>/app/models/user.rb class User < ActiveRecord::Base # authorizer: current_user.can_read?(resource) include Authority::UserAbilities # authorizer: user.readable_by(current_user) include Authority::Abilities # Devise token authentication for API acts_as_token_authenticatable # Include default devise modules. Others available are: # :confirmable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :timeoutable, :lockable # role def role Admin::UserRoles.new(self) end end <file_sep>/config/application.rb require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Rasbari class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true # ZIGVU BEGIN: Change default scaffold generation config.generators do |g| g.orm :active_record g.template_engine :erb g.test_framework :test_unit, fixture: false g.helper false g.assets false g.view_specs false g.jbuilder false end # ZIGVU END: Change default scaffold generation # ZIGVU BEGIN: Load order of engines # For some reason, putting messaging engine before others doesn't allow # subclassing of messaging classes in other engines config.railties_order = [ Setting::Engine, Admin::Engine, Video::Engine, Messaging::Engine, :main_app, :all ] # ZIGVU END: Load order of engines # ZIGVU BEGIN: autoloadable modules config.autoload_paths += Dir["#{config.root}/app/**/"] # ZIGVU END: autoloadable modules end end <file_sep>/engines/messaging/lib/messaging/config/reader.rb require 'yaml' module Messaging module Config class Reader attr_reader :config def initialize(yamlConfigFile) raise "Config file #{yamlConfigFile} doesn't exist" if !File.exist?(yamlConfigFile) if Module.const_defined?('Rails') env = Rails.env else env = 'development' env = ENV['RAILS_ENV'] if ENV['RAILS_ENV'] end @config ||= begin all_config = YAML.load_file(yamlConfigFile) || {} env_config = all_config[env] config = Messaging::BaseLibs::DeepSymbolize.convert(env_config) if env_config config end end end end end <file_sep>/bin/rasbari_servers #!/usr/bin/env ruby # @author: Evan require 'rubygems' require 'daemons' class RasbariServers def initialize $bunny_connection = Messaging.connection # start servers startCaptureServer # sleep - otherwise this will exit loop { sleep 1000 } rescue SystemExit, Interrupt Rails.logger.info("Exiting application") rescue Exception => e STDERR.puts e.message STDERR.puts e.backtrace Rails.logger.fatal(e) end def startCaptureServer captureHandler = Video::MainHandler.new Messaging.rasbari_cache.video_capture.server(captureHandler) end end dir = File.expand_path(File.join(File.dirname(__FILE__), '..')) daemon_options = { :multiple => false, :dir_mode => :normal, :dir => File.join(dir, 'tmp', 'pids'), :backtrace => true } Daemons.run_proc('rasbari_servers', daemon_options) do if ARGV.include?('--') ARGV.slice! 0..ARGV.index('--') else ARGV.clear end Dir.chdir dir require File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment')) # server_logger = Logger.new(File.join(Rails.root, "log", "rasbari_servers.log")) server_logger = Logger.new(STDOUT) Rails.logger = server_logger ActiveRecord::Base.logger = server_logger RasbariServers.new end <file_sep>/engines/messaging/lib/messaging/connections/rpc_server.rb # Note: Headers and mesages are exchanged as JSON data but are converted to # corresponding objects during API call to this file module Messaging module Connections class RpcServer def initialize(connection, exchangeName, listenRoutingKey, rpcHandlerObj) @channel = connection.create_channel @exchange = @channel.topic(exchangeName, :durable => true) # temporary exclusive queue for server to accept messages @serverQueue = @channel.queue("", exclusive: true, auto_delete: true) @serverQueue.bind(@exchange, routing_key: listenRoutingKey) @rpcHandlerObj = rpcHandlerObj end def start # need a non-blocking connection else rails won't load @serverQueue.subscribe(manual_ack: true) do |delivery_info, properties, payload| responseHeaders, responseMessage = @rpcHandlerObj.call( Messaging::Messages::Header.new(properties.headers), Messaging::Messages::MessageFactory.getMessage(payload) ) # once message is handled, send ack @channel.ack(delivery_info.delivery_tag) @exchange.publish( responseMessage.to_json, routing_key: properties.reply_to, correlation_id: properties.correlation_id, headers: responseHeaders.to_json ) end end end end end <file_sep>/engines/video/app/models/video/capture.rb module Video class Capture < ActiveRecord::Base def storageMachine self.storage_machine_id ? Setting::Machine.find(self.storage_machine_id) : nil end def captureMachine self.capture_machine_id ? Setting::Machine.find(self.capture_machine_id) : nil end def storageClient raise "No storage machine specified yet" if self.storage_machine_id == nil Messaging.rasbari_cache.storage.client(storageMachine.hostname) end def captureClient raise "No capture machine specified yet" if self.capture_machine_id == nil Messaging.rasbari_cache.video_capture.client(captureMachine.hostname) end def startedByUser self.started_by ? User.find(self.started_by) : nil end def stoppedByUser self.stopped_by ? User.find(self.stopped_by) : nil end def toMessage ar = self.attributes.symbolize_keys.merge({ captureId: self.id, captureUrl: self.capture_url, playbackFrameRate: self.playback_frame_rate, storageHostname: self.storageMachine.hostname, }) Messaging::Messages::VideoCapture::CaptureDetails.new(ar) end def isStopped? self.stopped_at != nil end belongs_to :stream has_many :clips, dependent: :destroy end end <file_sep>/engines/messaging/lib/messaging/connections/generic_client.rb module Messaging module Connections class GenericClient attr_accessor :exchangeName, :responseRoutingKey, :machineRoutingKey attr_accessor :rpcClient def initialize(exchangeName, responseRoutingKey, machineRoutingKey) connection = $bunny_connection || Messaging.connection @exchangeName = exchangeName @responseRoutingKey = responseRoutingKey @machineRoutingKey = machineRoutingKey @rpcClient = Messaging::Connections::RpcClient.new( connection, @exchangeName, @responseRoutingKey ) end def call(header, message, timeout = nil) # wait no more than 30 minutes timeout ||= 30 * 60 @rpcClient.call(@machineRoutingKey, header, message, timeout) end # Common methods def isRemoteAlive? header = Messaging::Messages::Header.pingRequest message = Messaging::Messages::MessageFactory.getNoneMessage # timeout after 2 minutes of ping call timeout = 120 responseHeader, _ = call(header, message, timeout) status = responseHeader.isPingSuccess? trace = status ? "Ping successful" : "Couldn't ping remote" return status, trace end end end end <file_sep>/engines/messaging/lib/messaging/messages/header_states.rb # Note: This relies in monkeypatching of module in # config/initializers/monkeypatch.rb (for Rails) # messaging/monkeypatch.rb (for non-Rails) module Messaging module Messages class HeaderStates def self.states ["request", "unknown", "success", "failure"] end zextend BaseNonPersisted, Messaging::Messages::HeaderStates.states, { prefix: 'state' } attr_reader :state def initialize(s) @state = s end end end end <file_sep>/engines/video/app/states/video/stream_priorities.rb module Video class StreamPriorities < BaseAr::ArAccessor def self.priorities ["none", "low", "medium", "high", "immediate"] end zextend BaseRole, Video::StreamPriorities.priorities def initialize(stream) super(stream, :zpriority) end end end <file_sep>/engines/video/app/workflows/video/capture_workflow/set_details.rb module Video module CaptureWorkflow class SetDetails def initialize(capture) @capture = capture end def canSkip @capture.stream.state.isAfterConfiguring? end def serve true end def handle(params) status = false trace = "Couldn't save capture details to database" if @capture.update(params) status = true trace = "Saved capture details to database" end return status, trace end end end end <file_sep>/engines/video/app/models/video/stream.rb module Video class Stream < ActiveRecord::Base # authorizer: current_user.can_read?(resource) include Authority::Abilities self.authorizer_name = 'Video::StreamAuthorizer' # Validations validates :name, presence: true validates :base_url, presence: true validates :ztype, presence: true def state Video::StreamStates.new(self) end def type Video::StreamTypes.new(self) end def priority Video::StreamPriorities.new(self) end has_many :captures, dependent: :destroy has_many :clips, through: :captures end end <file_sep>/engines/video/app/handlers/video/clip_details_handler.rb module Video class ClipDetailsHandler def initialize(header, message) @header = header @message = message end def handle returnHeader = Messaging::Messages::Header.dataSuccess returnMessage = @message returnMessage.trace = "Clip created" capture = Video::Capture.find(@message.captureId) clip = capture.clips.create clip.state.setCreated returnMessage.clipId = clip.id returnMessage.storageClipPath = clip.clipPath returnMessage.storageThumbnailPath = clip.thumbnailPath return returnHeader, returnMessage end def canHandle? Messaging::Messages::VideoCapture::ClipDetails.new(nil).isSameType?(@message) end end end <file_sep>/engines/sample_engine/config/routes.rb SampleEngine::Engine.routes.draw do # TODO: # root to: "controller#index" end <file_sep>/engines/video/app/controllers/video/streams_controller.rb require_dependency "video/application_controller" module Video class StreamsController < ApplicationController authorize_actions_for Stream before_action :set_stream, only: [:show, :edit, :update, :destroy] # GET /streams def index @activeStreams = Stream.where.not(zstate: Video::StreamStates.stopped) @inactiveStreams = Stream.where(zstate: Video::StreamStates.stopped) end # GET /streams/1 def show @activeCaptures = @stream.captures.where(stopped_at: nil).order(created_at: :desc) @stoppedCaptures = @stream.captures.where.not(stopped_at: nil).order(stopped_at: :desc) end # GET /streams/new def new @stream = Stream.new @streamTypes = Video::StreamTypes.to_h end # GET /streams/1/edit def edit @streamTypes = Video::StreamTypes.to_h end # POST /streams def create @stream = Stream.new(stream_params) if @stream.save @stream.state.setStopped @stream.priority.setNone redirect_to @stream, notice: 'Stream was successfully created.' else render :new end end # PATCH/PUT /streams/1 def update if @stream.update(stream_params) redirect_to @stream, notice: 'Stream was successfully updated.' else render :edit end end # DELETE /streams/1 def destroy @stream.destroy redirect_to streams_url, notice: 'Stream was successfully destroyed.' end private # Use callbacks to share common setup or constraints between actions. def set_stream @stream = Stream.find(params[:id]) end # Only allow a trusted parameter "white list" through. def stream_params params.require(:stream).permit(:ztype, :zstate, :zpriority, :name, :base_url) end end end <file_sep>/engines/video/app/controllers/video/captures_controller.rb require_dependency "video/application_controller" module Video class CapturesController < ApplicationController # Same permission model as for stream authorize_actions_for Stream authority_actions :start_vnc => :read authority_actions :force_stop => :read before_action :set_capture, only: [:show, :destroy, :start_vnc, :force_stop] # GET /captures/1/start_vnc def start_vnc status, trace = Video::CaptureWorkflow::StartVncServer.new(@capture).handle({}) notice = status ? :notice : :alert redirect_to capture_path(@capture), notice => trace end # GET /captures/1/force_stop def force_stop status, trace = Video::CaptureWorkflow::StopCapture.new(@capture).handle({ current_user_id: current_user.id }) notice = status ? :notice : :alert redirect_to capture_path(@capture), notice => trace end # GET /captures/1 def show @clips = @capture.clips.order(id: :desc).limit(8) end # GET /captures/new def new stream = Stream.find(params[:stream_id]) capture = stream.captures.create stream.state.setConfiguring redirect_to capture_workflow_path(Wicked::FIRST_STEP, capture_id: capture.id) end # DELETE /captures/1 def destroy # clean up any pending workflow steps Video::CaptureWorkflow::StopCapture.new(@capture).handle({ current_user_id: current_user.id }) @capture.destroy redirect_to stream_path(@stream), notice: 'Capture was successfully destroyed.' end private # Use callbacks to share common setup or constraints between actions. def set_capture @capture = Capture.find(params[:id]) @stream = @capture.stream end end end <file_sep>/engines/video/app/states/video/clip_states.rb module Video class ClipStates < BaseAr::ArAccessor def self.states ["created", "saved", "deleted"] end zextend BaseState, Video::ClipStates.states def initialize(clip) super(clip, :zstate) end end end <file_sep>/engines/messaging/lib/messaging/states/storage/file_operation_types.rb # Note: This relies in monkeypatching of module in # config/initializers/monkeypatch.rb (for Rails) # messaging/monkeypatch.rb (for non-Rails) module Messaging module States module Storage class FileOperationTypes def self.types ["put", "get", "delete", "closeConnection"] end zextend BaseNonPersisted, Messaging::States::Storage::FileOperationTypes.types, { prefix: 'type' } attr_reader :type def initialize(t) @type = t end end end end end <file_sep>/engines/messaging/lib/messaging/messages/message_factory.rb require 'json' module Messaging module Messages class MessageFactory def self.getMessage(jsonMessage) message = Messaging::BaseLibs::DeepSymbolize.convert(JSON.parse(jsonMessage)) categorySym = message.category.split("_").map{ |s| s.capitalize }.join("") nameSym = message.name.split("_").map{ |s| s.capitalize }.join("") moduleName = "Messaging::Messages::#{categorySym}::#{nameSym}" if Object.const_defined?(moduleName) return Object.const_get(moduleName).new(message) end # Should not reach here Messaging.logger.error("MessageFactory: Couldn't find message: categorySym: #{categorySym}, nameSym: #{nameSym}") raise "MessageFactory: Couldn't find message class for jsonMessage: #{jsonMessage}" end def self.getNoneMessage Messaging::Messages::General::None.new(nil) end end end end <file_sep>/engines/messaging/lib/messaging/connections/cache.rb # Class to enable memoization of client/servers module Messaging module Connections class RasbariCache # -------------------------------------------------------------------------- # VideoCapture def video_capture @video_capture ||= Messaging::Connections::RasbariCache::VideoCapture.new end class VideoCapture def client(hostname) @clients ||= {} @clients[hostname] ||= Video::RasbariClient.new(hostname) end def server(handler) @server ||= Video::RasbariServer.new(handler) end end # END class VideoCapture # -------------------------------------------------------------------------- # -------------------------------------------------------------------------- # Storage def storage @storage ||= Messaging::Connections::RasbariCache::Storage.new end class Storage def client(hostname) @clients ||= {} @clients[hostname] ||= Messaging::Connections::Clients::StorageClient.new(hostname) end end # END class Storage # -------------------------------------------------------------------------- end # END class RasbariCache end end <file_sep>/engines/video/app/controllers/video/captures/workflow_controller.rb require_dependency "video/application_controller" module Video class Captures::WorkflowController < ApplicationController include Wicked::Wizard before_action :set_steps before_action :setup_wizard before_action :set_steps_ll, only: [:show, :update] def show case step when :set_details @workflowObj = Video::CaptureWorkflow::SetDetails.new(@capture) @workflowObj.canSkip ? skip_step : @workflowObj.serve when :set_machines @workflowObj = Video::CaptureWorkflow::SetMachines.new(@capture) @workflowObj.canSkip ? skip_step : @workflowObj.serve when :ping_nimki @workflowObj = Video::CaptureWorkflow::PingNimki.new(@capture) @workflowObj.canSkip ? skip_step : @workflowObj.serve when :set_remote_ready @workflowObj = Video::CaptureWorkflow::SetRemoteReady.new(@capture) @workflowObj.canSkip ? skip_step : @workflowObj.serve when :start_capture @workflowObj = Video::CaptureWorkflow::StartCapture.new(@capture) @workflowObj.canSkip ? skip_step : @workflowObj.serve when :stop_capture @workflowObj = Video::CaptureWorkflow::StopCapture.new(@capture) @workflowObj.canSkip ? skip_step : @workflowObj.serve end render_wizard end def update status = false trace = "Could not complete step - unknown workflow step" case step when :set_details prms = params.require(:capture) .permit(:capture_url, :comment, :width, :height, :playback_frame_rate) status, trace = Video::CaptureWorkflow::SetDetails.new(@capture).handle(prms) when :set_machines prms = params.require(:capture).permit(:storage_machine_id, :capture_machine_id) status, trace = Video::CaptureWorkflow::SetMachines.new(@capture).handle(prms) when :ping_nimki status, trace = Video::CaptureWorkflow::PingNimki.new(@capture).handle(params) when :set_remote_ready status, trace = Video::CaptureWorkflow::SetRemoteReady.new(@capture).handle(params) when :start_capture params.merge!({current_user_id: current_user.id}) status, trace = Video::CaptureWorkflow::StartCapture.new(@capture).handle(params) when :stop_capture params.merge!({current_user_id: current_user.id}) status, trace = Video::CaptureWorkflow::StopCapture.new(@capture).handle(params) end # next step based on current step result if status # for some reason `finish_wizard_path` below not working if step == steps.last redirect_to stream_path(@capture.stream) else render_wizard @capture end else # re-render the current step flash.now[:alert] = trace render_wizard end end def finish_wizard_path stream_path(@capture.stream) end private # Use callbacks to share common setup or constraints between actions. def set_steps @capture = Capture.find(params[:capture_id]) @stream = @capture.stream self.steps = [ :set_details, :set_machines, :ping_nimki, :set_remote_ready, :start_capture, :stop_capture ] end def set_steps_ll @current_step = step @prev_step = steps.index(step) == 0 ? nil : steps[steps.index(step) - 1] @next_step = steps.index(step) == (steps.count - 1) ? nil : steps[steps.index(step) + 1] end end end <file_sep>/engines/sample_engine/lib/sample_engine/engine.rb module SampleEngine class Engine < ::Rails::Engine isolate_namespace SampleEngine # Append routes before initialization initializer "sample_engine", before: :load_config_initializers do |app| Rails.application.routes.append do mount SampleEngine::Engine, at: "/sample_engine" end end # Load files after initialization initializer "sample_engine", after: :load_config_initializers do |app| SampleEngine.files_to_load.each { |file| require_relative file } end # Change default generator to generate less files config.generators do |g| g.orm :active_record g.template_engine :erb g.test_framework :test_unit, fixture: false g.helper false g.assets false g.view_specs false g.jbuilder false g.templates.unshift File::expand_path('../../templates', __FILE__) end end end <file_sep>/engines/admin/README.rdoc = Admin User management engine. <file_sep>/engines/video/app/states/video/stream_states.rb module Video class StreamStates < BaseAr::ArAccessor def self.states # Also related: # Messaging::States::VideoCapture::CaptureStates.states ["configuring", "configured", "ready", "capturing", "failed", "stopped"] end zextend BaseState, Video::StreamStates.states def initialize(stream) super(stream, :zstate) end end end <file_sep>/engines/video/app/connections/video/rasbari_client.rb module Video class RasbariClient < Messaging::Connections::GenericClient attr_accessor :hostname def initialize(hostname) @hostname = hostname exchangeName = "#{Messaging.config.video_capture.exchange}" responseRoutingKey = "#{Messaging.config.video_capture.routing_keys.rasbari.client}.#{Process.pid}" machineRoutingKey = "#{Messaging.config.video_capture.routing_keys.nimki.server}.#{hostname}" super(exchangeName, responseRoutingKey, machineRoutingKey) Rails.logger.info("Start RasbariClient for hostname: #{hostname}.#{Process.pid}") end # States def isStateReady? responseHeader, responseMessage = getState() status = responseHeader.isStatusSuccess? && responseMessage.getVideoCaptureState.isReady? return status, responseMessage.trace end def setStateReady responseHeader, responseMessage = setState(Messaging::States::VideoCapture::CaptureStates.ready) status = responseHeader.isStatusSuccess? && responseMessage.getVideoCaptureState.isReady? return status, responseMessage.trace end def isStateCapturing? responseHeader, responseMessage = getState() status = responseHeader.isStatusSuccess? && responseMessage.getVideoCaptureState.isCapturing? return status, responseMessage.trace end def setStateCapturing responseHeader, responseMessage = setState(Messaging::States::VideoCapture::CaptureStates.capturing) status = responseHeader.isStatusSuccess? && responseMessage.getVideoCaptureState.isCapturing? return status, responseMessage.trace end def isStateStopped? responseHeader, responseMessage = getState() status = responseHeader.isStatusSuccess? && responseMessage.getVideoCaptureState.isStopped? return status, responseMessage.trace end def setStateStopped responseHeader, responseMessage = setState(Messaging::States::VideoCapture::CaptureStates.stopped) status = responseHeader.isStatusSuccess? && responseMessage.getVideoCaptureState.isStopped? return status, responseMessage.trace end # Video details def sendCaptureDetails(captureDetailsMessage) header = Messaging::Messages::Header.dataRequest message = captureDetailsMessage responseHeader, responseMessage = call(header, message) status = responseHeader.isDataSuccess? return status, responseMessage.trace end # VNC server start def startVncServer header = Messaging::Messages::Header.statusRequest message = Messaging::Messages::VideoCapture::VncServerStart.new(nil) responseHeader, responseMessage = call(header, message) status = responseHeader.isStatusSuccess? return status, responseMessage.trace end private def getState # prepare packets and send message header = Messaging::Messages::Header.statusRequest message = Messaging::Messages::VideoCapture::StateQuery.new(nil) return call(header, message) end def setState(newState) # prepare packets and send message header = Messaging::Messages::Header.statusRequest message = Messaging::Messages::VideoCapture::StateTransition.new(nil) message.state = newState return call(header, message) end end end <file_sep>/lib/helpers/workflow_creator.rb require 'fileutils' require 'find' class WorkflowCreator attr_accessor :engineFolder, :engineName, :trackerName, :parentName def initialize(engineName, trackerName, parentName, stepNames) raise "Engine name should be in underscore" if engineName == engineName.camelize raise "Tracker model name should be in underscore" if trackerName == trackerName.camelize raise "Parent model name should be in underscore" if parentName == parentName.camelize @engineFolder = "engines/#{engineName}" @engineName = engineName @trackerName = trackerName @parentName = parentName @stepNames = [] stepNames.split(" ").each do |stepName| raise "Step name '#{stepName}' should be in underscore" if stepName == stepName.camelize @stepNames << stepName end @templateFolder = "lib/helpers/workflow" raise "Workflow template folder doesn't exist at #{@templateFolder}" if !Dir.exists?(@templateFolder) createTrackerController createWorkflowController createViews createWorkflows printTodo end # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # Create tracker controller def createTrackerController wf_file_in = "#{@templateFolder}/trackers_controller.rb" wf_file_out = "#{@engineFolder}/app/controllers/#{@engineName}/#{@trackerName.pluralize}_controller.rb" if !File.exists?(wf_file_in) raise "Sample tracker controller doesn't exists at #{wf_file_in}" end # copy file if File.exists?(wf_file_out) puts "Skipping tracker controller creation at #{wf_file_out}" else puts "Rewording tracker controller: #{wf_file_in}" text = File.read(wf_file_in) text = gsubCommon(text) File.open(wf_file_out, "w") { |file| file.puts text } end end # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # Create worfklow controller def createWorkflowController wf_file_in = "#{@templateFolder}/workflow_controller.rb" wf_file_out_folder = "#{@engineFolder}/app/controllers/#{@engineName}/#{@trackerName.pluralize}" wf_file_out = "#{wf_file_out_folder}/workflow_controller.rb" FileUtils.mkdir_p(wf_file_out_folder) if !File.exists?(wf_file_in) raise "Sample workflow controller doesn't exists at #{wf_file_in}" end # copy file if File.exists?(wf_file_out) puts "Skipping workflow controller creation at #{wf_file_out}" else puts "Rewording workflow controller: #{wf_file_in}" text = File.read(wf_file_in) text = gsubCommon(text) replaceStepsWith = "" @stepNames.each do |stepName| replaceStepsWith += getWorkflowControllerShowStep(stepName) end text = text.gsub("XXX_REPLACE_SHOW_STEPS_XXX", "#{replaceStepsWith}") replaceStepsWith = "" @stepNames.each do |stepName| replaceStepsWith += getWorkflowControllerUpdateStep(stepName) end text = text.gsub("XXX_REPLACE_UPDATE_STEPS_XXX", "#{replaceStepsWith}") replaceStepsWith = "" @stepNames.each do |stepName| replaceStepsWith += ":#{stepName}, " end replaceStepsWith = replaceStepsWith[0..-3] text = text.gsub("XXX_REPLACE_SET_STEPS_XXX", "#{replaceStepsWith}") File.open(wf_file_out, "w") { |file| file.puts text } end end def getWorkflowControllerShowStep(stepName) return """ when :#{stepName} @workflowObj = #{@engineName.camelize}::#{@trackerName.camelize}Workflow::#{stepName.camelize}.new(@#{@trackerName}) @workflowObj.canSkip ? skip_step : @workflowObj.serve""" end def getWorkflowControllerUpdateStep(stepName) return """ when :#{stepName} status, message = #{@engineName.camelize}::#{@trackerName.camelize}Workflow::#{stepName.camelize}.new(@#{@trackerName}).handle(params)""" end # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # Create views def createViews wf_views_folder_in = "#{@templateFolder}/views" wf_views_folder_out = "#{@engineFolder}/app/views/#{@engineName}/#{@trackerName.pluralize}/workflow" FileUtils.mkdir_p(wf_views_folder_out) if !Dir.exists?(wf_views_folder_in) raise "Sample view folder doesn't exists at #{wf_views_folder_in}" end # copy common buttons file wf_file_in = "#{wf_views_folder_in}/_common_buttons.html.erb" wf_file_out = "#{wf_views_folder_out}/_common_buttons.html.erb" if File.exists?(wf_file_out) puts "Skipping view common bottons creation at #{wf_file_out}" else puts "Rewording view common bottons: #{wf_file_in}" text = File.read(wf_file_in) text = gsubCommon(text) File.open(wf_file_out, "w") { |file| file.puts text } end # copy outershell file wf_file_in = "#{wf_views_folder_in}/_outershell.html.erb" wf_file_out = "#{wf_views_folder_out}/_outershell.html.erb" if File.exists?(wf_file_out) puts "Skipping view outershell creation at #{wf_file_out}" else puts "Rewording view outershell: #{wf_file_in}" text = File.read(wf_file_in) text = gsubCommon(text) File.open(wf_file_out, "w") { |file| file.puts text } end # copy steps wf_file_in = "#{wf_views_folder_in}/step.html.erb" @stepNames.each do |stepName| wf_file_out = "#{wf_views_folder_out}/#{stepName}.html.erb" if File.exists?(wf_file_out) puts "Skipping view step creation at #{wf_file_out}" else puts "Rewording view outershell: #{wf_file_in}" text = File.read(wf_file_in) text = gsubCommon(text) title = stepName.split("_").map{ |s| s.capitalize }.join(" ") text = text.gsub("XXX_REPLACE_STEP_TITLE_XXX", "#{title}") File.open(wf_file_out, "w") { |file| file.puts text } end end # done with all views end # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # Create worfklows def createWorkflows wf_file_in = "#{@templateFolder}/workflow_step.rb" wf_steps_folder_out = "#{@engineFolder}/workflows/#{@engineName}/#{@trackerName}_workflow" FileUtils.mkdir_p(wf_steps_folder_out) if !File.exists?(wf_file_in) raise "Sample workflow step doesn't exists at #{wf_file_in}" end # copy steps @stepNames.each do |stepName| wf_file_out = "#{wf_steps_folder_out}/#{stepName}.rb" if File.exists?(wf_file_out) puts "Skipping workflow step creation at #{wf_file_out}" else puts "Rewording workflow step: #{wf_file_in}" text = File.read(wf_file_in) text = gsubCommon(text) text = text.gsub("XXX_REPLACE_STEP_CLASS_XXX", "#{stepName.camelize}") File.open(wf_file_out, "w") { |file| file.puts text } end end # done with all steps end # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- def printTodo puts "" puts "Following files need to be manually updated:" puts "" puts "#{@engineFolder}/config/routes.rb" puts "" puts "Look for intructions at:" puts "#{@templateFolder}/instructions.txt" end # ---------------------------------------------------------------------------- def gsubCommon(_text) text = _text.gsub("sample_engine", "#{@engineName}") text = text.gsub("SampleEngine", "#{@engineName.camelize}") text = text.gsub("tracker", "#{@trackerName}") text = text.gsub("Tracker", "#{@trackerName.camelize}") text = text.gsub("parent", "#{@parentName}") text = text.gsub("Parent", "#{@parentName.camelize}") text end end <file_sep>/engines/video/app/workflows/video/capture_workflow/start_capture.rb module Video module CaptureWorkflow class StartCapture def initialize(capture) @capture = capture end def canSkip @capture.stream.state.isAtOrAfterCapturing? end def serve true end def handle(params) status, trace = @capture.captureClient.setStateCapturing if status @capture.stream.state.setCapturing @capture.update(started_by: params[:current_user_id]) @capture.update(started_at: Time.now) @capture.captureMachine.state.setWorking else @capture.stream.state.setFailed end return status, trace end end end end <file_sep>/engines/video/README.rdoc = Video Engine to manage media streams. <file_sep>/lib/helpers/workflow/workflow_step.rb module SampleEngine module TrackerWorkflow class XXX_REPLACE_STEP_CLASS_XXX def initialize(tracker) @tracker = tracker end def canSkip false end def serve true end def handle(params) status = false message = "Couldn't handle step" # TODO: change return status, message end end end end <file_sep>/engines/setting/app/states/setting/cloud_types.rb module Setting class CloudTypes < BaseAr::ArAccessor def self.types ["local", "softLayer", "amazon", "microsoft"] end zextend BaseType, Setting::CloudTypes.types def initialize(machine) super(machine, :zcloud) end end end <file_sep>/engines/video/app/workflows/video/capture_workflow/set_remote_ready.rb module Video module CaptureWorkflow class SetRemoteReady def initialize(capture) @capture = capture end def canSkip @capture.stream.state.isAtOrAfterReady? end def serve true end def handle(params) status, trace = @capture.captureClient.setStateReady if status status, trace = @capture.captureClient.startVncServer if status @capture.stream.state.setReady trace = "Started all remote capture processes including VNC server" end end return status, trace end end end end <file_sep>/engines/video/db/migrate/20160105174226_create_video_captures.rb class CreateVideoCaptures < ActiveRecord::Migration def change create_table :video_captures do |t| t.integer :stream_id t.integer :storage_machine_id t.integer :capture_machine_id t.string :capture_url t.text :comment t.integer :width t.integer :height t.float :playback_frame_rate t.integer :started_by t.integer :stopped_by t.datetime :started_at t.datetime :stopped_at t.timestamps null: false end add_index :video_captures, :stream_id add_index :video_captures, :storage_machine_id add_index :video_captures, :capture_machine_id end end <file_sep>/engines/video/app/workflows/video/capture_workflow/ping_nimki.rb module Video module CaptureWorkflow class PingNimki def initialize(capture) @capture = capture end def canSkip @capture.stream.state.isAtOrAfterReady? end def serve true end def handle(params) status, trace = @capture.captureClient.isRemoteAlive? if status # set remote capture details status, trace = @capture.captureClient.sendCaptureDetails(@capture.toMessage) trace = "Capture remote is alive but couldn't set capture details" if !status end return status, trace end end end end <file_sep>/README.rdoc == README Wiki page: TODO: Put URL <file_sep>/app/states/base_ar.rb # Note: This relies in monkeypatching of module in # config/initializers/monkeypatch.rb module BaseAr # this is inherited from implementing classes class ArAccessor def initialize(tableObject, columnName) # attributeArr is defined by module monkeypatch @tableObject = tableObject @columnName = columnName end # methods for sub classes def getX @tableObject.send(@columnName) end def setX(setValue) @tableObject.update({@columnName => setValue}) end # get humanized version of current role def to_s getX().split(/(?=[A-Z])/).map{ |w| w.capitalize }.join(" ") end # see if it is valid def valid?(r) attributeArr.include?(r) end end end <file_sep>/Gemfile source 'https://rubygems.org' # ------------------------------------------------------------------------------ # ZIGVU BEGIN: Original gems from rails new # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.2.5' # Use mysql as the database for Active Record gem 'mysql2', '>= 0.3.13', '< 0.5' # Use SCSS for stylesheets gem 'sass-rails', '~> 5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~> 4.1.0' # See https://github.com/rails/execjs#readme for more supported runtimes # EVAN: not needed since we use node.js with lower memory footprint - so don't uncomment # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks gem 'turbolinks' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.0' # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', '~> 0.4.0', group: :doc # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' # Use Unicorn as the app server # gem 'unicorn' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug' end group :development do # Access an IRB console on exception pages or by using <%= console %> in views gem 'web-console', '~> 2.0' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring #gem 'spring' end # ZIGVU END: Original gems from rails new # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ZIGVU BEGIN: Additional gems # scaffold and view helpers # NOT USING: gem 'bootstrap-glyphicons' # although using foundation, use icons from bootstrap gem 'foundation-rails' # CSS library gem 'foundation-icons-sass-rails' # icons from foundation # NOT USING: gem 'foundation_rails_helper' # formatting for alerts etc. gem 'gretel' # for breadrums # NOT USING: gem 'fancybox2-rails', '~> 0.2.8' # pop-up image in fancy box gem 'simple_form' # simple form with foundations configuration gem 'draper', '~> 1.3' # decorator # authentication and roles gem 'devise' # for authentication gem 'simple_token_authentication' # for API authentication using devise gem 'authority' # for authorization # NOT USING: gem 'rolify' # for role management # analytics gem 'd3-rails' # main JS charting library gem 'crossfilter-rails' # JS data filter library # misc. gem 'high_voltage', '~> 2.4.0' # serve static pages for test gem 'quiet_assets', group: :development # quits the asset prints in console # NOT USING: gem 'parallel' # multi-threading # delayed_job # NOT USING: gem 'delayed_job_active_record' # background jobs # NOT USING: gem 'delayed_job_web' # view background job status gem 'daemons', '~> 1.2.3' # run daemon processes # memcached gem 'dalli' # gem for memcached # NOT USING: Now part of rails: gem 'cache_digests' # to expire view partials gem 'kgio', '~> 2.10.0' # makes dalli 20-30% faster as per dalli github page gem 'connection_pool' # enable dalli to share pooled connections # document store gem 'mongoid', '~> 5.0.0' # driver for mongo # serving gem 'puma' # kheer specific - not in cellroti gem 'bunny' # for rabbitmq gem 'wicked' # campaign gem 'her' # Use Cellroti API as model objects # javascript libraries gem 'underscore-rails' # JS helper library gem 'jquery-ui-rails', '~> 5.0.2' # JS UI assets gem 'jquery-turbolinks' # have turbolinks play nice with JS # ZIGVU END: Additional gems # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ZIGVU BEGIN: Internal engines gem 'messaging', path: 'engines/messaging' gem 'setting', path: 'engines/setting' gem 'admin', path: 'engines/admin' gem 'video', path: 'engines/video' # ZIGVU END: Internal engines # ------------------------------------------------------------------------------ <file_sep>/engines/messaging/README.md = Messaging Gem to communicate with RabbitMq. <file_sep>/engines/video/app/workflows/video/capture_workflow/stop_capture.rb module Video module CaptureWorkflow class StopCapture def initialize(capture) @capture = capture end def canSkip false end def serve true end def handle(params) # Note, unless exception, this will always succeed # if a capture machine has been set, need to release it gracefully if @capture.captureMachine # if we have started a capture client if @capture.captureClient # if we can ping then we can try to stop normally status, trace = @capture.captureClient.isRemoteAlive? if status @capture.captureClient.setStateStopped end # status end # captureClient @capture.captureMachine.state.setReady end # captureMachine @capture.stream.state.setStopped @capture.update(stopped_by: params[:current_user_id]) @capture.update(stopped_at: Time.now) status = true trace = "Capture stopped" return status, trace end end end end <file_sep>/engines/video/test/video_test.rb require 'test_helper' class VideoTest < ActiveSupport::TestCase test "truth" do assert_kind_of Module, Video end end <file_sep>/engines/admin/app/states/admin/user_roles.rb module Admin class UserRoles < BaseAr::ArAccessor def self.roles ["guest", "trainee", "analyst", "manager", "admin", "superAdmin"] end zextend BaseRole, Admin::UserRoles.roles def initialize(user) super(user, :zrole) end end end <file_sep>/engines/setting/app/states/setting/machine_types.rb module Setting class MachineTypes < BaseAr::ArAccessor def self.types ["local", "capture", "storage", "gpu"] end zextend BaseType, Setting::MachineTypes.types def initialize(machine) super(machine, :ztype) end end end <file_sep>/engines/video/db/migrate/20151217210040_create_video_streams.rb class CreateVideoStreams < ActiveRecord::Migration def change create_table :video_streams do |t| t.string :ztype t.string :zstate t.string :zpriority t.string :name t.string :base_url t.string :capture_url t.timestamps null: false end end end <file_sep>/engines/messaging/lib/messaging/messages/header.rb # # needed for load order require_relative "header_types" require_relative "header_states" module Messaging module Messages class Header attr_accessor :type, :state def initialize(jsonHeader) @type = Messaging::Messages::HeaderTypes.new(jsonHeader['type']) @state = Messaging::Messages::HeaderStates.new(jsonHeader['state']) end def to_json { type: @type.to_s, state: @state.to_s } end def to_s to_json.to_s end # define class methods eigenclass.instance_eval do Messaging::Messages::HeaderTypes.types.each do |t| Messaging::Messages::HeaderStates.states.each do |s| # self.pingSuccess define_method("#{t}#{s.capitalize}") do return Messaging::Messages::Header.new({ 'type' => t, 'state' => s }) end end end end # define instance methods Messaging::Messages::HeaderTypes.types.each do |t| Messaging::Messages::HeaderStates.states.each do |s| # self.isPingSuccess? define_method("is#{t.capitalize}#{s.capitalize}?") do return ("#{@type}" == "#{t}") && ("#{@state}" == "#{s}") end end end end end end <file_sep>/engines/setting/app/states/setting/machine_states.rb module Setting class MachineStates < BaseAr::ArAccessor def self.states ["unknown", "provisioning", "ready", "contracted", "working"] end zextend BaseState, Setting::MachineStates.states def initialize(machine) super(machine, :zstate) end end end <file_sep>/engines/messaging/lib/messaging/states/video_capture/capture_states.rb # Note: This relies in monkeypatching of module in # config/initializers/monkeypatch.rb (for Rails) # messaging/monkeypatch.rb (for non-Rails) module Messaging module States module VideoCapture class CaptureStates def self.states ["unknown", "ready", "capturing", "stopped"] end zextend BaseNonPersisted, Messaging::States::VideoCapture::CaptureStates.states, { prefix: 'state' } attr_reader :state def initialize(s) @state = s end end end end end <file_sep>/engines/video/app/decorators/video/capture_decorator.rb module Video class CaptureDecorator < Draper::Decorator delegate_all def canDelete? object.clips.count == 0 end def hasEnded? object.stopped_at != nil end def hasError? lastClip = object.clips.last # if the stream has not ended and no clip has been created in last 10 minutes if !hasEnded? && lastClip return ((Time.now - lastClip.created_at)/60 > 10) end false end end end <file_sep>/engines/sample_engine/README.rdoc = SampleEngine TODO: Write. <file_sep>/engines/video/app/models/video/clip.rb module Video class Clip < ActiveRecord::Base def state Video::ClipStates.new(self) end # TODO: move to storage path generator def path "#{self.capture.stream.id}/#{self.capture.id}/#{self.id}" end def clipPath "/data/#{self.capture.storageMachine.hostname}/#{self.path}/#{self.id}.mkv" end def thumbnailPath "/data/#{self.capture.storageMachine.hostname}/#{self.path}/#{self.id}.jpg" end belongs_to :capture end end <file_sep>/engines/video/app/handlers/video/main_handler.rb module Video class MainHandler def initialize end def call(header, message) Rails.logger.debug("Video::MainHandler: Request header : #{header}") Rails.logger.debug("Video::MainHandler: Request message: #{message}") returnHeader = Messaging::Messages::Header.statusFailure returnMessage = Messaging::Messages::MessageFactory.getNoneMessage returnMessage.trace = "Message handler not found" begin pingHandler = Video::PingHandler.new(header, message) returnHeader, returnMessage = pingHandler.handle if pingHandler.canHandle? clipDetailsHandler = Video::ClipDetailsHandler.new(header, message) returnHeader, returnMessage = clipDetailsHandler.handle if clipDetailsHandler.canHandle? rescue Exception => e returnHeader = Messaging::Messages::Header.statusFailure returnMessage.trace = "Error: #{e.backtrace.first}" Rails.logger.error(e) end Rails.logger.debug("Video::MainHandler: Served header : #{returnHeader}") Rails.logger.debug("Video::MainHandler: Served message: #{returnMessage}") return returnHeader, returnMessage end end end <file_sep>/engines/setting/config/routes.rb Setting::Engine.routes.draw do resources :machines root to: "machines#index" end <file_sep>/engines/messaging/lib/messaging/messages/header_types.rb # Note: This relies in monkeypatching of module in # config/initializers/monkeypatch.rb (for Rails) # messaging/monkeypatch.rb (for non-Rails) module Messaging module Messages class HeaderTypes # Note on types: # ping : to check if remote is alive # status: to get and set remote status/state # data : to get and supply data attributes def self.types ["ping", "status", "data"] end zextend BaseNonPersisted, Messaging::Messages::HeaderTypes.types, { prefix: 'type' } attr_reader :type def initialize(t) @type = t end end end end <file_sep>/engines/video/app/workflows/video/capture_workflow/set_machines.rb module Video module CaptureWorkflow class SetMachines attr_reader :storageMachines, :captureMachines def initialize(capture) @capture = capture end def canSkip @capture.stream.state.isAfterConfiguring? end def serve @storageMachines = Setting::Machine .where(ztype: Setting::MachineTypes.storage) .where(zstate: Setting::MachineStates.ready) .pluck(:hostname, :id) @captureMachines = Setting::Machine .where(ztype: Setting::MachineTypes.capture) .where(zstate: Setting::MachineStates.ready) .pluck(:hostname, :id) end def handle(params) # prevent race condition when another user already assigned machine to another stream captureMachine = Setting::Machine.find(params[:capture_machine_id]) status, trace = captureMachine.state.isReady? if status @capture.update(params) captureMachine.state.setContracted @capture.stream.state.setConfigured trace = "Saved machine states" end return status, trace end end end end <file_sep>/engines/messaging/lib/messaging/messages/video_capture/clip_details.rb module Messaging module Messages module VideoCapture class ClipDetails < BaseMessage::Common ATTR = ["captureId", "ffmpegName", "clipId", "storageClipPath", "storageThumbnailPath"] zextend BaseMessage, ATTR def initialize(message = nil) super(_category, _name, message) end private def _category __FILE__.split("/")[-2] end def _name File.basename(__FILE__, ".*") end # end private end end end end <file_sep>/engines/video/app/connections/video/rasbari_server.rb module Video class RasbariServer < Messaging::Connections::GenericServer def initialize(handler) exchangeName = "#{Messaging.config.video_capture.exchange}" listenRoutingKey = "#{Messaging.config.video_capture.routing_keys.rasbari.server}" super(exchangeName, listenRoutingKey, handler) Rails.logger.info("Start Video RasbariServer") end end end <file_sep>/engines/messaging/lib/messaging/messages/base_message.rb # Note: This relies in monkeypatching of module in # config/initializers/monkeypatch.rb module BaseMessage def self.zextended(base, arr, options = nil) # include general class and instance methods base.extend ClassMethods base.send :include, InstanceMethods # expand attr array arr += ["category", "name", "trace"] # change array elements into methods arr.each do |ss| # base.send(:attr_accessor, ss) base.send(:attr_reader, ss) base.send(:define_method, "#{ss}=") do |arg| self.instance_variable_set("@#{ss}", arg.to_s) end end base.send(:define_method, "attributes") do arr end end module ClassMethods # relevant class methods end module InstanceMethods # activated instance methods end class Common def initialize(category, name, message) attributes.each do |a| instance_variable_set("@#{a}", nil) end @category = category @name = name if message != nil message.each do |k, v| if(instance_variable_defined?("@#{k}")) instance_variable_set("@#{k}", v) # else # Messaging.logger.warn("Instance variable @#{k} not set") end end end end def isSameType?(anoMes) anoMes.category == @category && anoMes.name == @name end def to_hash retJson = {} attributes.each do |a| retJson[a] = "#{self.send(a)}" end retJson end def to_json to_hash.to_json end def to_s to_json.to_s end end end <file_sep>/engines/messaging/lib/messaging/base_libs/deep_symbolize.rb module Messaging module BaseLibs # Convert nested hash into ordered_options class DeepSymbolize def self.convert(h) self.deepSymbolize(h, Messaging::BaseLibs::OrderedOptions.new) end def self.deepSymbolize(h, newH) h.each do |k, v| if v.is_a?(Hash) newV = self.deepSymbolize(v, Messaging::BaseLibs::OrderedOptions.new) else newV = v end newH.merge!({k => newV}.symbolize_keys) end newH end end end end <file_sep>/engines/messaging/lib/messaging/messages/base_non_persisted.rb # Note: This relies in monkeypatching of module in # config/initializers/monkeypatch.rb module BaseNonPersisted def self.zextended(base, arr, options) # include general class and instance methods base.extend ClassMethods base.send :include, InstanceMethods # get prefix from options prefix = options[:prefix] # change array elements into methods arr.each do |ss| methodName = ss.slice(0,1).capitalize + ss.slice(1..-1) # query method: Example: isState? base.send(:define_method, "is#{methodName}?") do ss.to_s == self.send(prefix) end end # get string repr base.send(:define_method, "to_s") do self.send(prefix) end # equality base.send(:define_method, "==") do |another| self.send(prefix) == another.send(prefix) end # formatted hash for form input base.send(:define_method, "to_h") do arr.map{ |a| [a.split(/(?=[A-Z])/).map{ |w| w.capitalize }.join(" "), a] } end # create class methods base.eigenclass.instance_eval do arr.each do |ss| define_method("#{ss}") do return base.new(ss) end end end end module ClassMethods # relevant class methods end module InstanceMethods # activated instance methods end end <file_sep>/engines/messaging/lib/messaging/base_libs/mlogger.rb module Messaging module BaseLibs class Mlogger < Logger class Mformatter < Logger::Formatter def call(severity, time, progname, msg) Format % [severity[0..0], format_datetime(time), $$, colorizeSev(severity), progname, msgWithFilename(msg)] end def msgWithFilename(msg) "#{File.basename(caller[4].split(":")[0])}: #{msg2str(msg)}" end def colorizeSev(severity) case severity when 'DEBUG' colorize(severity, "gray") when 'INFO' colorize(severity, "yellow") when 'WARN' colorize(severity, "magenta") when 'ERROR' colorize(severity, "red") when 'UNKNOWN' colorize(severity, "red", {style: "bold"}) end end def colorize(text, color, options = {}) background = options[:background] || options[:bg] || false style = options[:style] offsets = ["gray","red", "green", "yellow", "blue", "magenta", "cyan","white"] styles = ["normal","bold","dark","italic","underline","xx","xx","underline","xx","strikethrough"] start = background ? 40 : 30 color_code = start + (offsets.index(color) || 8) style_code = styles.index(style) || 0 "\e[#{style_code};#{color_code}m#{text}\e[0m" end def format_datetime(time) "#{time.strftime('%Y-%m-%d %H:%M:%S')}" end end def initialize super(STDOUT) self.formatter = Messaging::BaseLibs::Mlogger::Mformatter.new self.level = Logger::DEBUG end end end end <file_sep>/app/states/base_role.rb # Note: This relies in monkeypatching of module in # config/initializers/monkeypatch.rb module BaseRole def self.zextended(base, arr, options = {}) # include general class and instance methods base.extend ClassMethods base.send :include, InstanceMethods # change array elements into methods arr.each do |ss| methodName = ss.slice(0,1).capitalize + ss.slice(1..-1) # query method: Example: isDownloadQueue? base.send(:define_method, "is#{methodName}?") do ss.to_s == getX() end # setter method: Example setDownloadQueue base.send(:define_method, "set#{methodName}") do setX(ss) end # heirarchy base.send(:define_method, "isAtLeast#{methodName}?") do arr.index(getX()) >= arr.index(ss) end base.send(:define_method, "isBelow#{methodName}?") do arr.index(getX()) < arr.index(ss) end end # get current base.send(:define_method, "get") do getX() end # make array accessible to instance methods base.send(:define_method, "attributeArr") do arr end # create class methods base.eigenclass.instance_eval do # individual element as method arr.each do |ss| define_method("#{ss}") do ss.to_s end end # formatted hash for form input define_method("to_h") do arr.map{ |a| [a.split(/(?=[A-Z])/).map{ |w| w.capitalize }.join(" "), a] } end end end module ClassMethods # relevant class methods end module InstanceMethods # activated instance methods end end <file_sep>/engines/video/app/states/video/stream_types.rb module Video class StreamTypes < BaseAr::ArAccessor def self.types ["youtube", "webBroadcast", "tvBroadcast", "oneOff", "other"] end zextend BaseType, Video::StreamTypes.types def initialize(stream) super(stream, :ztype) end end end <file_sep>/lib/helpers/workflow/workflow_controller.rb require_dependency "sample_engine/application_controller" module SampleEngine class Trackers::WorkflowController < ApplicationController include Wicked::Wizard before_action :set_steps before_action :setup_wizard before_action :set_steps_ll, only: [:show, :update] def show case step XXX_REPLACE_SHOW_STEPS_XXX end render_wizard end def update status = false trace = "Could not complete step - unknown workflow step" case step XXX_REPLACE_UPDATE_STEPS_XXX end # next step based on current step result if status if step == steps.last redirect_to parent_path(@parent) else render_wizard @capture end else # re-render the current step flash.now[:alert] = trace render_wizard end end private # Use callbacks to share common setup or constraints between actions. def set_steps @tracker = Tracker.find(params[:tracker_id]) @parent = @tracker.parent self.steps = [XXX_REPLACE_SET_STEPS_XXX] end def set_steps_ll @current_step = step @prev_step = steps.index(step) == 0 ? nil : steps[steps.index(step) - 1] @next_step = steps.index(step) == (steps.count - 1) ? nil : steps[steps.index(step) + 1] end end end <file_sep>/engines/video/db/migrate/20160102035551_remove_capture_url_from_video_stream.rb class RemoveCaptureUrlFromVideoStream < ActiveRecord::Migration def change remove_column :video_streams, :capture_url, :string end end <file_sep>/engines/messaging/lib/messaging.rb require "logger" require "messaging/version" # # extra files needed for load order require "messaging/messages/base_non_persisted" # load files based on whether it is loaded as Rails engine or not if Module.const_defined?('Rails') require "messaging/engine" else require "messaging/non_rails/monkeypatch" end module Messaging def self.files_to_load lib = File::expand_path('..', __FILE__) templateFolders = ["#{lib}/messaging/non_rails"] nonTemplateFolders = Dir["#{lib}/messaging/*"] - templateFolders nonTemplateFiles = [] nonTemplateFolders.each do |ntf| # assume that all files are namespaced Dir["#{ntf}/**/*.rb"].each do |f| nonTemplateFiles << File.join(File.dirname(f), File.basename(f, ".*")) end end nonTemplateFiles end mattr_accessor :_logger def self.logger Messaging._logger ||= begin if Module.const_defined?('Rails') Rails.logger else Messaging::BaseLibs::Mlogger.new end end end # Memoize config mattr_accessor :_config def self.config Messaging._config ||= begin yamlConfigFile = File::expand_path('../messaging/config/rabbit.yml', __FILE__) Messaging._config = Messaging::Config::Reader.new(yamlConfigFile).config end end # Memoize connection objects mattr_accessor :_rasbari_cache def self.rasbari_cache Messaging._rasbari_cache ||= begin raise "Cannot initilize rasbari cache in non rails environment" if !Module.const_defined?('Rails') Messaging._rasbari_cache = Messaging::Connections::RasbariCache.new end end # If using in rails context: DO NOT call this directly # instead use the global thread safe # $bunny_connection variable we get from # main_app/config/puma.rb def self.connection # currently assume default URL Messaging::Connections::BunnyConnection.new(nil).connection end end # load files if not used as engine if !Module.const_defined?('Rails') Messaging.files_to_load.each { |file| require_relative file } end <file_sep>/engines/messaging/lib/messaging/messages/storage/file_operations.rb module Messaging module Messages module Storage class FileOperations < BaseMessage::Common ATTR = ["hostname", "type", "clientFilePath", "serverFilePath"] zextend BaseMessage, ATTR def initialize(message = nil) super(_category, _name, message) end def getFileOperationType Messaging::States::Storage::FileOperationTypes.new(@type) end private def _category __FILE__.split("/")[-2] end def _name File.basename(__FILE__, ".*") end # end private end end end end <file_sep>/engines/admin/lib/admin/engine.rb module Admin class Engine < ::Rails::Engine isolate_namespace Admin # Append routes before initialization initializer "admin", before: :load_config_initializers do |app| Rails.application.routes.append do mount Admin::Engine, at: "/admin" end end # Load files after initialization initializer "admin", after: :load_config_initializers do |app| Admin.files_to_load.each { |file| require_relative file } end # Change default generator to generate less files config.generators do |g| g.orm :active_record g.template_engine :erb g.test_framework :test_unit, fixture: false g.helper false g.assets false g.view_specs false g.jbuilder false g.templates.unshift File::expand_path('../../templates', __FILE__) end end end <file_sep>/engines/messaging/lib/messaging/connections/bunny_connection.rb require 'bunny' module Messaging module Connections class BunnyConnection attr_reader :connection def initialize(amqp_url) if amqp_url.nil? @connection = Bunny.new else @connection = Bunny.new(amqp_url) end @connection.start at_exit { @connection.close } end end end end <file_sep>/engines/messaging/lib/messaging/connections/rpc_client.rb # Note: Headers and mesages are exchanged as JSON data but are converted to # corresponding objects during API call to this file module Messaging module Connections class RpcClient attr_accessor :responseMessage, :responseHeader, :correlationId attr_reader :lock, :condition def initialize(connection, exchangeName, responseRoutingKey) channel = connection.create_channel @exchange = channel.topic(exchangeName, durable: true) @responseRoutingKey = responseRoutingKey # temporary exclusive queue for client to accept messages replyQueue = channel.queue("", exclusive: true, auto_delete: true) replyQueue.bind(@exchange, routing_key: @responseRoutingKey) # for blocking mechanism @lock = Mutex.new @condition = ConditionVariable.new that = self # in a separate thread listen for reply messages replyQueue.subscribe(manual_ack: true) do |delivery_info, properties, payload| if properties[:correlation_id] == that.correlationId that.responseMessage = Messaging::Messages::MessageFactory.getMessage(payload) that.responseHeader = Messaging::Messages::Header.new(properties.headers) channel.ack(delivery_info.delivery_tag) that.lock.synchronize{ that.condition.signal } end end end def call(publishRoutingKey, header, message, timeout = nil) # if we are expecting that request could time out, we need to # set responses to nil from previous calls if timeout self.responseHeader = Messaging::Messages::Header.pingFailure self.responseMessage = Messaging::Messages::MessageFactory.getNoneMessage self.responseMessage.trace = "Ping failure - timed out" end self.correlationId = SecureRandom.uuid # send message @exchange.publish( message.to_json, routing_key: publishRoutingKey, correlation_id: self.correlationId, reply_to: @responseRoutingKey, headers: header.to_json ) # wait for reply if timeout lock.synchronize{ condition.wait(lock, timeout) } else lock.synchronize{ condition.wait(lock) } end # return reply return responseHeader, responseMessage end end end end <file_sep>/engines/video/config/routes.rb Video::Engine.routes.draw do resources :captures, only: [:new, :show, :destroy] do resources :workflow, only: [:show, :update], controller: 'captures/workflow' member do get 'start_vnc' get 'force_stop' end end resources :streams root to: "streams#index" end <file_sep>/engines/messaging/lib/messaging/non_rails/monkeypatch.rb # Author: Evan # Here be dragons! Tread carefully # This should only be loaded when in non-rails context. # For rails context, we use different monkeypatch file: # config/initializers/monkeypatch.rb if Module.const_defined?('Rails') raise "Messaging monkeypatch cannot be loaded in Rails context!" end # Copy rails hash methods # https://github.com/rails/rails/blob/4-2-stable/activesupport/lib/active_support/core_ext/hash/keys.rb class Hash # Returns a new hash with all keys converted using the block operation. # # hash = { name: 'Rob', age: '28' } # # hash.transform_keys{ |key| key.to_s.upcase } # # => {"NAME"=>"Rob", "AGE"=>"28"} def transform_keys return enum_for(:transform_keys) unless block_given? result = self.class.new each_key do |key| result[yield(key)] = self[key] end result end # Returns a new hash with all keys converted to symbols, as long as # they respond to +to_sym+. # # hash = { 'name' => 'Rob', 'age' => '28' } # # hash.symbolize_keys # # => {:name=>"Rob", :age=>"28"} def symbolize_keys transform_keys{ |key| key.to_sym rescue key } end alias_method :to_options, :symbolize_keys # Destructively convert all keys to symbols, as long as they respond # to +to_sym+. Same as +symbolize_keys+, but modifies +self+. def symbolize_keys! transform_keys!{ |key| key.to_sym rescue key } end alias_method :to_options!, :symbolize_keys! end # Copy rails array option extractor # https://github.com/rails/rails/blob/4-2-stable/activesupport/lib/active_support/core_ext/array/extract_options.rb class Array # Extracts options from a set of arguments. Removes and returns the last # element in the array if it's a hash, otherwise returns a blank hash. # # def options(*args) # args.extract_options! # end # # options(1, 2) # => {} # options(1, 2, a: :b) # => {:a=>:b} def extract_options! if last.is_a?(Hash) && last.extractable_options? pop else {} end end end class Object # Monkeypatch object to generate class methods def eigenclass class << self; self; end end end class Module # Monkeypatch module to allow `extend` with more capability def zextend(mod, *args) returnMod = include(mod) mod.zextended(self, *args) if mod.respond_to?(:zextended) returnMod end # Copy rails mattr # https://github.com/rails/rails/blob/4-2-stable/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb def mattr_reader(*syms) syms.each do |sym| next if sym.is_a?(Hash) class_eval(<<-EOS, __FILE__, __LINE__) unless defined? @@#{sym} @@#{sym} = nil end def self.#{sym} @@#{sym} end def #{sym} @@#{sym} end EOS end end def mattr_writer(*syms) options = syms.extract_options! syms.each do |sym| class_eval(<<-EOS, __FILE__, __LINE__) unless defined? @@#{sym} @@#{sym} = nil end def self.#{sym}=(obj) @@#{sym} = obj end #{" def #{sym}=(obj) @@#{sym} = obj end " unless options[:instance_writer] == false } EOS end end def mattr_accessor(*syms) mattr_reader(*syms) mattr_writer(*syms) end end <file_sep>/engines/sample_engine/test/sample_engine_test.rb require 'test_helper' class SampleEngineTest < ActiveSupport::TestCase test "truth" do assert_kind_of Module, SampleEngine end end <file_sep>/engines/messaging/lib/messaging/base_libs/ordered_options.rb module Messaging module BaseLibs # Copy rails OrderedOptions # https://github.com/rails/rails/blob/4-2-stable/activesupport/lib/active_support/ordered_options.rb class OrderedOptions < Hash alias_method :_get, :[] # preserve the original #[] method protected :_get # make it protected def []=(key, value) super(key.to_sym, value) end def [](key) super(key.to_sym) end def method_missing(name, *args) name_string = name.to_s if name_string.chomp!('=') self[name_string] = args.first else self[name] end end def respond_to_missing?(name, include_private) true end end end end <file_sep>/lib/helpers/engine_creator.rb require 'fileutils' require 'find' class EngineCreator attr_accessor :engineFileName, :engineName def initialize(name) raise "Name should be in underscore" if name == name.camelize @engineFileName = name @engineName = name.classify setSampleEngine createEngine printTodo end def setSampleEngine @sampleEngineFileName = "sample_engine" @sampleEngineName = "SampleEngine" @sampleEngineLocation = "engines/#{@sampleEngineFileName}" raise "Sample engine doesn't exists at #{@sampleEngineLocation}" if !Dir.exists?(@sampleEngineLocation) end def createEngine copyEngine changeFiles end def copyEngine @engineLocation = "engines/#{@engineFileName}" raise "Engine already exists at #{@engineLocation}" if Dir.exists?(@engineLocation) FileUtils.cp_r(@sampleEngineLocation, @engineLocation) end def changeFiles # if directory needs renaming allFiles = Find.find("engines/#{@engineFileName}").map{ |f| f } allFiles.each do |f| if File.directory?(f) && f.include?("#{@sampleEngineFileName}") puts "Renaming directory: #{f}" newF = f.gsub("#{@sampleEngineFileName}", "#{@engineFileName}") FileUtils.mv(f, newF) end end # if file needs renaming allFiles = Find.find("engines/#{@engineFileName}").map{ |f| f } allFiles.each do |f| if !File.directory?(f) && File.basename(f).include?("#{@sampleEngineFileName}") puts "Renaming file: #{f}" newF = f.gsub("#{@sampleEngineFileName}", "#{@engineFileName}") FileUtils.mv(f, newF) end end # grep through all files changing occurence allFiles = Find.find("engines/#{@engineFileName}").map{ |f| f } allFiles.each do |f| if !File.directory?(f) text = File.read(f) if text.include?("#{@sampleEngineFileName}") || text.include?("#{@sampleEngineName}") puts "Rewording file: #{f}" text = text.gsub("#{@sampleEngineFileName}", "#{@engineFileName}") text = text.gsub("#{@sampleEngineName}", "#{@engineName}") File.open(f, "w") { |file| file.puts text } end end end end def printTodo puts "" puts "Following files need to be manually updated:" puts "" allFiles = Find.find("engines/#{@engineFileName}").map{ |f| f } allFiles.each do |f| if !File.directory?(f) text = File.read(f) if text.include?("TODO") puts f end end end puts "" puts "Following files need to be updated with new engine information:" puts "" puts "Gemfile" puts "config/application.rb" puts "app/assets/stylesheets/_engines.scss" end end <file_sep>/db/migrate/20160105231013_create_video_clips.video.rb # This migration comes from video (originally 20160105183823) class CreateVideoClips < ActiveRecord::Migration def change create_table :video_clips do |t| t.integer :capture_id t.string :zstate t.integer :length t.integer :frame_number_start t.integer :frame_number_end t.timestamps null: false end add_index :video_clips, :capture_id end end <file_sep>/engines/messaging/lib/messaging/states/storage/client_types.rb # Note: This relies in monkeypatching of module in # config/initializers/monkeypatch.rb (for Rails) # messaging/monkeypatch.rb (for non-Rails) module Messaging module States module Storage class ClientTypes def self.types ["rasbari", "capture", "storage"] end zextend BaseNonPersisted, Messaging::States::Storage::ClientTypes.types, { prefix: 'type' } attr_reader :type def initialize(t) @type = t end end end end end <file_sep>/engines/setting/lib/setting/engine.rb module Setting class Engine < ::Rails::Engine isolate_namespace Setting # Append routes before initialization initializer "setting", before: :load_config_initializers do |app| Rails.application.routes.append do mount Setting::Engine, at: "/setting" end end # Load files after initialization initializer "setting", after: :load_config_initializers do |app| Setting.files_to_load.each { |file| require_relative file } end # Change default generator to generate less files config.generators do |g| g.orm :active_record g.template_engine :erb g.test_framework :test_unit, fixture: false g.helper false g.assets false g.view_specs false g.jbuilder false g.templates.unshift File::expand_path('../../templates', __FILE__) end end end <file_sep>/config/initializers/monkeypatch.rb # Author: Evan # Here be dragons! Tread carefully class Object # Monkeypatch object to generate class methods def eigenclass class << self; self; end end end class Module # Monkeypatch module to allow `extend` with more capability def zextend(mod, *args) returnMod = include(mod) mod.zextended(self, *args) if mod.respond_to?(:zextended) returnMod end end <file_sep>/db/migrate/20160101034658_create_setting_machines.setting.rb # This migration comes from setting (originally 20160101031406) class CreateSettingMachines < ActiveRecord::Migration def change create_table :setting_machines do |t| t.string :ztype t.string :zstate t.string :zcloud t.string :zdetails t.string :hostname t.string :ip t.timestamps null: false end end end <file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. protect_from_forgery with: :exception, :if => Proc.new { |c| c.request.format != Mime::JSON } # For APIs use :null_session instead. protect_from_forgery with: :null_session, :if => Proc.new { |c| c.request.format == Mime::JSON } acts_as_token_authentication_handler_for User #before_action :authenticate_user! # ensure HTML format def ensure_html_format if request.format != Mime::HTML raise ActionController::RoutingError, "Format #{params[:format].inspect} not supported for #{request.path.inspect}" end end # ensure JSON format def ensure_json_format if request.format != Mime::JSON raise ActionController::RoutingError, "Format #{params[:format].inspect} not supported for #{request.path.inspect}" end end end <file_sep>/engines/setting/setting.gemspec $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "setting/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "setting" s.version = Setting::VERSION s.authors = ["Zigvu Inc."] s.summary = "Setting and configuration manager." s.description = "Manager for configuring machines, capture, processing etc." s.files = Dir["{app,bin,config,db,lib}/**/*", "Rakefile", "README.rdoc"] s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) } s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 4.2.5" s.add_development_dependency "sqlite3" end <file_sep>/engines/messaging/lib/messaging/connections/generic_server.rb module Messaging module Connections class GenericServer attr_accessor :exchangeName, :listenRoutingKey, :handler attr_accessor :rpcServer def initialize(exchangeName, listenRoutingKey, handler) connection = $bunny_connection || Messaging.connection @exchangeName = exchangeName @listenRoutingKey = listenRoutingKey @handler = handler @rpcServer = Messaging::Connections::RpcServer.new( connection, @exchangeName, @listenRoutingKey, @handler ) @rpcServer.start end end end end <file_sep>/engines/video/app/decorators/video/stream_decorator.rb module Video class StreamDecorator < Draper::Decorator delegate_all def hasError? # if the stream is capturing but no clip has been created in last 10 minutes if object.state.isCapturing? && lastClip return ((Time.now - lastClip.created_at)/60 > 10) end false end def lastClip # if there is an ongoing capture, supply active clip, else stopped clip object.captures.where(stopped_at: nil).count > 0 ? activeLastClip : stoppedLastClip end def activeLastClip lastCapture = object.captures.where(stopped_at: nil).order(created_at: :desc).last lastCapture.clips.last if lastCapture end def stoppedLastClip lastCapture = object.captures.where.not(stopped_at: nil).order(stopped_at: :desc).last lastCapture.clips.last if lastCapture end end end <file_sep>/engines/setting/app/authorizers/video/machine_authorizer.rb module Setting class MachineAuthorizer < ::ApplicationAuthorizer def self.default(adjective, user) # manager has ability to manage streams user.role.isAtLeastManager? end def self.readable_by?(user) # analyst has ability to read streams user.role.isAtLeastAnalyst? end end end <file_sep>/db/migrate/20160102035609_remove_capture_url_from_video_stream.video.rb # This migration comes from video (originally 20160102035551) class RemoveCaptureUrlFromVideoStream < ActiveRecord::Migration def change remove_column :video_streams, :capture_url, :string end end <file_sep>/lib/helpers/workflow/trackers_controller.rb require_dependency "sample_engine/application_controller" module SampleEngine class TrackersController < ApplicationController # TODO: change if different authority authorize_actions_for Parent before_action :set_tracker, only: [:show, :destroy] # GET /trackers/1 def show end # GET /trackers/new def new parent = Parent.find(params[:parent_id]) tracker = parent.trackers.create redirect_to tracker_workflow_path(Wicked::FIRST_STEP, tracker_id: tracker.id) end # DELETE /trackers/1 def destroy @tracker.destroy redirect_to parent_path(@parent), notice: 'Tracker was successfully destroyed.' end private # Use callbacks to share common setup or constraints between actions. def set_tracker @tracker = Tracker.find(params[:id]) @parent = @tracker.parent end end end <file_sep>/lib/tasks/engine.rake load 'lib/helpers/engine_creator.rb' load 'lib/helpers/workflow_creator.rb' namespace :engine do desc "Create new engine based on sample engine" task create: :environment do engineName = ENV['engine_name'] if (engineName == nil) puts "Usage: rake engine:create engine_name=<underscore_name>" puts "This will generate a new engine based on sample engine." puts "Exiting" else EngineCreator.new(engineName) end end desc "Create new workflow based on sample workflow" task workflow: :environment do engineName = ENV['engine_name'] trackerName = ENV['tracker_name'] parentName = ENV['parent_name'] stepNames = ENV['step_names'] if (engineName == nil || trackerName == nil || parentName == nil || stepNames == nil) puts "Usage: rake engine:workflow engine_name=<underscore_name> tracker_name=<underscore_name> parent_name=<underscore_name> step_names=<quoted_space_delimited_underscore_names> " puts "This will generate a new workflow based on sample workflow." puts "" puts "Example:" puts 'rake engine:workflow engine_name=setting tracker_name=machine_setting parent_name=machine step_names="step_one step_two"' puts "" puts "Exiting" else WorkflowCreator.new(engineName, trackerName, parentName, stepNames) end end end
dc491c2a152484af8de774c3bdddf75a9e3b9c87
[ "Markdown", "RDoc", "Ruby" ]
94
Ruby
zigvu/rasbari
3e936591f36f608264b6a742b05f28fca2c15f13
fa63d3c9a030693cf952cf082602461cbce7c720
refs/heads/master
<repo_name>czjun86/cas<file_sep>/src/main/webapp/js/report/compare/point_baidu.js /** * 加入对比轨迹点展示 * gsmlist,wcdmalist分别是2G与3G的轨迹数据 * @author czj,4GFTP的ID自定义为71 * **/ var map_arr=[]; var cans = []; var canscount = 0; var idooorTag = new Object(); var mapWforGoogle; function queryPoint(gsmlist,wcdmalist,ltelist,center,flist,flowids,flowname){ var compare = 1; var psc_xlist=[],bcch_xlist=[],pci_xlist=[]; for(var t=0;t<flist.length;t++){ if(flist[t].kpiId==20){ psc_xlist=flist[t].y; } if(flist[t].kpiId==21){ bcch_xlist=flist[t].y; } if(flist[t].kpiId==26){ pci_xlist=flist[t].y; } } var arr_id=flowids.split(","); var arr_name=flowname.split(","); //浮动div $("#tuli_ul").html(''); var tuils=[]; tuils.push('<ul>'); var cen_arr_f=new Map(); map_arr=[]; $("#compare_map").html(""); markerMap_fliwids_2g.clear(); markerMap_fliwids_3g.clear(); markerMap_fliwids_4g.clear(); zNodes_map.clear(); var sumlist=gsmlist; for(var i=0;i<wcdmalist.length;i++){ sumlist.push(wcdmalist[i]); } for(var i=0;i<ltelist.length;i++){ sumlist.push(ltelist[i]); } //给2G数据 、3G,4G数据按流水号分组 var xxMap={}; for(var i=0;i<sumlist.length;i++){ if(xxMap[sumlist[i].flowid] == undefined){ var list = []; list.push(sumlist[i]); xxMap[sumlist[i].flowid] = list; }else{ xxMap[sumlist[i].flowid].push(sumlist[i]); } } //计算宽度高度 var wid_len=(document.body.scrollWidth-document.body.scrollWidth*0.15)/2; var hie_len=((document.body.scrollWidth-document.body.scrollWidth*0.15)/2)*(9/16); $("#max").css("width",(wid_len+15)*2+20); $("#max").css("height",((wid_len+15)*2+20)*(9/16)); var i_s=0; for(ss in xxMap){ //一个流水号下的数据 var yy_p=[],yy_b=[],yy_l=[]; if(psc_xlist.length>0){ for(var t=0;t<psc_xlist.length;t++){ if(psc_xlist[t].flowid==ss){ yy_p.push(psc_xlist[t].pscbcch); } } } if(bcch_xlist.length>0){ for(var t=0;t<bcch_xlist.length;t++){ if(bcch_xlist[t].flowid==ss){ yy_b.push(bcch_xlist[t].pscbcch); } } } if(pci_xlist.length>0){ for(var t=0;t<pci_xlist.length;t++){ if(pci_xlist[t].flowid==ss){ yy_l.push(pci_xlist[t].pscbcch); } } } var na_index= 0; na_index= $.inArray(ss,arr_id); tuils.push('<li style="color:'+colorRoom_1[i_s]+';">'+arr_name[na_index]+'</li>'); zNodes=[]; var child=[],child_1=[],child_2=[]; var st=xxMap[ss]; var map_html=[]; map_html.push('<div class="computer_map_div" style="width:'+wid_len+'px;height:'+(hie_len+32)+'px;" id="mapdiv'+ss+'" > '); map_html.push('<div style="float:left"><select name="" id="g2_'+ss+'" class="g2select" seno="'+ss+'" style="z-index:998;width:100px" data-options="editable:false,panelHeight: \'auto\'"></select><select name="" class="g3select" seno="'+ss+'" id="g3_'+ss+'" style="z-index:998;width:100px" data-options="editable:false,panelHeight: \'auto\'"></select>'); map_html.push('<select name="" id="g4_'+ss+'" class="g2select" seno="'+ss+'" style="z-index:998;width:100px" data-options="editable:false,panelHeight: \'auto\'"></select></div>'); map_html.push('<samp style="z-index:998;margin:0px 0 0 8px;" class="samp_comp" id="samp_'+ss+'" inside="'+st[0].inside+'" title="轨迹叠加"></samp>'); map_html.push('<div style="float:right;" id="count_'+ss+'"></div>'); map_html.push('<p id="p_'+ss+'" style="color:'+colorRoom_1[i_s]+';margin-left:10px;float:right;width:auto;line-height:24px;margin-right:10px">'+ss.substring(0,12)+'</p>'); map_html.push('<div style="height:'+(hie_len)+'px;position: absolute;margin-top:36px">'); map_html.push('<div style="z-index:999;float:right;width:20px;position: absolute; right: 0px;">'); map_html.push('<img src="'+contextPath+'/images/map_add.png" class="changeImg" style="cursor:pointer;" id="imageid'+ss+'" sta= "smail" />'); if(st[0].inside == 0){ map_html.push('<img src="'+contextPath+'/images/map_big.png" style="display:none;" id="extid'+ss+'" />'); map_html.push('<img src="'+contextPath+'/images/map_small.png" style="display:none;" id= "naid'+ss+'"/></div>'); }else{ map_html.push('<img src="'+contextPath+'/images/map_big.png" style="cursor:pointer;" id="extid'+ss+'" />'); map_html.push('<img src="'+contextPath+'/images/map_small.png" style="cursor:pointer;" id= "naid'+ss+'"/></div>'); } //图例 map_html.push('<div class="case_tuc" id="case_tuc_'+ss+'"><div class="case_tuc_yyy"><p id="img_demo_'+ss+'" style="width:19px;height:19px;"></p><div class="clear"></div><div id="demo_div_'+ss+'"></div></div></div>'); map_html.push('<div id="map_'+ss+'" class="svg-div-main" style="height:'+(hie_len)+'px; width:'+wid_len+'px;overflow:hidden;">'); map_html.push('<div id="container'+ss+'" class="svg-main" style="width:1500px;height:1500px;position:absolute;left:-400px;top:-400px;background-color:#fff"></div>'); map_html.push('</div></div></div>'); i_s++; $("#compare_map").append($(map_html.join('\r\n'))); $("#g2_"+ss).hide(); $("#g3_"+ss).hide(); $("#g2_"+ss).empty(); $("#g3_"+ss).empty(); $("#g4_"+ss).hide(); $("#g4_"+ss).empty(); $("#count_"+ss).html("采样点:"+st.length); //根据数据生成菜单 var s_len=st.length; var dd=[],dd_id=[]; var dd_1=[],dd_id_1=[],dd_2=[],dd_id_2=[],centers=[]; for(var t=0;t<s_len;t++){ if(st[t].lat_modi>0&&st[t].lng_modi>0) centers.push(new BMap.Point(st[t].lng_modi,st[t].lat_modi)); if($.inArray(1,dd_id)<0&&st[t].rscp>0){ dd_id.push(1); dd.push({"text":'RSCP', "id": '1',"selected":true}); child.push({'id':4,'text':"RSCP"}); } if($.inArray(2,dd_id)<0&&st[t].ecno>0){ dd_id.push(2); dd.push({"text":'EcNo', "id": '2'}); child.push({'id':5,'text':"EcNo"}); } if($.inArray(3,dd_id)<0&&st[t].txpower>0&&st[t].rscp>0){ dd_id.push(3); dd.push({"text":'TXPOWER', "id": '3'}); child.push({'id':6,'text':"TXPOWER"}); } if(st[t].rscp>0){ if($.inArray(4,dd_id)<0&&st[t].ftpSpeed>0){ dd_id.push(4); dd.push({"text":'FTP3G', "id": '4'}); child.push({'id':7,'text':"FTP3G"}); }} if($.inArray(20,dd_id)<0&&st[t].psc>0){ dd_id.push(20); dd.push({"text":'PSC', "id": '20'}); child.push({'id':23,'text':"PSC"}); } if($.inArray(6,dd_id_1)<0&&st[t].rxlev>0){ dd_id_1.push(6); dd_1.push({"text":'RXLEV', "id": '6',"selected":true}); child_1.push({'id':9,'text':"RXLEV"}); } if($.inArray(7,dd_id_1)<0&&st[t].rxqual>0){ dd_id_1.push(7); dd_1.push({"text":'RXQUAL', "id": '7'}); child_1.push({'id':10,'text':"RXQUAL"}); } if($.inArray(8,dd_id_1)<0&&st[t].rxqual>0){ dd_id_1.push(8); dd_1.push({"text":'C/I', "id": '8'}); child_1.push({'id':11,'text':"C/I"}); } if($.inArray(21,dd_id_1)<0&&st[t].bcch>0){ dd_id_1.push(21); dd_1.push({"text":'BCCH', "id": '21'}); child_1.push({'id':24, 'text':"BCCH"}); } if($.inArray(23,dd_id_2)<0&&st[t].rsrp>0){ dd_id_2.push(23); dd_2.push({"text":'RSRP', "id": '23',"selected":true}); child_2.push({'id':26, 'text':"RSRP"}); } if($.inArray(24,dd_id_2)<0&&st[t].rsrq>0){ dd_id_2.push(24); dd_2.push({"text":'RSRQ', "id": '24'}); child_2.push({'id':27, 'text':"RSRQ"}); } if($.inArray(25,dd_id_2)<0&&st[t].snr>0){ dd_id_2.push(25); dd_2.push({"text":'SINR', "id": '25'}); child_2.push({'id':28, 'text':"SINR"}); } if(st[t].rsrp>0){ if($.inArray(71,dd_id_2)<0&&st[t].ftpSpeed>0){ dd_id_2.push(71); dd_2.push({"text":'FTP4G', "id": '71'}); child_2.push({'id':74,'text':"FTP4G"}); }} if($.inArray(26,dd_id_2)<0&&st[t].pci>0){ dd_id_2.push(26); dd_2.push({"text":'PCI', "id": '26'}); child_2.push({'id':29, 'text':"PCI"}); } } cen_arr_f.put(ss,centers); if(dd_id.length>0){ zNodes.push({'id':2, text:"3G",'children':child}); } if(dd_id_1.length>0){ zNodes.push({'id':1, text:"2G",'children':child_1}); } if(dd_id_2.length>0){ zNodes.push({'id':3, text:"4G",'children':child_2}); } if(dd_id.length>0){ $("#g3_"+ss).combobox({ data:dd, valueField: 'id', textField: 'text' });} if(dd_id_1.length>0){ $("#g2_"+ss).combobox({ data:dd_1, valueField: 'id', textField: 'text' });} if(dd_id_2.length>0){ $("#g4_"+ss).combobox({ data:dd_2, valueField: 'id', textField: 'text' });} zNodes_map.put(ss,zNodes); if(st[0].inside==0){ //生成地图 var map = new BMap.Map(document.getElementById("map_"+ss)); map.centerAndZoom(new BMap.Point(106.54241,29.559247) ,10); //地图事件设置函数: map.enableDragging(); //启用地图拖拽事件,默认启用(可不写) map.enableScrollWheelZoom(); //启用地图滚轮放大缩小 map.enableDoubleClickZoom(); //启用鼠标双击放大,默认启用(可不写) map.enableKeyboard(); //启用键盘上下左右键移动地图 //地图控件添加函数: //向地图中添加缩放控件 var ctrl_nav = new BMap.NavigationControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT, type: BMAP_NAVIGATION_CONTROL_SMALL }); map.addControl(ctrl_nav); //向地图中添加缩略图控件 var ctrl_ove = new BMap.OverviewMapControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT, isOpen: 1 }); map.addControl(ctrl_ove); //向地图中添加比例尺控件 var ctrl_sca = new BMap.ScaleControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT }); map.addControl(ctrl_sca); mapWforGoogle = new BMapLib.MapWrapper(map, BMapLib.COORD_TYPE_GOOGLE); var ija=$.inArray(ss,cen_arr_f.keys()); if(ija>=0){ map.setViewport(cen_arr_f.get(ss)); } map_arr.push(map); //下拉选择事件 (function(){ var p = map; var s_fid = ss; var st_p=st,ww=[],gg=[],ll=[]; var pp_y=yy_p,bb_y=yy_b,ll_y=yy_l; for (var f in st_p){ if(st_p[f].rxlev>0){ gg.push(st_p[f]); }else if(st_p[f].rscp>0){ ww.push(st_p[f]); }else if(st_p[f].rsrp>0){ ll.push(st_p[f]); } } var d=dd_id,d_1=dd_id_1,d_2=dd_id_2; if(d_1.length>0){ $("#g2_"+s_fid).combobox({ onSelect: function (n) { var str =n.text; chooseKpi(s_fid,p,null,st_p,null,str,1,pp_y,bb_y,ll_y); var sel1=0,sel2=0,sel3=0; var sel1_n="",sel2_n="",sel3_n=""; if(d_1.length>0){sel1=$("#g2_"+s_fid).combobox("getValue"); var str = $("#g2_"+s_fid).combobox("getText"); sel1_n=str; } if(d.length>0){sel2=$("#g3_"+s_fid).combobox("getValue"); sel2_n=$("#g3_"+s_fid).combobox("getText");} if(d_2.length>0){sel3=$("#g4_"+s_fid).combobox("getValue"); sel3_n=$("#g4_"+s_fid).combobox("getText");} if($("#demo_div_"+s_fid).html()){ choose_demo(s_fid,flist,sel1,sel2,sel3,sel1_n,sel2_n,sel3_n,"#demo_div_"+s_fid,ww,gg,ll); } } });} if(d.length>0){ $("#g3_"+s_fid).combobox({ onSelect: function (n) { var str =n.text; chooseKpi(s_fid,p,st_p,null,null,str,2,pp_y,bb_y,ll_y); var sel1=0,sel2=0,sel3=0; var sel1_n="",sel2_n="",sel3_n=""; if(d_1.length>0){sel1=$("#g2_"+s_fid).combobox("getValue"); var str = $("#g2_"+s_fid).combobox("getText"); sel1_n=str; } if(d.length>0){sel2=$("#g3_"+s_fid).combobox("getValue"); sel2_n=$("#g3_"+s_fid).combobox("getText");} if(d_2.length>0){sel3=$("#g4_"+s_fid).combobox("getValue"); sel3_n=$("#g4_"+s_fid).combobox("getText");} if($("#demo_div_"+s_fid).html()){ choose_demo(s_fid,flist,sel1,sel2,sel3,sel1_n,sel2_n,sel3_n,"#demo_div_"+s_fid,ww,gg,ll); } } });} if(d_2.length>0){ $("#g4_"+s_fid).combobox({ onSelect: function (n) { var str =n.text; chooseKpi(s_fid,p,null,null,st_p,str,3,pp_y,bb_y,ll_y); var sel1=0,sel2=0,sel3=0; var sel1_n="",sel2_n="",sel3_n=""; if(d_1.length>0){sel1=$("#g2_"+s_fid).combobox("getValue"); var str = $("#g2_"+s_fid).combobox("getText"); sel1_n=str; } if(d.length>0){sel2=$("#g3_"+s_fid).combobox("getValue"); sel2_n=$("#g3_"+s_fid).combobox("getText");} if(d_2.length>0){sel3=$("#g4_"+s_fid).combobox("getValue"); sel3_n=$("#g4_"+s_fid).combobox("getText");} if($("#demo_div_"+s_fid).html()){ choose_demo(s_fid,flist,sel1,sel2,sel3,sel1_n,sel2_n,sel3_n,"#demo_div_"+s_fid,ww,gg,ll); } } });} $("#imageid"+s_fid).unbind("click").bind("click", function(){ var pw = $("#map_"+s_fid).width(); var sta = $(this).attr("sta"); if(sta == "smail"){ $(this).attr("src","../images/map_lessen.png"); $(this).attr("sta","large"); var width = $("#max").width(); $("#map_"+s_fid).css('width',width); $("#mapdiv"+s_fid).css('width',width); }else{ $(this).attr("src","../images/map_add.png"); $(this).attr("sta","smail"); $("#map_"+s_fid).css('width',wid_len); $("#mapdiv"+s_fid).css('width',wid_len); } //google.maps.event.trigger(p, 'resize'); location.hash = "#mapdiv"+s_fid; }); })(); //3G室外点默认加载rscp chooseKpi(ss,map,st,null,null,"RSCP",2,psc_xlist,bcch_xlist,pci_xlist); //2G室外点默认加载rxlev chooseKpi(ss,map,null,st,null,"RXLEV",1,psc_xlist,bcch_xlist,pci_xlist); //4G室外点默认加载RSRP chooseKpi(ss,map,null,null,st,"RSRP",3,psc_xlist,bcch_xlist,pci_xlist); }else if(st[0].inside==1){ //室内 var canvas = showIndoorPoint(ss,st,st,st,colorlist,wid_len,yy_p,yy_b,yy_l,compare); cans.push(canvas); $("#mapdiv"+ss).attr("index",canscount); canscount ++; (function(){ var g2sel,g3sel,temp=""; var vs= new Array(); var s_fid = ss; var st_p=st,ww=[],gg=[],ll=[]; for (var f in st_p){ if(st_p[f].rxlev>0){ gg.push(st_p[f]); }else if(st_p[f].rscp>0){ ww.push(st_p[f]); }else if(st_p[f].rsrp>0){ ll.push(st_p[f]); } } var d=dd_id,d_1=dd_id_1,d_2=dd_id_2; var name_sel=[]; if(d_1.length>0)name_sel.push("#g2_"); if(d.length>0)name_sel.push("#g3_"); if(d_2.length>0)name_sel.push("#g4_"); for(var h=0;h<name_sel.length;h++){ $(name_sel[h]+s_fid).combobox({ onSelect: function (n,o) { temp=""; var str =""; var seno = $(this).attr("seno"); var _key = $(this).combobox("getText"); g3sel=$("#g3_"+seno).val(); if(d_1.length>0){ str = $("#g2_"+seno).combobox("getText"); temp = str+"," + temp; } if(d.length>0){temp = $("#g3_"+seno).combobox("getText")+"," + temp;} if(d_2.length>0){temp = $("#g4_"+seno).combobox("getText")+"," + temp;} var sel1=0,sel2=0,sel3=0; var sel1_n="",sel2_n="",sel3_n=""; if(d_1.length>0){sel1=$("#g2_"+seno).combobox("getValue"); sel1_n=$("#g2_"+seno).combobox("getText");} if(d.length>0){sel2=$("#g3_"+seno).combobox("getValue"); sel2_n=$("#g3_"+seno).combobox("getText");} if(d_2.length>0){sel3=$("#g4_"+seno).combobox("getValue"); sel3_n=$("#g4_"+seno).combobox("getText");} if($("#demo_div_"+seno).html()){ choose_demo(seno,flist,sel1,sel2,sel3,sel1_n,sel2_n,sel3_n,"#demo_div_"+seno,ww,gg,ll); } vs=temp.split(","); var index = $("#mapdiv"+seno).attr("index"); var ss = "data_" + seno; var draw_vs = new Array(); for (var x=0;x<vs.length;x++){ if($.inArray(vs[x], idooorTag[ss])<0){ idooorTag[ss].push(vs[x]); draw_vs.push(vs[x]); } } var cans_index = cans[index]; if(draw_vs.length>0){ var obj = getIdooorTagData(cans_index.allDatas,draw_vs); cans_index.initData(obj,draw_vs,cans_index.fristId,cans_index.fristType,cans_index.id_last,cans_index.type_last,cans_index.cw/3,cans_index.ch/3,cans_index.isclick,ss); } cans_index.display(vs); } }); } })(); } (function(){ var ff=true; var s_fid = ss; var st_p=st,ww=[],gg=[],ll=[]; for (var f in st_p){ if(st_p[f].rxlev>0){ gg.push(st_p[f]); }else if(st_p[f].rscp>0){ ww.push(st_p[f]); }else if(st_p[f].rsrp>0){ ll.push(st_p[f]); } } var d=dd_id,d_1=dd_id_1,d_2=dd_id_2; $("#img_demo_"+s_fid).unbind("click").bind("click", function(){ $("#case_tuc_"+s_fid).css("background","none repeat scroll 0 0 #fff"); $("#case_tuc_"+s_fid).css("border-bottom","1px solid #979797"); $("#case_tuc_"+s_fid).css("border-right","1px solid #979797"); var sel1=0,sel2=0,sel3=0; var sel1_n="",sel2_n="",sel3_n=""; if(d_1.length>0){sel1=$("#g2_"+s_fid).combobox("getValue"); sel1_n=$("#g2_"+s_fid).combobox("getText");} if(d.length>0){sel2=$("#g3_"+s_fid).combobox("getValue"); sel2_n=$("#g3_"+s_fid).combobox("getText");} if(d_2.length>0){sel3=$("#g4_"+s_fid).combobox("getValue"); sel3_n=$("#g4_"+s_fid).combobox("getText");} if(ff==true){ choose_demo(s_fid,flist,sel1,sel2,sel3,sel1_n,sel2_n,sel3_n,"#demo_div_"+s_fid,ww,gg,ll); $("#img_demo_"+s_fid).css({'background-image':'url(../images/case_tu.png)'}); ff=false; }else{ $("#case_tuc_"+s_fid).css("background",""); $("#case_tuc_"+s_fid).css("border-bottom",""); $("#case_tuc_"+s_fid).css("border-right",""); $("#demo_div_"+s_fid).html(""); ff=true; $("#img_demo_"+s_fid).css({'background-image':'url(../images/case_tu_s.png)'}); } }); })(); //轨迹叠加树形菜单 var inside = 0; (function(){ var s_fid = ss; var d=dd_id,d_1=dd_id_1,d_2=dd_id_2; $('#samp_'+s_fid).die().live("click",function(e){ $(".easyui-linkbutton").show(); inside = $(this).attr("inside"); $('.sure').attr("id",s_fid+"_sure"); var zno=zNodes_map.get(s_fid); $("#zhibiao").dialog({ height: 200,width: 380,title: "测试指标选择", modal: true,closed:false }); $("#tul").tree({ data:zno, animate:true, checkbox:true, onlyLeafCheck:true }); var sel1,sel2,sel3; sel1="#g2_"+s_fid; sel2="#g3_"+s_fid; sel3="#g4_"+s_fid; if(d_1.length>0){sel1 =$(sel1).combobox("getValue");} if(d.length>0){sel2 =$(sel2).combobox("getValue");} if(d_2.length>0){sel3 =$(sel3).combobox("getValue");} for(i in zno) { child=zno[i].children; for(j in child){ if(child[j].id==(parseInt(sel1)+3)){ var no= $("#tul").tree("find",child[j].id); $("#tul").tree("remove",no.target); } if(child[j].id==(parseInt(sel2)+3)){ var no= $("#tul").tree("find",child[j].id); $("#tul").tree("remove",no.target); } if(child[j].id==(parseInt(sel3)+3)){ var no= $("#tul").tree("find",child[j].id); $("#tul").tree("remove",no.target); } } } $('#zhibiao').dialog('open'); $.parser.parse('#zhibiao'); }); //树形确定事件 $('.treeb').unbind("click").click(function(e){ var sel1,sel2,sel3; var ss_f=$(".sure").attr("id").split("_")[0]; sel1="#g2_"+ss_f; sel2="#g3_"+ss_f; sel3="#g4_"+ss_f; var sgf=xxMap[ss_f]; for (var rr in sgf){ if(sgf[rr].rxlev>0){ sel1=$(sel1).combobox("getValue"); break; } } for (var rr in sgf){ if(sgf[rr].rscp>0){ sel2=$(sel2).combobox("getValue"); break; } } for (var rr in sgf){ if(sgf[rr].rsrp>0){ sel3=$(sel3).combobox("getValue"); break; } } var nodes = $('#zhibiao').tree('getChecked'); var v="",id_v="",str=""; if(nodes.length==0){ $.messager.alert("warning","至少选择一个指标!","warning"); return ; } for(var i=0; i<nodes.length; i++){ str = nodes[i].text; if(i != nodes.length-1){ v+=str + ","; id_v+=nodes[i].id + ","; }else{ v+=str; id_v+=nodes[i].id ; } } var idd=""; if(sel2){ idd+=(parseInt(sel2)+3)+","; } if(sel1){ idd+=(parseInt(sel1)+3)+","; } if(sel3){ idd+=(parseInt(sel3)+3)+","; } idd+=id_v; $("#undata").val(v); $("#undata_id").val(idd); if(inside == 1){ var slf=xxMap[ss_f]; var str = ""; for (var rr in slf){ if(slf[rr].rxlev>0){ str = $("#g2_"+ss_f).combobox("getText"); v = str+"," + v; break; } if(slf[rr].rscp>0){ v = $("#g3_"+ss_f).combobox("getText")+"," + v; break; } if(slf[rr].rsrp>0){ v = $("#g4_"+ss_f).combobox("getText")+"," + v; break; } } var vs= new Array(); vs = v.split(","); var index = $("#mapdiv"+ss_f).attr("index"); var draw_vs = new Array(); var ss = "data_" + ss_f; for (var x=0;x<vs.length;x++){ if($.inArray(vs[x], idooorTag[ss])<0){ idooorTag[ss].push(vs[x]); draw_vs.push(vs[x]); } } var cans_index = cans[index]; if(draw_vs.length>0){ var obj = getIdooorTagData(cans_index.allDatas,draw_vs); cans_index.initData(obj,draw_vs,cans_index.fristId,cans_index.fristType,cans_index.id_last,cans_index.type_last,cans_index.cw/3,cans_index.ch/3,cans_index.isclick,ss); } cans[index].display(vs); $('.wrapper,#dialData').hide(); }else if(inside == 0){ outclick($(".sure").attr("id").split("_")[0],map_arr,xxMap[$(".sure").attr("id").split("_")[0]],xxMap[$(".sure").attr("id").split("_")[0]],xxMap[$(".sure").attr("id").split("_")[0]],yy_p,yy_b,yy_l); } $('#zhibiao').dialog('close'); }); })(); } $("#background").hide(); $("#bar_id").hide(); $(document).css({"overflow":"auto"}); tuils.push('</ul>'); tuils = $(tuils.join('\r\n')); $("#tuli_ul").html(tuils); } /** * 室外多选点击事件 * @param doc */ function outclick(ss,map_arr,wcdmalist,gsmlist,ltelist,yy_p,yy_b,yy_l){ var map=null; for(t in map_arr){ if($(map_arr[t].getContainer()).attr("id").split("_")[1]==ss){ map=map_arr[t]; } } $('.wrapper,#dialData').hide(); var obj_id = $("#undata_id").attr("value"); var sid=obj_id.split(","); var g3="",g2="",g4=""; for(var i in sid){ switch (parseInt(sid[i])) { case 4: g3+=",RSCP"; break; case 5: g3+=",EcNo"; break; case 6: g3+=",TXPOWER"; break; case 7: g3+=",FTP3G"; break; case 23: g3+=",PSC"; break; case 9: g2+=",RXLEV"; break; case 10: g2+=",RXQUAL"; break; case 11: g2+=",C/I"; break; case 12: g2+=",MOS"; break; case 24: g2+=",BCCH"; break; case 26: g4+=",RSRP"; break; case 27: g4+=",RSRQ"; break; case 28: g4+=",SINR"; break; case 29: g4+=",PCI"; break; case 74: g4+=",FTP4G"; break; default: break; } } g2= g2.length>0?g2.substring(1,g2.length):""; g3= g3.length>0?g3.substring(1,g3.length):""; g4= g4.length>0?g4.substring(1,g4.length):""; if(g2!=""){ chooseKpi(ss,map,null,gsmlist,null,g2,1,yy_p,yy_b,yy_l); } if(g3!=""){ chooseKpi(ss,map,wcdmalist,null,null,g3,2,yy_p,yy_b,yy_l); } if(g4!=""){ chooseKpi(ss,map,null,null,ltelist,g4,3,yy_p,yy_b,yy_l); } } /** * 关闭弹出框 */ function closeclick(){ $("#background").hide(); $("#bar_id").hide(); $("body").removeClass('background'); $(document).css({"overflow":"show"}); $('.wrapper,#dialData').hide(); } /*** * 根据展示室内轨迹点数据* * */ function showIndoorPoint(ss,gsmlist,wcdmalist,ltelist,colorlist,winlen,yy_p,yy_b,yy_l,compare) { var pscmap = new Map();//键:PSC值,值:颜色集id var bcchmap=new Map();//键:PSC值,值:颜色集id var time_3g="",time_2g="",id_3g,id_2g,time_4g="",id_4g; var colorall=[]; var arr_color=[]; var co_len=colorlist.length; for(var t=0;t<co_len;t++) { var color=colorlist[t]; arr_color.push(color.colourcode); } var psc_arr_color=[]; var arr_co_len=arr_color.length; for (var j=arr_co_len-1;j>=0;j--){ psc_arr_color.push(arr_color[j]); } var dc=colorall.concat(psc_arr_color,colorRoom);//两个颜色合并作为PSC颜色用 //指标数据 var rscp=[],ecno=[],TxPower=[],psc=[],ftpSpeed=[],ftpSpeed_4g=[],rsrp=[],rsrq=[],snr=[],pci=[],rxlev=[],txpower_2g=[],rxqual=[],bcch=[],ci=[],mos=[]; //3G for(var i=0;i<wcdmalist.length;i++) { var wcdma=wcdmalist[i]; //RSCP if(wcdma.rscp>0){ var colorid=wcdma.rscp-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'2',va:wcdma.rscp_,reltype:wcdma.realnet_type}; rscp.push(obj); } //ECNO if(wcdma.ecno>0){ var colorid=wcdma.ecno-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'2',va:wcdma.ecno_,reltype:wcdma.realnet_type}; ecno.push(obj); } //TxPower if(wcdma.txpower>0){ var colorid=wcdma.txpower-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'2',va:wcdma.txpower_,reltype:wcdma.realnet_type}; TxPower.push(obj); } //FTP if(wcdma.ftpSpeed>0){ var tt_ft=wcdma.rscp>0?"2":"3"; var colorid=wcdma.ftpSpeed-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:tt_ft,va:wcdma.ftpSpeed_,reltype:wcdma.realnet_type}; if(tt_ft==2)ftpSpeed.push(obj); if(tt_ft==3)ftpSpeed_4g.push(obj); } //PSC if(wcdma.psc){ var ij=$.inArray(wcdma.psc.toString(),yy_p); if(ij<20){ var obj={x:wcdma.x,y:wcdma.y,color:dc[ij],id:wcdma.id,type:'2',va:wcdma.psc,reltype:wcdma.realnet_type}; psc.push(obj); } }//RSRP if(wcdma.rsrp>0){ var colorid=wcdma.rsrp-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'3',va:wcdma.rsrp_,reltype:wcdma.realnet_type}; rsrp.push(obj); } //RSRQ if(wcdma.rsrq>0){ var colorid=wcdma.rsrq-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'3',va:wcdma.rsrq_,reltype:wcdma.realnet_type}; rsrq.push(obj); } //SNR if(wcdma.snr>0){ var colorid=wcdma.snr-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'3',va:wcdma.snr_,reltype:wcdma.realnet_type}; snr.push(obj); } //PCI if(wcdma.pci){ var ij=$.inArray(wcdma.pci.toString(),yy_l); if(ij<20){ var obj={x:wcdma.x,y:wcdma.y,color:dc[ij],id:wcdma.id,type:'3',va:wcdma.pci,reltype:wcdma.realnet_type}; pci.push(obj); } } //RxLev if(wcdma.rxlev>0){ var colorid=wcdma.rxlev-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'1',va:wcdma.rxlev_,reltype:wcdma.realnet_type}; rxlev.push(obj); } //TxPower if(wcdma.txpower>0){ var colorid=wcdma.txpower-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'1',va:wcdma.txpower_,reltype:wcdma.realnet_type}; txpower_2g.push(obj); } //rxqual if(wcdma.rxqual>0){ var colorid=wcdma.rxqual-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'1',va:wcdma.rxqual_,reltype:wcdma.realnet_type}; rxqual.push(obj); } //ci if(wcdma.ci>0){ var colorid=wcdma.ci-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'1',va:wcdma.ci_,reltype:wcdma.realnet_type}; ci.push(obj); } //mos if(wcdma.mos>0){ var colorid=wcdma.mos-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'1',va:wcdma.mos_,reltype:wcdma.realnet_type}; mos.push(obj); } //bcch if(wcdma.bcch){ var ij=$.inArray(wcdma.bcch.toString(),yy_b); if(ij<20){ var obj={x:wcdma.x,y:wcdma.y,color:dc[ij],id:wcdma.id,type:'1',va:wcdma.bcch,reltype:wcdma.realnet_type}; bcch.push(obj); } } } //室内轨迹点数据 var dataObj = new Object(); if(rscp.length>0){dataObj.RSCP=rscp;} if(ecno.length>0){dataObj.EcNo=ecno;} if(TxPower.length>0){dataObj.TXPOWER=TxPower;} if(psc.length>0){dataObj.PSC=psc;} if(ftpSpeed.length>0){dataObj.FTP3G=ftpSpeed;} if(ftpSpeed_4g.length>0){dataObj.FTP4G=ftpSpeed_4g;} if(rxlev.length>0){dataObj.RXLEV=rxlev;} if(rxqual.length>0){dataObj.RXQUAL=rxqual;} if(ci.length>0){dataObj['C/I']=ci;} if(bcch.length>0){dataObj.BCCH=bcch;} if(rsrp.length>0){dataObj.RSRP=rsrp;} if(rsrq.length>0){dataObj.RSRQ=rsrq;} if(snr.length>0){dataObj.SINR=snr;} if(pci.length>0){dataObj.PCI=pci;} var s = new Array(); s.push("RSCP"); s.push("RXLEV"); s.push("RSRP"); idooorTag["data_"+ss] = s; var obj = getIdooorTagData(dataObj,s); var canvas = MyCanvas(dataObj,obj,s,"map_"+ss,"container"+ss,"imageid"+ss,"extid"+ss,"naid"+ss,"max",3000,1500,winlen,"mapdiv"+ss,false,null,null,null,null,compare); canvas.initPaper("data_"+ss); return canvas; } function getIdooorTagData(datas,vs){ var _2G = new Object(); var _3G = new Object(); var _4G = new Object(); if(vs.length>0){ for(var i=0;i<vs.length;i++){ if(vs[i]=='RXLEV'||vs[i]=='RXQUAL'||vs[i]=='C/I'||vs[i]=='BCCH'){ if(datas[vs[i]]){ _2G[vs[i]]=datas[vs[i]]; } } if(vs[i]=='RSCP'|| vs[i]=='EcNo' || vs[i]=='TXPOWER' || vs[i]=='PSC'|| vs[i]=='FTP3G'){ if(datas[vs[i]]){ _3G[vs[i]]=datas[vs[i]]; } } if(vs[i]=='RSRP'|| vs[i]=='RSRQ' || vs[i]=='SINR' || vs[i]=='PCI'|| vs[i]=='FTP4G'){ if(datas[vs[i]]){ _4G[vs[i]]=datas[vs[i]]; } } } } var obj = new Object(); obj["3G"] = _3G; obj["2G"] = _2G; obj["4G"] = _4G; return obj; } /*** * 公共选择指标加载数据 * @param wcdmalist 3g数据 * @param gsmlist 2g数据 * @param kpi用逗号隔开可多个',' * @param type 0-清除所有点,1-清除2G点,2-清除3G点 */ function chooseKpi(ss,map,wcdmalist,gsmlist,ltelist,kpi,type,yy_p,yy_b,yy_l){ //清除数据点 markerArr_2g=[]; markerArr_3g=[]; markerArr_2g_ex=[]; markerArr_3g_ex=[]; markerArr_4g=[]; markerArr_4g_ex=[]; if(type==1){ var arr=markerMap_fliwids_2g.get(ss); if(arr){ for(var d=0;d<arr.length; d++){ map.removeOverlay(arr[d]); } } markerMap_fliwids_2g.remove(ss); markerMap_fliwids_2g_ex.remove(ss); } if(type==2){ var arr=markerMap_fliwids_3g.get(ss); if(arr){ for(var d=0;d<arr.length; d++){ map.removeOverlay(arr[d]); } } markerMap_fliwids_3g.remove(ss); markerMap_fliwids_3g_ex.remove(ss); }if(type==3){ var arr=markerMap_fliwids_4g.get(ss); if(arr){ for(var d=0;d<arr.length; d++){ map.removeOverlay(arr[d]); } } markerMap_fliwids_4g.remove(ss); markerMap_fliwids_4g_ex.remove(ss); } var pscmap = new Map();//键:PSC值,值:颜色集id var bcchmap=new Map();//键:PSC值,值:颜色集id var arr_color=[]; for(var t=0;t<colorlist.length;t++) { var color=colorlist[t]; arr_color.push(color.colourcode); } var colorall=[]; var psc_arr_color=[]; var arr_co_len=arr_color.length; for (var j=arr_co_len-1;j>=0;j--){ psc_arr_color.push(arr_color[j]); } var dc=colorall.concat(psc_arr_color,colorRoom);//两个颜色合并作为PSC颜色用 var str=[]; str=kpi.length>1?kpi.split(','):str; if(str.length==0)str.push(kpi); var wd_len=0; if(wcdmalist){ wd_len=wcdmalist.length; } var lte_len=0; if(ltelist){ lte_len=ltelist.length; } var gs_len=0; if(gsmlist) { gs_len=gsmlist.length; } for(var i=0;i<wd_len;i++){ if(wcdmalist[i].rscp>0&&$.inArray('RSCP',str)>=0){ addMarker(map,wcdmalist[i].rscp,wcdmalist[i].id,2,new BMap.Point(wcdmalist[i].lat_modi+$.inArray('RSCP',str)/(map.getZoom()*100),wcdmalist[i].lng_modi-$.inArray('RSCP',str)/(map.getZoom()*100)),i,"RSCP", new BMap.Point(wcdmalist[i].lat+$.inArray('RSCP',str)/(map.getZoom()*100),wcdmalist[i].lng-$.inArray('RSCP',str)/(map.getZoom()*100)),wcdmalist[i].rscp_,wcdmalist[i].realnet_type); } if(wcdmalist[i].ecno>0&&$.inArray('EcNo',str)>=0){ addMarker(map,wcdmalist[i].ecno,wcdmalist[i].id,2,new BMap.Point(wcdmalist[i].lat_modi+$.inArray('EcNo',str)/(map.getZoom()*100),wcdmalist[i].lng_modi-$.inArray('EcNo',str)/(map.getZoom()*100)),i,"EC/No", new BMap.Point(wcdmalist[i].lat+$.inArray('EcNo',str)/(map.getZoom()*100),wcdmalist[i].lng-$.inArray('EcNo',str)/(map.getZoom()*100)),wcdmalist[i].ecno_,wcdmalist[i].realnet_type); } if(wcdmalist[i].txpower>0&&$.inArray('TXPOWER',str)>=0){ addMarker(map,wcdmalist[i].txpower,wcdmalist[i].id,2,new BMap.Point(wcdmalist[i].lat_modi+$.inArray('TXPOWER',str)/(map.getZoom()*100),wcdmalist[i].lng_modi-$.inArray('TXPOWER',str)/(map.getZoom()*100)),i,"TxPower", new BMap.Point(wcdmalist[i].lat+$.inArray('TXPOWER',str)/(map.getZoom()*100),wcdmalist[i].lng-$.inArray('TXPOWER',str)/(map.getZoom()*100)),wcdmalist[i].txpower_,wcdmalist[i].realnet_type); } if(wcdmalist[i].rscp>0&&wcdmalist[i].ftpSpeed>0&&$.inArray('FTP3G',str)>=0){ addMarker(map,wcdmalist[i].ftpSpeed,wcdmalist[i].id,2,new BMap.Point(wcdmalist[i].lat_modi+$.inArray('FTP3G',str)/(map.getZoom()*100),wcdmalist[i].lng_modi-$.inArray('FTP3G',str)/(map.getZoom()*100)),i,"FTP3G", new BMap.Point(wcdmalist[i].lat+$.inArray('FTP3G',str)/(map.getZoom()*100),wcdmalist[i].lng-$.inArray('FTP3G',str)/(map.getZoom()*100)),wcdmalist[i].ftpSpeed_,wcdmalist[i].realnet_type); } if(wcdmalist[i].psc&&$.inArray('PSC',str)>=0) { //PSC var ij=$.inArray(wcdmalist[i].psc.toString(),yy_p); if(ij<20){ addMarker(map,dc[ij],wcdmalist[i].id,2,new BMap.Point(wcdmalist[i].lat_modi+$.inArray('PSC',str)/(map.getZoom()*100),wcdmalist[i].lng_modi-$.inArray('PSC',str)/(map.getZoom()*100)),i,"PSC", new BMap.Point(wcdmalist[i].lat+$.inArray('PSC',str)/(map.getZoom()*100),wcdmalist[i].lng-$.inArray('PSC',str)/(map.getZoom()*100)),wcdmalist[i].psc,wcdmalist[i].realnet_type); } } } //4G for(var i=0;i<lte_len;i++){ if(ltelist[i].rsrp>0&&$.inArray('RSRP',str)>=0){ addMarker(map,ltelist[i].rsrp,ltelist[i].id,3,new BMap.Point(ltelist[i].lat_modi+$.inArray('RSRP',str)/(map.getZoom()*100),ltelist[i].lng_modi-$.inArray('RSRP',str)/(map.getZoom()*100)),i,"RSRP", new BMap.Point(ltelist[i].lat+$.inArray('RSRP',str)/(map.getZoom()*100),ltelist[i].lng-$.inArray('RSRP',str)/(map.getZoom()*100)),ltelist[i].rsrp_,ltelist[i].realnet_type); } if(ltelist[i].rsrq>0&&$.inArray('RSRQ',str)>=0){ addMarker(map,ltelist[i].rsrq,ltelist[i].id,3,new BMap.Point(ltelist[i].lat_modi+$.inArray('RSRQ',str)/(map.getZoom()*100),ltelist[i].lng_modi-$.inArray('RSRQ',str)/(map.getZoom()*100)),i,"RSRQ", new BMap.Point(ltelist[i].lat+$.inArray('RSRQ',str)/(map.getZoom()*100),ltelist[i].lng-$.inArray('RSRQ',str)/(map.getZoom()*100)),ltelist[i].rsrq_,ltelist[i].realnet_type); } if(ltelist[i].snr>0&&$.inArray('SINR',str)>=0){ addMarker(map,ltelist[i].snr,ltelist[i].id,3,new BMap.Point(ltelist[i].lat_modi+$.inArray('SINR',str)/(map.getZoom()*100),ltelist[i].lng_modi-$.inArray('SINR',str)/(map.getZoom()*100)),i,"SINR", new BMap.Point(ltelist[i].lat+$.inArray('SINR',str)/(map.getZoom()*100),ltelist[i].lng-$.inArray('SINR',str)/(map.getZoom()*100)),ltelist[i].snr_,ltelist[i].realnet_type); } if(ltelist[i].rsrp>0&&ltelist[i].ftpSpeed>0&&$.inArray('FTP4G',str)>=0){ addMarker(map,ltelist[i].ftpSpeed,ltelist[i].id,3,new BMap.Point(ltelist[i].lat_modi+$.inArray('FTP4G',str)/(map.getZoom()*100),ltelist[i].lng_modi-$.inArray('FTP4G',str)/(map.getZoom()*100)),i,"FTP4G", new BMap.Point(ltelist[i].lat+$.inArray('FTP4G',str)/(map.getZoom()*100),ltelist[i].lng-$.inArray('FTP4G',str)/(map.getZoom()*100)),ltelist[i].ftpSpeed_,ltelist[i].realnet_type); } if(ltelist[i].pci&&$.inArray('PCI',str)>=0) { //PSC var ij=$.inArray(ltelist[i].pci.toString(),yy_l); if(ij<20){ addMarker(map,dc[ij],ltelist[i].id,3,new BMap.Point(ltelist[i].lat_modi+$.inArray('PCI',str)/(map.getZoom()*100),ltelist[i].lng_modi-$.inArray('PCI',str)/(map.getZoom()*100)),i,"PCI", new BMap.Point(ltelist[i].lat+$.inArray('PCI',str)/(map.getZoom()*100),ltelist[i].lng-$.inArray('PCI',str)/(map.getZoom()*100)),ltelist[i].pci,ltelist[i].realnet_type); } } } for(var i=0;i<gs_len;i++){ if(gsmlist[i].rxlev>0&&$.inArray('RXLEV',str)>=0){ addMarker(map,gsmlist[i].rxlev,gsmlist[i].id,1,new BMap.Point(gsmlist[i].lat_modi+$.inArray('RXLEV',str)/(map.getZoom()*100),gsmlist[i].lng_modi-$.inArray('RXLEV',str)/(map.getZoom()*100)),i,"Rxlev", new BMap.Point(gsmlist[i].lat+$.inArray('RXLEV',str)/(map.getZoom()*100),gsmlist[i].lng-$.inArray('RXLEV',str)/(map.getZoom()*100)),gsmlist[i].rxlev_,gsmlist[i].realnet_type); } if(gsmlist[i].rxqual>0&&$.inArray('RXQUAL',str)>=0){ addMarker(map,gsmlist[i].rxqual,gsmlist[i].id,1,new BMap.Point(gsmlist[i].lat_modi+$.inArray('RXQUAL',str)/(map.getZoom()*100),gsmlist[i].lng_modi-$.inArray('RXQUAL',str)/(map.getZoom()*100)),i,"Rxqual", new BMap.Point(gsmlist[i].lat+$.inArray('RXQUAL',str)/(map.getZoom()*100),gsmlist[i].lng-$.inArray('RXQUAL',str)/(map.getZoom()*100)),gsmlist[i].rxqual_,gsmlist[i].realnet_type); } if(gsmlist[i].ci>0&&$.inArray('C/I',str)>=0){ addMarker(map,gsmlist[i].ci,gsmlist[i].id,1,new BMap.Point(gsmlist[i].lat_modi+$.inArray('C/I',str)/(map.getZoom()*100),gsmlist[i].lng_modi-$.inArray('C/I',str)/(map.getZoom()*100)),i,"C/I", new BMap.Point(gsmlist[i].lat+$.inArray('C/I',str)/(map.getZoom()*100),gsmlist[i].lng-$.inArray('C/I',str)/(map.getZoom()*100)),gsmlist[i].ci_,gsmlist[i].realnet_type); } if(gsmlist[i].bcch&&$.inArray('BCCH',str)>=0){ var ij=$.inArray(gsmlist[i].bcch.toString(),yy_b); if(ij<20){ addMarker(map,dc[ij],gsmlist[i].id,1,new BMap.Point(gsmlist[i].lat_modi+$.inArray('BCCH',str)/(map.getZoom()*100),gsmlist[i].lng_modi-$.inArray('BCCH',str)/(map.getZoom()*100)),i,"BCCH", new BMap.Point(gsmlist[i].lat+$.inArray('BCCH',str)/(map.getZoom()*100),gsmlist[i].lng-$.inArray('BCCH',str)/(map.getZoom()*100)),gsmlist[i].bcch,gsmlist[i].realnet_type); } } } if(type==1){ markerMap_fliwids_2g.put(ss,markerArr_2g); markerMap_fliwids_2g_ex.put(ss,markerArr_2g_ex); }else if(type==2){ markerMap_fliwids_3g.put(ss,markerArr_3g); markerMap_fliwids_3g_ex.put(ss,markerArr_3g_ex); }else if(type==3){ markerMap_fliwids_4g.put(ss,markerArr_4g); markerMap_fliwids_4g_ex.put(ss,markerArr_4g_ex); } } /*** * 室外添加marker方法 * @param state颜色状态 * @param id * @param type类型1-2g,2-3g * @param location_地方——偏移后 * @param exlocation地方-偏移前 * @param index顺序 * @param kpi * * @param intevl指标值 * @param realnetType真实网络状态 */ function addMarker(map,state,id,type,location_,index,kpi,exlocation,intevl,realnetType){ var location = new BMap.Point(location_.lat,location_.lng); intevl=":"+intevl; var scale=1; var icon,path,marker,strokeWeight; if(type==2){ //3g图标 //path= 'M0,0 C130,75 30,25'; path = 'w_'; strokeWeight=1; }else if(type==1){ //2G图标 path = 'g_'; strokeWeight=1; }else if(type==3){ //2G图标 path = 'l_'; strokeWeight=1; } //psc与bcch用的颜色不一样 if(kpi!='PSC'&&kpi!='BCCH'&&kpi!='PCI'){ if(state>0){ var fil; if(realnetType!=-1){ path+=colorlist[state-1].colourcode.substring(1,colorlist[state - 1].colourcode.length); }else{ path="linxin"; intevl=""; } icon =new BMap.Icon(contextPath+'/images/integration/'+path+'.png'+"?t="+new Date().getTime(),new BMap.Size(14,14), {imageSize:new BMap.Size(14,14)}); marker = new BMap.Marker(location, { title : kpi + intevl, icon:icon}); map.addOverlay(marker); } }else{ if(realnetType == -1){ //无服务-菱形 path="linxin"; intevl=""; state=","; } icon =new BMap.Icon(contextPath+'/images/integration/'+path+state.substring(1,state.length)+'.png'+"?t="+new Date().getTime(),new BMap.Size(14,14), {imageSize:new BMap.Size(14,14)}); marker = new BMap.Marker(location, { title : kpi + intevl, icon:icon}); map.addOverlay(marker); } //把各自的点装入数组中 if(type==1){ markerArr_2g.push(marker); markerArr_2g_ex.push(exlocation); }else if(type==2){ markerArr_3g.push(marker); markerArr_3g_ex.push(exlocation); }else if(type==3){ markerArr_4g.push(marker); markerArr_4g_ex.push(exlocation); } } function changeWindow(){ //计算宽度高度 var wid_len=(document.body.scrollWidth-document.body.scrollWidth*0.15)/2; var hie_len=((document.body.scrollWidth-document.body.scrollWidth*0.15)/2)*(9/16); $("#max").css("width",(wid_len+15)*2+20); $("#max").css("height",((wid_len+15)*2+20)*(9/16)); $(".computer_map_div").css("width",wid_len); $(".svg-div-main").css("width",wid_len); $(".computer_map_div").css("height",hie_len+32); $(".svg-div-main").css("width",wid_len); $(".svg-div-main").css("height",hie_len); $(".svg-div").css("height",hie_len); $(".svg-div").css("width",wid_len); $("#parentContainer").css("height",hie_len); $("#parentContainer").css("width",wid_len); $("#container").css("height",hie_len); $("#container").css("width",wid_len); var wid=(document.body.scrollWidth-document.body.scrollWidth*0.05)/2; $(".histogram_flash").css("width",wid); }<file_sep>/src/main/java/com/complaint/utils/SessionUtils.java package com.complaint.utils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import com.complaint.model.User; public class SessionUtils { public static User getUserByRequest(HttpServletRequest request){ HttpSession session = request.getSession(); User user = (User)session.getAttribute("user"); return user; } public static User getUserBySession(HttpSession session){ User user = (User)session.getAttribute("user"); return user; } public static String getUsernameByRequest(HttpServletRequest request){ HttpSession session = request.getSession(); User user = (User)session.getAttribute("user"); if(user == null) return ""; return user.getName(); } public static String getUsernameBySession(HttpSession session){ User user = (User)session.getAttribute("user"); if(user == null) return ""; return user.getName(); } public static String getRolenameByRequest(HttpServletRequest request){ HttpSession session = request.getSession(); User user = (User)session.getAttribute("user"); if(user == null) return ""; return user.getRolename(); } public static Integer getRoleidByRequest(HttpServletRequest request){ HttpSession session = request.getSession(); User user = (User)session.getAttribute("user"); if(user == null) return null; return user.getRoleid(); } public static String getRolenameBySession(HttpSession session){ User user = (User)session.getAttribute("user"); if(user == null) return ""; return user.getRolename(); } } <file_sep>/src/main/java/com/complaint/action/FileUploadController.java package com.complaint.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/upload") public class FileUploadController { @RequestMapping(value="/index",method=RequestMethod.GET) public ModelAndView index(HttpServletRequest requst){ ModelAndView mv = new ModelAndView("/upload/index"); return mv; } @RequestMapping(value="/fileupload",method=RequestMethod.POST) public ModelAndView fileupload(HttpServletRequest requst){ ModelAndView mv = new ModelAndView("/upload/index"); MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)requst; List<MultipartFile> files = mreq.getFiles("myfiles"); try { for(MultipartFile file : files){ if(file.isEmpty()){ continue; } double size = file.getSize() / 1024 / 1024; } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return mv; } } <file_sep>/src/main/webapp/js/Component/JPopUps.js SJ.NameSpace.register("SJ.Component"); SJ.Component["JPopUps"] = function(args){ var private, public, element, fn, handle; private = { EventClick: [ {nodeName:"a",className:"sure",fn:function(event, elem){ fn.EventClick(event, elem, 'sure'); }}, {nodeName:"a",className:"cancel",fn:function(event, elem){ fn.EventClick(event, elem, 'cancel'); }}, {nodeName:"img",className:"close",fn:function(event, elem){ fn.EventClick(event, elem, 'close'); }} ], EventDown: [ {nodeName:"div",className:"pop_up_top",fn:function(event, elem){ SJ.Drag(event, elem, element.POPUP[0]); return false; }}, {nodeName:"span",className:"pop_up_title",fn:function(event, elem){ SJ.Drag(event, elem, element.POPUP[0]); return false; }} ] }; public = { title: 'PopUps', width: 400, height: 395, html: '', button: { sure: { text: '确定', isClose: true, fn: null } } }; element = {}; fn = { createHtml: function(){ if(element.POPUP){ element.POPUP.remove(); element.POPUPBG.remove(); } var html = [], buttons, key, w, h; html.push('<div class="pop_up" style="position:absolute;top:-9999px;left:-9999px;z-index:1000;">'); html.push('<div class="pop_up_top"><span class="pop_up_title">#TITLE#</span>'); html.push('<samp><img class="close" src="' + contextPath + '/images/close.png" /></samp></div>'); html.push('<div class="pop_up_center">'); html.push('<div class="pop_up_content"><img src="' + contextPath + '/images/032.gif" id="loading" style="float:left;"></div>'); html.push('<div class="clear"></div>'); html.push('<div class="bottom_btn">'); buttons = public.button; for(key in buttons){ html.push('<div class="btn" style="margin:auto 5px;"><a class="'+key+'">'+buttons[key].text+'</a></div>'); } html.push('</div>'); html.push('</div>'); // html.push('<div class="all_list_bottom"><span></span><samp></samp></div>'); html.push('</div>'); html = $(html.join('\r\n').replace('#TITLE#', public.title)); w = public.width, h = public.height; html.css('width', w+'px').css('height', h+'px'); html.find('.pop_up_center').css('width', w+'px').css('height', (h-40-30)+'px'); html.find('.pop_up_content').css('width', '100%').css('height', (h-40-42-30)+'px'); element.POPUP = html; element.POPUPBG = $('<div class="pop_up_bg"></div>') .attr('style', 'position:absolute;top:-9999px;left:-9999px;z-index:-1;width:100%;background:#000000;'+ 'filter:alpha(opacity=10);opacity:0.1;_moz_opacity:0.1;' ); $(document.body).append(html); $(document.body).append(element.POPUPBG); var content = html.find('.pop_up_content'); var h = content.height(), w = content.width(); var img = content.find('img#loading'); img.css('margin-top', ((h/2)-(img.height()/2))+'px').css('margin-left', ((w/2)-(img.width()/2)-30)+'px'); if(public.html){ content.html(public.html); } }, EventClick: function(event, elem, clas){ if(clas == 'close'){ fn.hidden(); } else{ var key = public.button[clas]; if(key.fn){ key.fn(); } if(key.isClose){ fn.hidden(); } } }, show: function(args){ var top, left; top = ((SJ.clientWH().height/2)-(public.height/2)+(SJ.getScroll().top)); left = ((SJ.scrollWH().width/2)-(public.width/2)); top = top < 0 ? 0 : top; element.POPUP.css('top', (top)+'px').css('left', (left)+'px'); var background = element.POPUPBG; background.css('height', (SJ.scrollWH().height)+'px').css('top', '0px').css('left', '0px').css('z-index', '999'); var filter = 10; var times = SJ.browser().firefox ? 20 : 5; background = background[0].style; var thread = new SJ.Thread(function(){ background['filter'] = 'alpha(opacity='+filter+')'; background['opacity'] = filter/100; background['_moz_opacity'] = filter/100; filter += 4; if(filter >= 50){ thread.stop(); } }, times); thread.run(); }, hidden: function(){ element.POPUP.css('top', '-9999px').css('left', '-9999px'); var background = element.POPUPBG; background.css('top', '-9999px').css('left', '-9999px'); var filter = 70; var times = SJ.browser().firefox ? 20 : 5; background = background[0].style; var thread = new SJ.Thread(function(){ background['filter'] = 'alpha(opacity='+filter+')'; background['opacity'] = filter/100; background['_moz_opacity'] = filter/100; filter -= 4; if(filter <= 10){ thread.stop(); } }, times); thread.run(); } }; handle = { initArgs: function(args){ if(args){ $.extend(public, args); } fn.createHtml(); handle.bindEvent(); }, bindEvent: function(){ var popups = element.POPUP[0]; SJ.eventBubbling(private.EventClick, "click", popups); SJ.eventBubbling(private.EventDown, "mousedown", popups); var top, t; $(window).scroll(function(){ $(".pop_up").each(function(index, elem){ elem = $(elem); top = parseInt(elem.css('top')); if(top != -9999 && !isNaN(top)){ t = (SJ.clientWH().height/2)-(elem.height()/2)+(SJ.getScroll().top); elem.css('top', (t<0?0:t)+"px") } }); }); } }; handle.initArgs(args); this.panel = function(){ return element.POPUP; }; this.open = function(args){ if(args){ handle.initArgs(args); } fn.show(args); }; this.load = function(url, data, callBack){ fn.show(); var timestamp = '&'; if(url.indexOf('?') == -1){ timestamp = '?'; } timestamp = timestamp + 'timestamp=' + new Date().getTime(); element.POPUP.find('.pop_up_content').load(url+timestamp, data, callBack); }, this.close = function(){ fn.hidden(); }; };<file_sep>/src/main/java/com/complaint/mina/MinaServerHandler.java package com.complaint.mina; import java.io.StringWriter; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.complaint.service.EpinfoService; import com.complaint.service.Ftp4gService; import com.complaint.service.FtpService; import com.complaint.service.KPIColorService; import com.complaint.service.SceneService; import com.complaint.service.TestMasterlogService; import com.complaint.service.WorkOrderService; public class MinaServerHandler extends IoHandlerAdapter{ private static final Logger logger = LoggerFactory.getLogger(MinaServerHandler.class); @Autowired private EpinfoService epinfoService; @Autowired private WorkOrderService workOrderService; @Autowired private SceneService sceneService; @Autowired private TestMasterlogService testMasterlogService; @Autowired private KPIColorService kPIColorService; @Autowired private FtpService ftpService; @Autowired private Ftp4gService ftp4gService; //当一个客端端连结进入时 @Override public void sessionOpened(IoSession session) throws Exception { logger.debug("client incoming!"); } //当一个客户端关闭时 @Override public void sessionClosed(IoSession session) { logger.debug("client disconnect"); session.close(true); } //当客户端发送的消息到达时: @Override @SuppressWarnings("unchecked") public void messageReceived(IoSession session, Object message) throws Exception { System.out.println(session); System.out.println(message); boolean isvalid = Boolean.parseBoolean(session.getAttribute("validRequest").toString()); if(isvalid) { //解码已经转换为了String JSONObject json = (JSONObject)JSONValue.parse(message.toString()); short commond = Short.parseShort(session.getAttribute("commond").toString()); logger.debug("received msg:" + message + " received commond:" + commond); switch(commond){ //登陆验证 case 1: session.write(this.epinfoService.isValid(json.get("id")!=null?json.get("id").toString():null,json.get("pid")!=null?json.get("pid").toString():null)); break; //终端测试数据上报 case 2: try { this.testMasterlogService.addTestReport(json); JSONObject jsonObject = new JSONObject(); jsonObject.put("suc", "t"); StringWriter out = new StringWriter(); jsonObject.writeJSONString(out); session.write(out.toString()); }catch(RuntimeException ex){ JSONObject jsonObject = new JSONObject(); jsonObject.put("suc", "f"); StringWriter out = new StringWriter(); jsonObject.writeJSONString(out); session.write(out.toString()); logger.error("终端测试数据上报出错:",ex); } break; //获取工单列表 case 3: session.write(this.workOrderService.queryWorkOrderForPhoneList(json.get("pid").toString())); break; //获取场景信息 case 4: session.write(this.sceneService.queryAll()); break; //获取工单详情 case 5: session.write(this.workOrderService.queryWorkOrderForDetail(json.get("no").toString(),json.get("id").toString())); break; case 6:session.write(this.kPIColorService.queryKpicolor(json));break; //版本更新 case 7:session.write(this.kPIColorService.queryVision(json.get("vi").toString()));break; //FTP配置 case 8:session.write(json.get("nt")!=null && "4".equals(json.get("nt").toString())? this.ftp4gService.queryFtp(json.get("vi").toString()):this.ftpService.queryFtp(json.get("vi").toString()));break; //获取任务工单 case 9:session.write(this.workOrderService.queryTaskWorkOrder(json.get("pid").toString()));break; //4g工单列表 case 10: session.write(this.workOrderService.queryLteWorkOrderForPhoneList(json.get("pid").toString())); break; //4G版本更新 case 11:session.write(this.kPIColorService.queryVisionLte(json.get("vi").toString()));break; } }else session.close(true); } @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { logger.error("exceptionCaught ====>",cause); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { logger.debug("session idle,closed!"); session.close(true); } } <file_sep>/src/main/java/com/complaint/webservice/ServiceClient.java package com.complaint.webservice; import javax.xml.namespace.QName; import org.apache.axis2.AxisFault; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.client.Options; import org.apache.axis2.rpc.client.RPCServiceClient; import com.complaint.model.User; public class ServiceClient { public static void main(String[] args1) throws AxisFault { String path = "http://localhost:8080/services/SpringAwareService"; EndpointReference targetEPR = new EndpointReference(path); RPCServiceClient serviceClient = new RPCServiceClient(); Options options = serviceClient.getOptions(); options.setTo(targetEPR); QName opGetWeather = new QName("http://webservice.complaint.com","greeting"); User user = new User(); user.setUserid(5); Object[] response = serviceClient.invokeBlocking(opGetWeather, new Object[]{"张三"},new Class[]{String.class}); System.out.println(response[0]); } } <file_sep>/src/main/java/com/complaint/model/ReportDetials.java package com.complaint.model; /** * 数据分析页面报表内容 * @author peng * */ public class ReportDetials { private String flowid;//工单流水号 private String netType;//网络类型 private String area;//投诉区域 private String workerid;//派单员工号 private String dealnum;//受理号码 private String clientnum;//客户联系电话 private String url;//详细投诉地址 private String contentrs;//投诉内容 private String moduleContents;//模块内容 private String submitDateTime;//系统接单时间 } <file_sep>/src/main/webapp/js/gisgrad/angleconfig.js $(function(){ var num = 0; /** *修改角度配置 */ $("#saveangle").click(function(){ if(num == 0){ num++; $('#dataForm').ajaxForm({ url: contextPath + "/gisgrad/saveangle", type:'post', beforeSubmit:function(){ var ty = $("#angletype").val(); var an = $("#angle").val(); if(parseInt(ty)==0){ if(an==null||an==""){ $.messager.alert("提示","角度不能为空","success"); num=0; return false; } if(parseInt(an)<0 || parseInt(an)>360){//判定取值范围 $.messager.alert("提示","角度应该0-360","success"); num=0; return false; } } return true; }, success:function(data){ if(data == 1){ num=0; $.messager.alert("提示","角度配置修改成功!","success",function(){ location.href = contextPath+"/gisgrad/angleconfig"; }); }else{ num=0; $.messager.alert("提示","角度配置修改失败!","success",function(){ location.href = contextPath+"/gisgrad/angleconfig"; }); } } }); $('#dataForm').submit(); } }); /** * 当选中自身方位角的时候角度不输入 */ $("#angletype").combobox({ onSelect:function(){ var nowvalue = $(this).combobox('getValue'); if(parseInt(nowvalue) == 0){ $("#angleli").show(); }else if(parseInt(nowvalue) == 1){ $("#angleli").hide(); } }, onBeforeLoad:function(){ var nowvalue = $(this).combobox('getValue'); if(parseInt(nowvalue) == 0){ $("#angleli").show(); }else if(parseInt(nowvalue) == 1){ $("#angleli").hide(); } } }); });<file_sep>/src/main/webapp/js/workorder/kpi.js $(function() { $.parser.parse('.yfpz'); var num = 0; var colornum = 0; $("#setKpi").click(function(){ if(num == 0){ num++; $('#dataForm').ajaxForm({ url: contextPath + "/kpi/kipconfig?ischange="+ isChange, beforeSubmit:function(){ if(!$('#dataForm').form('validate')){ num = 0; return false; }else{ return true; } }, success: function(data) { num = 0; $.messager.alert("提示",data.msg,"success",function(){ window.location.href = window.location.href; }); } }); $("#dataForm").submit(); } }); $("#savecolor").click(function(){ if(colornum == 0){ colornum ++; $('#colorForm').ajaxForm({ url: contextPath + "/kpi/colorconfig", success: function(data) { colornum = 0; if(data.msg == -2){ $.messager.alert("提示","请将颜色值填写完整!","warning"); }else if(data.msg == -1){ $.messager.alert("提示","请不要选择相同的颜色值!","warning"); }else if(data.msg == 0){ $.messager.alert("提示","操作失败!","error"); }else{ $.messager.alert("提示","操作成功!","success"); } } }); $("#colorForm").submit(); } }); }); function changecolor(obj){ $(obj).css('background', $(obj).val()); } function isChangeVal(arg){ var oldval = $(arg).attr("oldval"); var newval = $(arg).val(); var isc = $(arg).attr("isc"); if(oldval != newval && isc ==0){ isChange ++; $(arg).attr("isc",1); }else{ isChange --; $(arg).attr("isc",0); } }<file_sep>/src/main/java/com/complaint/dao/TeamGroupDao.java package com.complaint.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.complaint.model.AreaBean; import com.complaint.model.GroupManager; import com.complaint.model.Personnel; import com.complaint.model.TeamGroup; public interface TeamGroupDao { /** * 分页统计页面 */ Integer countGroup(Map<String, Object> map); /** * 查出对应信息 */ List<GroupManager> groupInfo(Map<String, Object> map); /** * 大组与小组 * * @return */ List<TeamGroup> queryBigAndSmallRelation(); /** * 查询不在大组中的小组 * * @return */ List<TeamGroup> queryNotInBig(); /** * 小组与人员 * * @return */ List<TeamGroup> querySmallAndPersonnelRelation(); /** * 查询不在小组中的人员 * * @return */ List<Personnel> queryNotInSmall(); /** * 查询不是大组组长对应小组人员 * * @param groupid * @return */ List<Personnel> queryNotInBigPersonnel( @Param(value = "groupid") Integer groupid); /** * 查询不是小组组长的小组人员 * * @param groupid * @return */ List<Personnel> queryNotInSmallPersonnel( @Param(value = "groupid") Integer groupid); /** * 查询大组组长 * * @param groupid * @return */ Personnel queryGreatLeader(@Param(value = "groupid") Integer groupid); /** * 查询小组组长 * * @param groupid * @return */ Personnel queryLeader(@Param(value = "groupid") Integer groupid); /** * 人员与区域 * * @return */ List<Personnel> queryPersonneAndAreaRelation(); /** * 查询不在人员的区域 * * @return */ List<AreaBean> queryNotInPersonne(); /** * * @param groupname * @return */ int countGroupname(@Param(value = "groupname") String groupname); /** * 添加大组小组 */ void insertTeam(Map<String, Object> map); /** * 修改大组小组 * * @param map */ void updateTeam(Map<String, Object> map); /** * 删除大组小组 * * @param groupid */ void deleteTeam(@Param(value = "groupid") String groupid); /** * 删除小组加减分 * * @param groupid */ void deleteTeamScore(@Param(value = "groupid") String groupid); /** * 删除大组与小组关系 * * @param groupid */ void deleteTeamBigRelation(@Param(value = "groupid") String groupid); void deleteTeamMa(@Param(value = "groupid") String groupid); /** * 添加大组与小组关系 * * @param map */ void insertTeamBigRelation(Map<String, Object> map); /** * 删除小组与人员关系 */ void deleteTeamSmallRelation(@Param(value = "groupid") Integer groupid); /** * 添加小组人员关系 * * @param map */ void insertTeamSmallRelation(Map<String, Object> map); /** * 添加人员 * * @param map */ void insertPersonnel(Map<String, Object> map); /** * 修改人员信息 * * @param map */ void updatePersonnel(Map<String, Object> map); /** * 删除人员 * * @param groupid */ void deletePersonnel(@Param(value = "id") String id); /** * 删除人员与区域关系 * * @param id */ void deletePersonnelRelation(@Param(value = "id") String id); /** * 删除人员与小组关系 * * @param id */ void deletePersonTim(@Param(value = "id") String id); /** * 修改组长关系 * * @param id */ void updateTeamer(Map<String, Object> map); /** * 添加人员与区域关系 * * @param map */ void insertPersonnelRelation(Map<String, Object> map); /** * 取消小组组长 * * @param id */ void cancelLeader(); /** * 取消大组组长 * * @param id */ void cancelGreatLeader(); /** * 设置小组组长 * * @param map */ void setLeader(@Param(value = "id") Integer id); /** * 设置大组组长 * * @param map */ void setGreatLeader(@Param(value = "id") Integer id); } <file_sep>/src/main/java/com/complaint/model/Group.java package com.complaint.model; import java.util.ArrayList; import java.util.List; public class Group { private Integer groupid;// 分公司ID private String groupname;// 分公司名称 private List<AreaBean> list = new ArrayList<AreaBean>();// 已经归属的区域 private List<AreaBean> unlist = new ArrayList<AreaBean>();// 待归属的区域 private List<QualityConfig> quals = new ArrayList<QualityConfig>();// 分公司对应的步长 private String areas;// 区域名称集合 public String getAreas() { return areas; } public void setAreas(String areas) { this.areas = areas; } public List<QualityConfig> getQuals() { return quals; } public void setQuals(List<QualityConfig> quals) { this.quals = quals; } public List<AreaBean> getUnlist() { return unlist; } public void setUnlist(List<AreaBean> unlist) { this.unlist = unlist; } public Integer getGroupid() { return groupid; } public void setGroupid(Integer groupid) { this.groupid = groupid; } public String getGroupname() { return groupname; } public void setGroupname(String groupname) { this.groupname = groupname; } public List<AreaBean> getList() { return list; } public void setList(List<AreaBean> list) { this.list = list; } } <file_sep>/src/main/java/com/complaint/model/StaffAreas.java package com.complaint.model; import java.util.ArrayList; import java.util.List; public class StaffAreas { private Integer id;//人员ID private String name;//姓名 private String areaname;//区域名称 private Integer curr_serialno; //总量 private Integer curr_upgrade;//升级量 private Integer curr_over;//超时量 private Integer curr_complaint;//重复投诉 private Integer curr_send;//重派 private Integer curr_solve;// 真正解决 private List<StaffAreas> list = new ArrayList<StaffAreas>(); public List<StaffAreas> getList() { return list; } public void setList(List<StaffAreas> list) { this.list = list; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAreaname() { return areaname; } public void setAreaname(String areaname) { this.areaname = areaname; } public Integer getCurr_serialno() { return curr_serialno; } public void setCurr_serialno(Integer curr_serialno) { this.curr_serialno = curr_serialno; } public Integer getCurr_upgrade() { return curr_upgrade; } public void setCurr_upgrade(Integer curr_upgrade) { this.curr_upgrade = curr_upgrade; } public Integer getCurr_over() { return curr_over; } public void setCurr_over(Integer curr_over) { this.curr_over = curr_over; } public Integer getCurr_complaint() { return curr_complaint; } public void setCurr_complaint(Integer curr_complaint) { this.curr_complaint = curr_complaint; } public Integer getCurr_send() { return curr_send; } public void setCurr_send(Integer curr_send) { this.curr_send = curr_send; } public Integer getCurr_solve() { return curr_solve; } public void setCurr_solve(Integer curr_solve) { this.curr_solve = curr_solve; } } <file_sep>/src/main/webapp/js/login.js $(document).ready(function() { initAjaxForm(); $('#submit').click(function(){ var _this = $('#username'); var _errorMsg = $('#errorMsg'); var _length = jQuery.trim(_this.val()).length; if(_length == 0){ _errorMsg.html('用户名不能为空!'); _this.focus(); return; } if(_length > 30){ _errorMsg.html('用户名不能大于30位!'); _this.focus(); return; } _username = _this.val(); _this = $('#password'); _length = jQuery.trim(_this.val()).length; if(_length == 0) { _errorMsg.html('密码不能为空!'); _this.focus(); return; } if(_length > 32){ _errorMsg.html('密码不能大于32位'); _this.focus(); return; } _errorMsg.html('正在登陆...'); $("#myform").submit(); }); $('#myform').keydown(function(e){ var curKey = e.which; if(curKey == 13) $(this).submit(); }); }); function initAjaxForm(){ $('#myform').ajaxForm(function(data) { var _this = $('#password'); var _errorMsg = $('#errorMsg'); _errorMsg.html(data.msg); if(data.status == 0) { _this.val(''); _this.focus(); } else if(data.status == 1){ location.href = contextPath + data.url; } }); }<file_sep>/src/main/webapp/js/user/update.js $(function(){ var oknum = 0; $.parser.parse('.sys_possword'); $("#ok").click(function(){ if(oknum == 0){ oknum ++; $('#dataForm').ajaxForm({ url: contextPath + "/user/updatePsw", beforeSubmit:function(){ if(!$('#dataForm').form('validate')){ oknum = 0; return false; }else{ return true; } }, success: function(data) { oknum = 0; if(data.msg == 1){ $.messager.alert("提示","密码修改成功!","success",function(){ init(); }); }else if (data.msg == -1){ $.messager.alert("提示","旧密码输入错误!","error",function(){ $("#oldpsw").val(""); $("#oldpsw").focus(); }); }else if (data.msg == -2){ $.messager.alert("提示","两次密码输入不一致!","error",function(){ $("#password").focus(); $("#password").val(""); $("#repsw").val(""); }); }else{ $.messager.alert("提示","密码修改失败!","error",function(){ init(); }); } } }); $("#dataForm").submit(); } }); $("#reset").click(function(){ init(); }); var updatenum = 0; $("#update").click(function(){ if(updatenum == 0){ updatenum ++; $('#dataForm').ajaxForm({ type: "POST", url: contextPath + "/user/updateInfo", beforeSubmit:function(){ if(!$('#dataForm').form('validate')){ updatenum = 0; return false; }else{ return true; } }, success: function(data) { updatenum = 0; if(data.msg == 1){ $.messager.alert("提示","修改成功!","success"); }else{ $.messager.alert("提示","修改失败!","error"); } } }); $("#dataForm").submit(); } }); function init(){ $("#oldpsw").val("").attr('class','easyui-validatebox'); $("#password").val("").attr('class','easyui-validatebox'); $("#repsw").val("").attr('class','easyui-validatebox'); } }); <file_sep>/src/main/java/com/complaint/model/GradeBean.java package com.complaint.model; import org.codehaus.jackson.annotate.JsonIgnore; /** * * @ClassName: GradeBean * @Description: 等级评测实体 * @author: czj * @date: 2013-8-2 上午10:25:08 */ public class GradeBean { private Double free3;//自由模式3G百分比 private int isf; //是否第一次查询 private String area;//区域 private String sence;//场景 private String time;//测试时间 private String jtime;//接单时间 private String path;//受理路径 private Double lat_y;//原始纬度 private Double lng_y;//原始经度 private Double talkaround;//脱网率 private Double pocent2;//2G占比 private String sumc;//测试总条数 private String flowid;//流水号 private String phone;//投诉电话 private String net_worktype;//工单网络类型 private int test_type; private int call_type; private int ftp_type; private Double lat_m; private Double lng_m; private String serialno; private String problemsAddress; private String nettype;//1-2G,2-3G,3-3G自由,4-2G自由 private String inside; private String RSCP_g; private String rscp_color; private String ECNO_g; private String ecno_color; private String txpower_g; private String tx_color; private String fu_g; private String fu_color; private String fd_g; private String fd_color; private String fu_g_4g; private String fu_color_4g; private String fd_g_4g; private String fd_color_4g; private String rx_g; private String rx_color; private String rq_g; private String rq_color; private String ci_g; private String ci_color; private String RSRP_g; private String rsrp_color; private String RSRQ_g; private String rsrq_color; private String SNR_g; private String snr_color; //单个流水号的总评价 private String comp_eval_3g_g; private String comp_eval_3g_color; private String comp_eval_2g_g; private String comp_eval_2g_color; private String comp_eval_4g_g; private String comp_eval_4g_color; private Double RSCP_1; private Double RSCP_2; private Double RSCP_3; private Double RSCP_4; private Double EC_NO_1; private Double EC_NO_2; private Double EC_NO_3; private Double EC_NO_4; private Double txpower_1; private Double txpower_2; private Double txpower_3; private Double txpower_4; private Double FTP_SPEED_UP_1; private Double FTP_SPEED_UP_2; private Double FTP_SPEED_UP_3; private Double FTP_SPEED_UP_4; private Double FTP_SPEED_DOWN_1; private Double FTP_SPEED_DOWN_2; private Double FTP_SPEED_DOWN_3; private Double FTP_SPEED_DOWN_4; private Double RXLEV_Sub_1; private Double RXLEV_Sub_2; private Double RXLEV_Sub_3; private Double RXLEV_Sub_4; private Double RXQUAL_Sub_1; private Double RXQUAL_Sub_2; private Double RXQUAL_Sub_3; private Double RXQUAL_Sub_4; private Double ci_1; private Double ci_2; private Double ci_3; private Double ci_4; private Double rsrp_1; private Double rsrp_2; private Double rsrp_3; private Double rsrp_4; private Double rsrq_1; private Double rsrq_2; private Double rsrq_3; private Double rsrq_4; private Double snr_1; private Double snr_2; private Double snr_3; private Double snr_4; public Double getCi_1() { return ci_1; } public void setCi_1(Double ci_1) { this.ci_1 = ci_1; } public Double getCi_2() { return ci_2; } public void setCi_2(Double ci_2) { this.ci_2 = ci_2; } public Double getCi_3() { return ci_3; } public void setCi_3(Double ci_3) { this.ci_3 = ci_3; } public Double getCi_4() { return ci_4; } public void setCi_4(Double ci_4) { this.ci_4 = ci_4; } public String getComp_eval_3g_g() { return comp_eval_3g_g; } public void setComp_eval_3g_g(String comp_eval_3g_g) { this.comp_eval_3g_g = comp_eval_3g_g; } public String getComp_eval_3g_color() { return comp_eval_3g_color; } public void setComp_eval_3g_color(String comp_eval_3g_color) { this.comp_eval_3g_color = comp_eval_3g_color; } public String getComp_eval_2g_g() { return comp_eval_2g_g; } public void setComp_eval_2g_g(String comp_eval_2g_g) { this.comp_eval_2g_g = comp_eval_2g_g; } public String getComp_eval_2g_color() { return comp_eval_2g_color; } public void setComp_eval_2g_color(String comp_eval_2g_color) { this.comp_eval_2g_color = comp_eval_2g_color; } public String getJtime() { return jtime; } public void setJtime(String jtime) { this.jtime = jtime; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getSence() { return sence; } public void setSence(String sence) { this.sence = sence; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public Double getLat_m() { return lat_m; } public void setLat_m(Double lat_m) { this.lat_m = lat_m; } public Double getLng_m() { return lng_m; } public void setLng_m(Double lng_m) { this.lng_m = lng_m; } public String getSerialno() { return serialno; } public void setSerialno(String serialno) { this.serialno = serialno; } public String getProblemsAddress() { return problemsAddress; } public void setProblemsAddress(String problemsAddress) { this.problemsAddress = problemsAddress; } private Double ftp_avg_speed; public Double getRSCP_1() { return RSCP_1; } public void setRSCP_1(Double rSCP_1) { RSCP_1 = rSCP_1; } public Double getRSCP_2() { return RSCP_2; } public String getNettype() { return nettype; } public void setNettype(String nettype) { this.nettype = nettype; } public void setRSCP_2(Double rSCP_2) { RSCP_2 = rSCP_2; } public Double getRSCP_3() { return RSCP_3; } public void setRSCP_3(Double rSCP_3) { RSCP_3 = rSCP_3; } public Double getRSCP_4() { return RSCP_4; } public void setRSCP_4(Double rSCP_4) { RSCP_4 = rSCP_4; } public Double getEC_NO_1() { return EC_NO_1; } public void setEC_NO_1(Double eC_NO_1) { EC_NO_1 = eC_NO_1; } public Double getEC_NO_2() { return EC_NO_2; } public void setEC_NO_2(Double eC_NO_2) { EC_NO_2 = eC_NO_2; } public Double getEC_NO_3() { return EC_NO_3; } public void setEC_NO_3(Double eC_NO_3) { EC_NO_3 = eC_NO_3; } public Double getEC_NO_4() { return EC_NO_4; } public void setEC_NO_4(Double eC_NO_4) { EC_NO_4 = eC_NO_4; } public Double getTxpower_1() { return txpower_1; } public void setTxpower_1(Double txpower_1) { this.txpower_1 = txpower_1; } public Double getTxpower_2() { return txpower_2; } public void setTxpower_2(Double txpower_2) { this.txpower_2 = txpower_2; } public Double getTxpower_3() { return txpower_3; } public void setTxpower_3(Double txpower_3) { this.txpower_3 = txpower_3; } public Double getTxpower_4() { return txpower_4; } public void setTxpower_4(Double txpower_4) { this.txpower_4 = txpower_4; } public Double getFTP_SPEED_UP_1() { return FTP_SPEED_UP_1; } public void setFTP_SPEED_UP_1(Double fTP_SPEED_UP_1) { FTP_SPEED_UP_1 = fTP_SPEED_UP_1; } public Double getFTP_SPEED_UP_2() { return FTP_SPEED_UP_2; } public void setFTP_SPEED_UP_2(Double fTP_SPEED_UP_2) { FTP_SPEED_UP_2 = fTP_SPEED_UP_2; } public Double getFTP_SPEED_UP_3() { return FTP_SPEED_UP_3; } public void setFTP_SPEED_UP_3(Double fTP_SPEED_UP_3) { FTP_SPEED_UP_3 = fTP_SPEED_UP_3; } public Double getFTP_SPEED_UP_4() { return FTP_SPEED_UP_4; } public void setFTP_SPEED_UP_4(Double fTP_SPEED_UP_4) { FTP_SPEED_UP_4 = fTP_SPEED_UP_4; } public Double getFTP_SPEED_DOWN_1() { return FTP_SPEED_DOWN_1; } public void setFTP_SPEED_DOWN_1(Double fTP_SPEED_DOWN_1) { FTP_SPEED_DOWN_1 = fTP_SPEED_DOWN_1; } public Double getFTP_SPEED_DOWN_2() { return FTP_SPEED_DOWN_2; } public void setFTP_SPEED_DOWN_2(Double fTP_SPEED_DOWN_2) { FTP_SPEED_DOWN_2 = fTP_SPEED_DOWN_2; } public Double getFTP_SPEED_DOWN_3() { return FTP_SPEED_DOWN_3; } public void setFTP_SPEED_DOWN_3(Double fTP_SPEED_DOWN_3) { FTP_SPEED_DOWN_3 = fTP_SPEED_DOWN_3; } public Double getFTP_SPEED_DOWN_4() { return FTP_SPEED_DOWN_4; } public void setFTP_SPEED_DOWN_4(Double fTP_SPEED_DOWN_4) { FTP_SPEED_DOWN_4 = fTP_SPEED_DOWN_4; } public Double getRXLEV_Sub_1() { return RXLEV_Sub_1; } public void setRXLEV_Sub_1(Double rXLEV_Sub_1) { RXLEV_Sub_1 = rXLEV_Sub_1; } public Double getRXLEV_Sub_2() { return RXLEV_Sub_2; } public void setRXLEV_Sub_2(Double rXLEV_Sub_2) { RXLEV_Sub_2 = rXLEV_Sub_2; } public Double getRXLEV_Sub_3() { return RXLEV_Sub_3; } public void setRXLEV_Sub_3(Double rXLEV_Sub_3) { RXLEV_Sub_3 = rXLEV_Sub_3; } public Double getRXLEV_Sub_4() { return RXLEV_Sub_4; } public void setRXLEV_Sub_4(Double rXLEV_Sub_4) { RXLEV_Sub_4 = rXLEV_Sub_4; } public Double getRXQUAL_Sub_1() { return RXQUAL_Sub_1; } public void setRXQUAL_Sub_1(Double rXQUAL_Sub_1) { RXQUAL_Sub_1 = rXQUAL_Sub_1; } public Double getRXQUAL_Sub_2() { return RXQUAL_Sub_2; } public void setRXQUAL_Sub_2(Double rXQUAL_Sub_2) { RXQUAL_Sub_2 = rXQUAL_Sub_2; } public Double getRXQUAL_Sub_3() { return RXQUAL_Sub_3; } public void setRXQUAL_Sub_3(Double rXQUAL_Sub_3) { RXQUAL_Sub_3 = rXQUAL_Sub_3; } public Double getRXQUAL_Sub_4() { return RXQUAL_Sub_4; } public void setRXQUAL_Sub_4(Double rXQUAL_Sub_4) { RXQUAL_Sub_4 = rXQUAL_Sub_4; } public String getRSCP_g() { return RSCP_g; } public void setRSCP_g(String rSCP_g) { RSCP_g = rSCP_g; } public String getECNO_g() { return ECNO_g; } public void setECNO_g(String eCNO_g) { ECNO_g = eCNO_g; } public String getTxpower_g() { return txpower_g; } public void setTxpower_g(String txpower_g) { this.txpower_g = txpower_g; } public String getFu_g() { return fu_g; } public void setFu_g(String fu_g) { this.fu_g = fu_g; } public String getFd_g() { return fd_g; } public void setFd_g(String fd_g) { this.fd_g = fd_g; } public String getRx_g() { return rx_g; } public void setRx_g(String rx_g) { this.rx_g = rx_g; } public String getRq_g() { return rq_g; } public void setRq_g(String rq_g) { this.rq_g = rq_g; } public String getRscp_color() { return rscp_color; } public void setRscp_color(String rscp_color) { this.rscp_color = rscp_color; } public String getEcno_color() { return ecno_color; } public void setEcno_color(String ecno_color) { this.ecno_color = ecno_color; } public String getTx_color() { return tx_color; } public void setTx_color(String tx_color) { this.tx_color = tx_color; } public String getFu_color() { return fu_color; } public void setFu_color(String fu_color) { this.fu_color = fu_color; } public String getFd_color() { return fd_color; } public void setFd_color(String fd_color) { this.fd_color = fd_color; } public String getRx_color() { return rx_color; } public void setRx_color(String rx_color) { this.rx_color = rx_color; } public String getRq_color() { return rq_color; } public void setRq_color(String rq_color) { this.rq_color = rq_color; } public Double getFtp_avg_speed() { return ftp_avg_speed; } public void setFtp_avg_speed(Double ftp_avg_speed) { this.ftp_avg_speed = ftp_avg_speed; } public String getInside() { return inside; } public void setInside(String inside) { this.inside = inside; } public int getIsf() { return isf; } public void setIsf(int isf) { this.isf = isf; } public int getTest_type() { return test_type; } public void setTest_type(int test_type) { this.test_type = test_type; } public int getCall_type() { return call_type; } public void setCall_type(int call_type) { this.call_type = call_type; } public int getFtp_type() { return ftp_type; } public void setFtp_type(int ftp_type) { this.ftp_type = ftp_type; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Double getLat_y() { return lat_y; } public void setLat_y(Double lat_y) { this.lat_y = lat_y; } public Double getLng_y() { return lng_y; } public void setLng_y(Double lng_y) { this.lng_y = lng_y; } public Double getTalkaround() { return talkaround; } public void setTalkaround(Double talkaround) { this.talkaround = talkaround; } public Double getPocent2() { return pocent2; } public void setPocent2(Double pocent2) { this.pocent2 = pocent2; } public String getFlowid() { return flowid; } public void setFlowid(String flowid) { this.flowid = flowid; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Double getFree3() { return free3; } public void setFree3(Double free3) { this.free3 = free3; } public String getSumc() { return sumc; } public void setSumc(String sumc) { this.sumc = sumc; } public String getNet_worktype() { return net_worktype; } public void setNet_worktype(String net_worktype) { this.net_worktype = net_worktype; } public String getCi_g() { return ci_g; } public void setCi_g(String ci_g) { this.ci_g = ci_g; } public String getCi_color() { return ci_color; } public void setCi_color(String ci_color) { this.ci_color = ci_color; } public String getComp_eval_4g_g() { return comp_eval_4g_g; } public void setComp_eval_4g_g(String comp_eval_4g_g) { this.comp_eval_4g_g = comp_eval_4g_g; } public String getComp_eval_4g_color() { return comp_eval_4g_color; } public void setComp_eval_4g_color(String comp_eval_4g_color) { this.comp_eval_4g_color = comp_eval_4g_color; } public Double getRsrp_1() { return rsrp_1; } public void setRsrp_1(Double rsrp_1) { this.rsrp_1 = rsrp_1; } public Double getRsrp_2() { return rsrp_2; } public void setRsrp_2(Double rsrp_2) { this.rsrp_2 = rsrp_2; } public Double getRsrp_3() { return rsrp_3; } public void setRsrp_3(Double rsrp_3) { this.rsrp_3 = rsrp_3; } public Double getRsrp_4() { return rsrp_4; } public void setRsrp_4(Double rsrp_4) { this.rsrp_4 = rsrp_4; } public Double getRsrq_1() { return rsrq_1; } public void setRsrq_1(Double rsrq_1) { this.rsrq_1 = rsrq_1; } public Double getRsrq_2() { return rsrq_2; } public void setRsrq_2(Double rsrq_2) { this.rsrq_2 = rsrq_2; } public Double getRsrq_3() { return rsrq_3; } public void setRsrq_3(Double rsrq_3) { this.rsrq_3 = rsrq_3; } public Double getRsrq_4() { return rsrq_4; } public void setRsrq_4(Double rsrq_4) { this.rsrq_4 = rsrq_4; } public Double getSnr_1() { return snr_1; } public void setSnr_1(Double snr_1) { this.snr_1 = snr_1; } public Double getSnr_2() { return snr_2; } public void setSnr_2(Double snr_2) { this.snr_2 = snr_2; } public Double getSnr_3() { return snr_3; } public void setSnr_3(Double snr_3) { this.snr_3 = snr_3; } public Double getSnr_4() { return snr_4; } public void setSnr_4(Double snr_4) { this.snr_4 = snr_4; } public String getRSRP_g() { return RSRP_g; } public void setRSRP_g(String rSRP_g) { RSRP_g = rSRP_g; } public String getRsrp_color() { return rsrp_color; } public void setRsrp_color(String rsrp_color) { this.rsrp_color = rsrp_color; } public String getRSRQ_g() { return RSRQ_g; } public void setRSRQ_g(String rSRQ_g) { RSRQ_g = rSRQ_g; } public String getRsrq_color() { return rsrq_color; } public void setRsrq_color(String rsrq_color) { this.rsrq_color = rsrq_color; } public String getSNR_g() { return SNR_g; } public void setSNR_g(String sNR_g) { SNR_g = sNR_g; } public String getSnr_color() { return snr_color; } public void setSnr_color(String snr_color) { this.snr_color = snr_color; } public String getFu_g_4g() { return fu_g_4g; } public void setFu_g_4g(String fu_g_4g) { this.fu_g_4g = fu_g_4g; } public String getFu_color_4g() { return fu_color_4g; } public void setFu_color_4g(String fu_color_4g) { this.fu_color_4g = fu_color_4g; } public String getFd_g_4g() { return fd_g_4g; } public void setFd_g_4g(String fd_g_4g) { this.fd_g_4g = fd_g_4g; } public String getFd_color_4g() { return fd_color_4g; } public void setFd_color_4g(String fd_color_4g) { this.fd_color_4g = fd_color_4g; } } <file_sep>/src/main/java/com/complaint/service/ColourCodeService.java package com.complaint.service; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.complaint.dao.ColourCodeDao; import com.complaint.io.ObjectSerializableUtil; import com.complaint.model.ColourCode; import com.complaint.model.ConfigColor; import com.complaint.model.RateColor; import com.complaint.utils.CreateImgByColors; @Service("colourCodeService") public class ColourCodeService { @Autowired private ColourCodeDao colourCodeDao; /** * 查询所用的颜色值 * @return */ public List<ColourCode> getColourCodes(){ return colourCodeDao.queryColourCodes(); } /** * 查询不带#的颜色值 * @return */ public List<ColourCode> getColoursWithNoPoundSign(){ List<ColourCode> codes = colourCodeDao.queryColourCodes(); if (codes != null && codes.size() > 0) { for (ColourCode colourCode : codes) { colourCode.setColourcode(colourCode.getColourcode().replace("#", "")); } }else{ codes = initColors(codes); } return codes; } /** * 初始化codes * @param codes * @return */ private List<ColourCode> initColors(List<ColourCode> codes){ if(codes == null){ codes = new ArrayList<ColourCode>(); } ColourCode cc = null; for (int i = 0; i < 6; i++) { cc = new ColourCode(); cc.setSerialNum((short)(i+1)); codes.add(cc); } return codes; } /** * * @param colors * @return -2:未填完整 -1:有重复的color 0:系统错误 1:修改成功 */ @Transactional(rollbackFor=Exception.class) public int updateColour(String[] colors)throws Exception{ if(colors == null || colors.length <6){ return -2; }else{ for(int i = 0; i < colors.length; i++) { if(StringUtils.isEmpty(colors[i])){ return -2; } } for (int i = 0; i < colors.length; i++) { if(isExist(colors,colors[i],i)){ return -1; } } List<ColourCode> oldColors = this.getColoursWithNoPoundSign(); ColourCode colourCode = null; for(int i=0; i<colors.length; i++){ colourCode = new ColourCode(); colourCode.setSerialNum((short)(i+1)); colourCode.setColourcode("#"+colors[i]); colourCodeDao.update(colourCode); } //判断颜色是否修改 boolean flag = false; for(int i = 0;i < oldColors.size();i++){ if(!oldColors.get(i).getColourcode().equals(colors[i])){ flag = true; break; } } if(flag){ String filePath = this.getClass().getClassLoader().getResource("").getPath()+"/colorvision.txt"; try { ConfigColor color = ObjectSerializableUtil.readObject(filePath); if(color == null){ color = new ConfigColor(); color.setVision("1"); }else{ color.setVision((Integer.parseInt(color.getVision())+1)+""); } JSONObject jsonObject = new JSONObject(); jsonObject.put("vision", color.getVision()); StringWriter out = new StringWriter(); jsonObject.writeJSONString(out); ObjectSerializableUtil.write(filePath, out.toString()); out.close(); } catch (IOException e) { e.printStackTrace(); } } return 1; } } /** * 判断颜色值是否重复 * @param colors * @param color * @param index * @return */ private boolean isExist(String[] colors,String color,int index){ for(int i = 0; i < colors.length; i++) { if (index == i) { continue; }else{ if(color.equals(colors[i])){ return true; } } } return false; } /** * 生成图片 */ public void createImages(String completionPath,String[] colors){ // 生成图片 ColourCode[] cc = new ColourCode[6]; for(int i =0;i<colors.length;i++){ cc[i] = new ColourCode(); cc[i].setSerialNum(i+1); cc[i].setColourcode("#"+colors[i]); } try { CreateImgByColors.createKpiImage(cc,completionPath+"/images/integration/w_","●",18,19,18); CreateImgByColors.createKpiImage(cc,completionPath+"/images/integration/g_","▼",19,16,19); CreateImgByColors.createKpiImage(cc,completionPath+"/images/integration/l_","■",19,16,19); //CreateImgByColors.createKpiImage(cc,completionPath+"/images/integration/s_","◆",23,23,23); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>/src/main/java/com/complaint/model/LogSubmanualLte.java package com.complaint.model; import java.math.BigDecimal; import java.util.Date; public class LogSubmanualLte { private String lteid; private String flowid; private String uuid; private Integer areaid; private Short inside; private Date epTime; private Short gpsType; private BigDecimal longitude; private BigDecimal latitude; private BigDecimal longitudeModify; private BigDecimal latitudeModify; private BigDecimal positionX; private BigDecimal positionY; private Short realnetType; private Date testtime; private Long tac; private Long cid; private BigDecimal rsrp; private Long rsrq; private BigDecimal snr; private Long cqi; private Long pci; private Long ebid; private Short ftptype; private BigDecimal ftpSpeed; private BigDecimal longitudeBmap; private BigDecimal latitudeBmap; public String getLteid() { return lteid; } public void setLteid(String lteid) { this.lteid = lteid; } public String getFlowid() { return flowid; } public void setFlowid(String flowid) { this.flowid = flowid; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public Integer getAreaid() { return areaid; } public void setAreaid(Integer areaid) { this.areaid = areaid; } public Short getInside() { return inside; } public void setInside(Short inside) { this.inside = inside; } public Date getEpTime() { return epTime; } public void setEpTime(Date epTime) { this.epTime = epTime; } public Short getGpsType() { return gpsType; } public void setGpsType(Short gpsType) { this.gpsType = gpsType; } public BigDecimal getLongitude() { return longitude; } public void setLongitude(BigDecimal longitude) { this.longitude = longitude; } public BigDecimal getLatitude() { return latitude; } public void setLatitude(BigDecimal latitude) { this.latitude = latitude; } public BigDecimal getLongitudeModify() { return longitudeModify; } public void setLongitudeModify(BigDecimal longitudeModify) { this.longitudeModify = longitudeModify; } public BigDecimal getLatitudeModify() { return latitudeModify; } public void setLatitudeModify(BigDecimal latitudeModify) { this.latitudeModify = latitudeModify; } public BigDecimal getPositionX() { return positionX; } public void setPositionX(BigDecimal positionX) { this.positionX = positionX; } public BigDecimal getPositionY() { return positionY; } public void setPositionY(BigDecimal positionY) { this.positionY = positionY; } public Short getRealnetType() { return realnetType; } public void setRealnetType(Short realnetType) { this.realnetType = realnetType; } public Date getTesttime() { return testtime; } public void setTesttime(Date testtime) { this.testtime = testtime; } public Long getTac() { return tac; } public void setTac(Long tac) { this.tac = tac; } public Long getCid() { return cid; } public void setCid(Long cid) { this.cid = cid; } public BigDecimal getRsrp() { return rsrp; } public void setRsrp(BigDecimal rsrp) { this.rsrp = rsrp; } public Long getRsrq() { return rsrq; } public void setRsrq(Long rsrq) { this.rsrq = rsrq; } public BigDecimal getSnr() { return snr; } public void setSnr(BigDecimal snr) { this.snr = snr; } public Long getCqi() { return cqi; } public void setCqi(Long cqi) { this.cqi = cqi; } public Long getPci() { return pci; } public void setPci(Long pci) { this.pci = pci; } public Long getEbid() { return ebid; } public void setEbid(Long ebid) { this.ebid = ebid; } public BigDecimal getLongitudeBmap() { return longitudeBmap; } public void setLongitudeBmap(BigDecimal longitudeBmap) { this.longitudeBmap = longitudeBmap; } public BigDecimal getLatitudeBmap() { return latitudeBmap; } public void setLatitudeBmap(BigDecimal latitudeBmap) { this.latitudeBmap = latitudeBmap; } public Short getFtptype() { return ftptype; } public void setFtptype(Short ftptype) { this.ftptype = ftptype; } public BigDecimal getFtpSpeed() { return ftpSpeed; } public void setFtpSpeed(BigDecimal ftpSpeed) { this.ftpSpeed = ftpSpeed; } } <file_sep>/src/main/java/com/complaint/service/RateColorCodeService.java package com.complaint.service; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.complaint.dao.RateColorDao; import com.complaint.io.ObjectSerializableUtil; import com.complaint.model.ColourCode; import com.complaint.model.ConfigColor; import com.complaint.model.RateColor; import com.complaint.utils.CreateImgByColors; @Service("rateColorCodeService") public class RateColorCodeService { @Autowired private RateColorDao rateColorDao; /** * 查出所有颜色去掉# * @return */ public List<RateColor> getColoursWithNoPoundSign(){ List<RateColor> colors = this.rateColorDao.queryRateColors(); if(colors != null && colors.size()>0){ for(RateColor rateColors:colors){ rateColors.setRank_color(rateColors.getRank_color().replace("#", "")); } }else{ colors = initColors(colors); } return colors; } /** * 没查到颜色数据,手动初始化颜色数据 */ public List<RateColor> initColors(List<RateColor> colors){ if(colors == null){ colors = new ArrayList<RateColor>(); } RateColor rateColor = null; for(int i = 0;i < 4;i++){ rateColor = new RateColor(); rateColor.setRank_code(i+1); rateColor.setRank_color("00CCFF"); colors.add(rateColor); } return colors; } /** * 保存颜色 */ @Transactional(rollbackFor=Exception.class) public int saveColor(String[] colors)throws Exception{ if(colors == null || colors.length <4){ return -2; }else{ for(int i =0;i<colors.length;i++){ if(StringUtils.isEmpty(colors[i])){ return -2; } } for(int i =0;i<colors.length;i++){ if(isExist(colors,colors[i],i)){ return -1; } } List<RateColor> oldColors = this.getColoursWithNoPoundSign(); RateColor rateColor = null; for(int i=0; i<colors.length; i++){ rateColor = new RateColor(); rateColor.setRank_code(i+1); rateColor.setRank_color("#"+colors[i]); rateColor.setScene(0); rateColorDao.update(rateColor); } //判断颜色是否修改 boolean flag = false; for(int i = 0;i < oldColors.size();i++){ if(!oldColors.get(i).getRank_color().equals(colors[i])){ flag = true; break; } } if(flag){ String filePath = this.getClass().getClassLoader().getResource("").getPath()+"/colorvision.txt"; ConfigColor color = ObjectSerializableUtil.readObject(filePath); if(color == null){ color = new ConfigColor(); color.setVision("1"); }else{ color.setVision((Integer.parseInt(color.getVision())+1)+""); } JSONObject jsonObject = new JSONObject(); jsonObject.put("vision", color.getVision()); StringWriter out = new StringWriter(); jsonObject.writeJSONString(out); ObjectSerializableUtil.write(filePath, out.toString()); out.close(); } return 1; } } /** * 判断颜色值是否重复 * @param colors * @param color * @param index * @return */ private boolean isExist(String[] colors,String color,int index){ for(int i = 0; i < colors.length; i++) { if (index == i) { continue; }else{ if(color.equals(colors[i])){ return true; } } } return false; } /** * 生成图片 */ public void createImages(String completionPath,String[] colors){ // 生成图片 RateColor[] rateColor = new RateColor[4]; for(int i =0;i<colors.length;i++){ rateColor[i] = new RateColor(); rateColor[i].setRank_code(i+1); rateColor[i].setRank_color("#"+colors[i]); } try { //生成图片 CreateImgByColors.createImage(rateColor,completionPath+"/images/integration/w_","●",13,14,13); CreateImgByColors.createImage(rateColor,completionPath+"/images/integration/g_","▼",14,12,14); CreateImgByColors.createImage(rateColor,completionPath+"/images/integration/s_","★",14,14,14); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>/src/main/webapp/js/reportIndependent/compare/point_baidu.js /** * 加入对比轨迹点展示 * gsmlist,wcdmalist分别是2G与3G的轨迹数据 * @author czj * **/ var map_arr=[]; var cans = []; var canscount = 0; var idooorTag = new Object(); var mapWforGoogle; function queryPoint(gsmlist,wcdmalist,center,flist,flowids,flowname){ var compare = 1; var psc_xlist=[],bcch_xlist=[]; for(var t=0;t<flist.length;t++){ if(flist[t].kpiId==20){ psc_xlist=flist[t].y; } if(flist[t].kpiId==21){ bcch_xlist=flist[t].y; } } var arr_id=flowids.split(","); var arr_name=flowname.split(","); //浮动div $("#tuli_ul").html(''); var tuils=[]; tuils.push('<ul>'); var cen_arr_f=[]; for (var t=0;t<center.length;t++){ cen_arr_f.push(center[t].flowid); } map_arr=[]; $("#compare_map").html(""); markerMap_fliwids_2g.clear(); markerMap_fliwids_3g.clear(); zNodes_map.clear(); var sumlist=gsmlist; for(var i=0;i<wcdmalist.length;i++){ sumlist.push(wcdmalist[i]); } //给2G数据 、3G数据按流水号分组 var xxMap={}; for(var i=0;i<sumlist.length;i++){ if(xxMap[sumlist[i].flowid] == undefined){ var list = []; list.push(sumlist[i]); xxMap[sumlist[i].flowid] = list; }else{ xxMap[sumlist[i].flowid].push(sumlist[i]); } } //计算宽度高度 var wid_len=(document.body.scrollWidth-document.body.scrollWidth*0.15)/2; var hie_len=((document.body.scrollWidth-document.body.scrollWidth*0.15)/2)*(9/16); $("#max").css("width",(wid_len+15)*2+20); $("#max").css("height",((wid_len+15)*2+20)*(9/16)); var i_s=0; for(ss in xxMap){ //一个流水号下的数据 var yy_p=[],yy_b=[]; if(psc_xlist.length>0){ for(var t=0;t<psc_xlist.length;t++){ if(psc_xlist[t].flowid==ss){ yy_p.push(psc_xlist[t].pscbcch); } } } if(bcch_xlist.length>0){ for(var t=0;t<bcch_xlist.length;t++){ if(bcch_xlist[t].flowid==ss){ yy_b.push(bcch_xlist[t].pscbcch); } } } var na_index= 0; na_index= $.inArray(ss,arr_id); tuils.push('<li style="color:'+colorRoom_1[i_s]+';">'+arr_name[na_index]+'</li>'); zNodes=[]; var child=[],child_1=[]; var st=xxMap[ss]; var map_html=[]; map_html.push('<div class="computer_map_div" style="width:'+wid_len+'px;height:'+(hie_len+32)+'px;" id="mapdiv'+ss+'" > '); map_html.push('<div style="float:left"><select name="" id="g2_'+ss+'" class="g2select" seno="'+ss+'" style="z-index:998;width:100px" data-options="editable:false,panelHeight: \'auto\'"></select><select name="" class="g3select" seno="'+ss+'" id="g3_'+ss+'" style="z-index:998;width:100px" data-options="editable:false,panelHeight: \'auto\'"></select></div>'); map_html.push('<samp style="z-index:998;margin:0px 0 0 8px;" class="samp_comp" id="samp_'+ss+'" inside="'+st[0].inside+'" title="轨迹叠加"></samp>'); map_html.push('<div style="float:right;" id="count_'+ss+'"></div>'); map_html.push('<p id="p_'+ss+'" style="color:'+colorRoom_1[i_s]+';margin-left:10px;float:right;width:auto;line-height:24px;margin-right:10px">'+ss.substring(0,12)+'</p>'); map_html.push('<div style="height:'+(hie_len)+'px;position: absolute;margin-top:36px">'); map_html.push('<div style="z-index:999;float:right;width:20px;position: absolute; right: 0px;">'); map_html.push('<img src="'+contextPath+'/images/map_add.png" class="changeImg" style="cursor:pointer;" id="imageid'+ss+'" sta= "smail" />'); if(st[0].inside == 0){ map_html.push('<img src="'+contextPath+'/images/map_big.png" style="display:none;" id="extid'+ss+'" />'); map_html.push('<img src="'+contextPath+'/images/map_small.png" style="display:none;" id= "naid'+ss+'"/></div>'); }else{ map_html.push('<img src="'+contextPath+'/images/map_big.png" style="cursor:pointer;" id="extid'+ss+'" />'); map_html.push('<img src="'+contextPath+'/images/map_small.png" style="cursor:pointer;" id= "naid'+ss+'"/></div>'); } //图例 map_html.push('<div class="case_tuc" id="case_tuc_'+ss+'"><div class="case_tuc_yyy"><p id="img_demo_'+ss+'" style="width:19px;height:19px;"></p><div class="clear"></div><div id="demo_div_'+ss+'"></div></div></div>'); map_html.push('<div id="map_'+ss+'" class="svg-div-main" style="height:'+(hie_len)+'px; width:'+wid_len+'px;overflow:hidden;">'); map_html.push('<div id="container'+ss+'" class="svg-main" style="width:1500px;height:1500px;position:absolute;left:-400px;top:-400px;background-color:#fff"></div>'); map_html.push('</div></div></div>'); i_s++; $("#compare_map").append($(map_html.join('\r\n'))); $("#g2_"+ss).hide(); $("#g3_"+ss).hide(); $("#g2_"+ss).empty(); $("#g3_"+ss).empty(); $("#count_"+ss).html("采样点:"+st.length); //根据数据生成菜单 var s_len=st.length; var dd=[],dd_id=[]; var dd_1=[],dd_id_1=[]; for(var t=0;t<s_len;t++){ if($.inArray(1,dd_id)<0&&st[t].rscp>0){ dd_id.push(1); dd.push({"text":'RSCP', "id": '1',"selected":true}); child.push({'id':3,'text':"RSCP"}); } if($.inArray(2,dd_id)<0&&st[t].ecno>0){ dd_id.push(2); dd.push({"text":'EcNo', "id": '2'}); child.push({'id':4,'text':"EcNo"}); } if($.inArray(3,dd_id)<0&&st[t].txpower>0&&st[t].rscp>0){ dd_id.push(3); dd.push({"text":'TXPOWER', "id": '3'}); child.push({'id':5,'text':"TXPOWER"}); } if($.inArray(4,dd_id)<0&&st[t].ftpSpeed>0){ dd_id.push(4); dd.push({"text":'FTP', "id": '4'}); child.push({'id':6,'text':"FTP"}); } if($.inArray(20,dd_id)<0&&st[t].psc>0){ dd_id.push(20); dd.push({"text":'PSC', "id": '20'}); child.push({'id':22,'text':"PSC"}); } if($.inArray(6,dd_id_1)<0&&st[t].rxlev>0){ dd_id_1.push(6); dd_1.push({"text":'RXLEV', "id": '6',"selected":true}); child_1.push({'id':8,'text':"RXLEV"}); } if($.inArray(7,dd_id_1)<0&&st[t].rxqual>0){ dd_id_1.push(7); dd_1.push({"text":'RXQUAL', "id": '7'}); child_1.push({'id':9,'text':"RXQUAL"}); } if($.inArray(8,dd_id_1)<0&&st[t].rxqual>0){ dd_id_1.push(8); dd_1.push({"text":'C/I', "id": '8'}); child_1.push({'id':10,'text':"C/I"}); } if($.inArray(21,dd_id_1)<0&&st[t].bcch>0){ dd_id_1.push(21); dd_1.push({"text":'BCCH', "id": '21'}); child_1.push({'id':23, 'text':"BCCH"}); } } if(dd_id.length>0){ zNodes.push({'id':2, text:"3G",'children':child}); } if(dd_id_1.length>0){ zNodes.push({'id':1, text:"2G",'children':child_1}); } if(dd_id.length>0){ $("#g3_"+ss).combobox({ data:dd, valueField: 'id', textField: 'text' });} if(dd_id_1.length>0){ $("#g2_"+ss).combobox({ data:dd_1, valueField: 'id', textField: 'text' });} zNodes_map.put(ss,zNodes); if(st[0].inside==0){ //生成地图 var map = new BMap.Map(document.getElementById("map_"+ss)); map.centerAndZoom(new BMap.Point(106.54241,29.559247) ,10); //地图事件设置函数: map.enableDragging(); //启用地图拖拽事件,默认启用(可不写) map.enableScrollWheelZoom(); //启用地图滚轮放大缩小 map.enableDoubleClickZoom(); //启用鼠标双击放大,默认启用(可不写) map.enableKeyboard(); //启用键盘上下左右键移动地图 //地图控件添加函数: //向地图中添加缩放控件 var ctrl_nav = new BMap.NavigationControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT, type: BMAP_NAVIGATION_CONTROL_SMALL }); map.addControl(ctrl_nav); //向地图中添加缩略图控件 var ctrl_ove = new BMap.OverviewMapControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT, isOpen: 1 }); map.addControl(ctrl_ove); //向地图中添加比例尺控件 var ctrl_sca = new BMap.ScaleControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT }); map.addControl(ctrl_sca); mapWforGoogle = new BMapLib.MapWrapper(map, BMapLib.COORD_TYPE_GOOGLE); var ija=$.inArray(ss,cen_arr_f); if(ija>=0){ var cenetr_fl=[new BMap.Point(center[0].max_lng, center[0].max_lat), new BMap.Point(center[0].min_lng,center[0].min_lat)]; map.setViewport(cenetr_fl); } else{ map.centerAndZoom(cenetr_fl[0] ,15); } map_arr.push(map); //下拉选择事件 (function(){ var p = map; var s_fid = ss; var st_p=st,ww=[],gg=[]; var pp_y=yy_p,bb_y=yy_b; for (var f in st_p){ if(st_p[f].rxlev>0){ gg.push(st_p[f]); }else if(st_p[f].rscp>0){ ww.push(st_p[f]); } } var d=dd_id,d_1=dd_id_1; if(d_1.length>0){ $("#g2_"+s_fid).combobox({ onSelect: function (n,o) { var str = $("#g2_"+s_fid).combobox("getText"); chooseKpi(s_fid,p,null,st_p,str,1,pp_y,bb_y); var sel1=0,sel2=0; var sel1_n="",sel2_n=""; if(d_1.length>0){sel1=$("#g2_"+s_fid).combobox("getValue"); var str = $("#g2_"+s_fid).combobox("getText"); sel1_n=str; } if(d.length>0){sel2=$("#g3_"+s_fid).combobox("getValue"); sel2_n=$("#g3_"+s_fid).combobox("getText");} if($("#demo_div_"+s_fid).html()){ choose_demo(s_fid,flist,sel1,sel2,sel1_n,sel2_n,"#demo_div_"+s_fid,ww,gg); } } }); } //下拉列表3G点击事件 if(d.length>0){ $("#g3_"+s_fid).combobox({ onSelect: function (n,o) { chooseKpi(s_fid,p,st_p,null,$("#g3_"+s_fid).combobox("getText"),2,pp_y,bb_y); var sel1=0,sel2=0; var sel1_n="",sel2_n=""; if(d_1.length>0){sel1=$("#g2_"+s_fid).combobox("getValue"); sel1_n=$("#g2_"+s_fid).combobox("getText");} if(d.length>0){sel2=$("#g3_"+s_fid).combobox("getValue"); sel2_n=$("#g3_"+s_fid).combobox("getText");} if($("#demo_div_"+s_fid).html()){ choose_demo(s_fid,flist,sel1,sel2,sel1_n,sel2_n,"#demo_div_"+s_fid,ww,gg);} } }); } $("#imageid"+s_fid).unbind("click").bind("click", function(){ var pw = $("#map_"+s_fid).width(); var sta = $(this).attr("sta"); if(sta == "smail"){ $(this).attr("src","../images/map_lessen.png"); $(this).attr("sta","large"); var width = $("#max").width(); $("#map_"+s_fid).css('width',width); $("#mapdiv"+s_fid).css('width',width); }else{ $(this).attr("src","../images/map_add.png"); $(this).attr("sta","smail"); $("#map_"+s_fid).css('width',wid_len); $("#mapdiv"+s_fid).css('width',wid_len); } //google.maps.event.trigger(p, 'resize'); location.hash = "#mapdiv"+s_fid; }); })(); //3G室外点默认加载rscp chooseKpi(ss,map,st,null,"RSCP",2,psc_xlist,bcch_xlist); //2G室外点默认加载rxlev chooseKpi(ss,map,null,st,"RXLEV",1,psc_xlist,bcch_xlist); }else if(st[0].inside==1){ //室内 var canvas = showIndoorPoint(ss,st,st,colorlist,wid_len,yy_p,yy_b,compare); cans.push(canvas); $("#mapdiv"+ss).attr("index",canscount); canscount ++; (function(){ var g2sel,g3sel,temp=""; var vs= new Array(); var s_fid = ss; var st_p=st,ww=[],gg=[]; for (var f in st_p){ if(st_p[f].rxlev>0){ gg.push(st_p[f]); }else if(st_p[f].rscp>0){ ww.push(st_p[f]); } } var d=dd_id,d_1=dd_id_1; if(d_1.length>0){ $("#g2_"+s_fid).combobox({ onSelect: function (n,o) { temp=""; var str =""; var seno = $(this).attr("seno"); var _key = $(this).combobox("getText"); g3sel=$("#g3_"+seno).val(); if(d_1.length>0){ str = $("#g2_"+seno).combobox("getText"); temp = str+"," + temp; } if(d.length>0){temp = $("#g3_"+seno).combobox("getText")+"," + temp;} var sel1=0,sel2=0; var sel1_n="",sel2_n=""; if(d_1.length>0){sel1=$("#g2_"+seno).combobox("getValue"); sel1_n=$("#g2_"+seno).combobox("getText");} if(d.length>0){sel2=$("#g3_"+seno).combobox("getValue"); sel2_n=$("#g3_"+seno).combobox("getText");} if($("#demo_div_"+seno).html()){ choose_demo(seno,flist,sel1,sel2,sel1_n,sel2_n,"#demo_div_"+seno,ww,gg); } vs=temp.split(","); var index = $("#mapdiv"+seno).attr("index"); var ss = "data_" + seno; var draw_vs = new Array(); for (var x=0;x<vs.length;x++){ if($.inArray(vs[x], idooorTag[ss])<0){ idooorTag[ss].push(vs[x]); draw_vs.push(vs[x]); } } var cans_index = cans[index]; if(draw_vs.length>0){ var obj = getIdooorTagData(cans_index.allDatas,draw_vs); cans_index.initData(obj,draw_vs,cans_index.fristId,cans_index.fristType,cans_index.id_last,cans_index.type_last,cans_index.cw/3,cans_index.ch/3,cans_index.isclick,ss); } cans_index.display(vs); } }); } //下拉列表3G点击事件 if(d.length>0){ $("#g3_"+s_fid).combobox({ onSelect: function (n,o) { temp=""; var str = ""; var seno = $(this).attr("seno"); g2sel=$("#g2_"+seno).val(); if(d.length>0){temp = $("#g3_"+seno).combobox("getText")+"," + temp;} if(d_1.length>0){ str = $("#g2_"+seno).combobox("getText"); temp = str+"," + temp; } var sel1=0,sel2=0; var sel1_n="",sel2_n=""; if(d_1.length>0){sel1=$("#g2_"+seno).combobox("getValue"); sel1_n=$("#g2_"+seno).combobox("getText");} if(d.length>0){sel2=$("#g3_"+seno).combobox("getValue"); sel2_n=$("#g3_"+seno).combobox("getText");} if($("#demo_div_"+seno).html()){ choose_demo(seno,flist,sel1,sel2,sel1_n,sel2_n,"#demo_div_"+seno,ww,gg); } vs=temp.split(","); var index = $("#mapdiv"+seno).attr("index"); var ss = "data_" + seno; var draw_vs = new Array(); for (var x=0;x<vs.length;x++){ if($.inArray(vs[x], idooorTag[ss])<0){ idooorTag[ss].push(vs[x]); draw_vs.push(vs[x]); } } var cans_index = cans[index]; if(draw_vs.length>0){ var obj = getIdooorTagData(cans_index.allDatas,draw_vs); cans_index.initData(obj,draw_vs,cans_index.fristId,cans_index.fristType,cans_index.id_last,cans_index.type_last,cans_index.cw/3,cans_index.ch/3,cans_index.isclick,ss); } cans_index.display(vs); } }); } })(); } (function(){ var ff=true; var s_fid = ss; var st_p=st,ww=[],gg=[]; for (var f in st_p){ if(st_p[f].rxlev>0){ gg.push(st_p[f]); }else if(st_p[f].rscp>0){ ww.push(st_p[f]); } } var d=dd_id,d_1=dd_id_1; $("#img_demo_"+s_fid).unbind("click").bind("click", function(){ $("#case_tuc_"+s_fid).css("background","none repeat scroll 0 0 #fff"); $("#case_tuc_"+s_fid).css("border-bottom","1px solid #979797"); $("#case_tuc_"+s_fid).css("border-right","1px solid #979797"); var sel1=0,sel2=0; var sel1_n="",sel2_n=""; if(d_1.length>0){sel1=$("#g2_"+s_fid).combobox("getValue"); sel1_n=$("#g2_"+s_fid).combobox("getText");} if(d.length>0){sel2=$("#g3_"+s_fid).combobox("getValue"); sel2_n=$("#g3_"+s_fid).combobox("getText");} if(ff==true){ choose_demo(s_fid,flist,sel1,sel2,sel1_n,sel2_n,"#demo_div_"+s_fid,ww,gg); $("#img_demo_"+s_fid).css({'background-image':'url(../images/case_tu.png)'}); ff=false; }else{ $("#case_tuc_"+s_fid).css("background",""); $("#case_tuc_"+s_fid).css("border-bottom",""); $("#case_tuc_"+s_fid).css("border-right",""); $("#demo_div_"+s_fid).html(""); ff=true; $("#img_demo_"+s_fid).css({'background-image':'url(../images/case_tu_s.png)'}); } }); })(); //轨迹叠加树形菜单 var inside = 0; (function(){ var s_fid = ss; var d=dd_id,d_1=dd_id_1; $('#samp_'+s_fid).die().live("click",function(e){ $(".easyui-linkbutton").show(); inside = $(this).attr("inside"); $('.sure').attr("id",s_fid+"_sure"); var zno=zNodes_map.get(s_fid); $("#zhibiao").dialog({ height: 200,width: 380,title: "测试指标选择", modal: true,closed:false }); $("#tul").tree({ data:zno, animate:true, checkbox:true, onlyLeafCheck:true }); var sel1,sel2; sel1="#g2_"+s_fid; sel2="#g3_"+s_fid; if(d_1.length>0){sel1 =$(sel1).combobox("getValue");} if(d.length>0){sel2 =$(sel2).combobox("getValue");} for(i in zno) { child=zno[i].children; for(j in child){ if(child[j].id==(parseInt(sel1)+2)){ var no= $("#tul").tree("find",child[j].id); $("#tul").tree("remove",no.target); } if(child[j].id==(parseInt(sel2)+2)){ var no= $("#tul").tree("find",child[j].id); $("#tul").tree("remove",no.target); } } } $('#zhibiao').dialog('open'); $.parser.parse('#zhibiao'); }); //树形确定事件 $('.treeb').unbind("click").click(function(e){ var sel1,sel2; var ss_f=$(".sure").attr("id").split("_")[0]; sel1="#g2_"+ss_f; sel2="#g3_"+ss_f; var sgf=xxMap[ss_f]; for (var rr in sgf){ if(sgf[rr].rxlev>0){ sel1=$(sel1).combobox("getValue"); break; } } for (var rr in sgf){ if(sgf[rr].rscp>0){ sel2=$(sel2).combobox("getValue"); break; } } // if(d_1.length>0){sel1=$(sel1).combobox("getValue");} // if(d.length>0){sel2=$(sel2).combobox("getValue");} var nodes = $('#zhibiao').tree('getChecked'); var v="",id_v="",str=""; if(nodes.length==0){ $.messager.alert("warning","至少选择一个指标!","warning"); return ; } for(var i=0; i<nodes.length; i++){ str = nodes[i].text; if(i != nodes.length-1){ v+=str + ","; id_v+=nodes[i].id + ","; }else{ v+=str; id_v+=nodes[i].id ; } } var idd=""; if(sel2){ idd+=(parseInt(sel2)+2)+","; } if(sel1){ idd+=(parseInt(sel1)+2)+","; } idd+=id_v; $("#undata").val(v); $("#undata_id").val(idd); if(inside == 1){ var slf=xxMap[ss_f]; var str = ""; for (var rr in slf){ if(slf[rr].rxlev>0){ str = $("#g2_"+ss_f).combobox("getText"); v = str+"," + v; break; } } for (var rr in slf){ if(slf[rr].rscp>0){ v = $("#g3_"+ss_f).combobox("getText")+"," + v; break; } } var vs= new Array(); vs = v.split(","); var index = $("#mapdiv"+ss_f).attr("index"); var draw_vs = new Array(); var ss = "data_" + ss_f; for (var x=0;x<vs.length;x++){ if($.inArray(vs[x], idooorTag[ss])<0){ idooorTag[ss].push(vs[x]); draw_vs.push(vs[x]); } } var cans_index = cans[index]; if(draw_vs.length>0){ var obj = getIdooorTagData(cans_index.allDatas,draw_vs); cans_index.initData(obj,draw_vs,cans_index.fristId,cans_index.fristType,cans_index.id_last,cans_index.type_last,cans_index.cw/3,cans_index.ch/3,cans_index.isclick,ss); } cans[index].display(vs); $('.wrapper,#dialData').hide(); }else if(inside == 0){ outclick($(".sure").attr("id").split("_")[0],map_arr,xxMap[$(".sure").attr("id").split("_")[0]],xxMap[$(".sure").attr("id").split("_")[0]],yy_p,yy_b); } $('#zhibiao').dialog('close'); }); })(); } $("#background").hide(); $("#bar_id").hide(); $(document).css({"overflow":"auto"}); tuils.push('</ul>'); tuils = $(tuils.join('\r\n')); $("#tuli_ul").html(tuils); } /** * 室外多选点击事件 * @param doc */ function outclick(ss,map_arr,wcdmalist,gsmlist,yy_p,yy_b){ var map=null; for(t in map_arr){ if($(map_arr[t].getContainer()).attr("id").split("_")[1]==ss){ map=map_arr[t]; } } $('.wrapper,#dialData').hide(); var obj_id = $("#undata_id").attr("value"); var sid=obj_id.split(","); var g3="";g2=""; for(var i in sid){ switch (parseInt(sid[i])) { case 3: g3+=",RSCP"; break; case 4: g3+=",EcNo"; break; case 5: g3+=",TXPOWER"; break; case 6: g3+=",FTP"; break; case 22: g3+=",PSC"; break; case 8: g2+=",RXLEV"; break; case 9: g2+=",RXQUAL"; break; case 10: g2+=",C/I"; break; case 11: g2+=",MOS"; break; case 23: g2+=",BCCH"; break; default: break; } } g2= g2.length>0?g2.substring(1,g2.length):""; g3= g3.length>0?g3.substring(1,g3.length):""; if(g2!=""){ chooseKpi(ss,map,null,gsmlist,g2,1,yy_p,yy_b); } if(g3!=""){ chooseKpi(ss,map,wcdmalist,null,g3,2,yy_p,yy_b); } } /** * 关闭弹出框 */ function closeclick(){ $("#background").hide(); $("#bar_id").hide(); $("body").removeClass('background'); $(document).css({"overflow":"show"}); $('.wrapper,#dialData').hide(); } /*** * 根据展示室内轨迹点数据* * */ function showIndoorPoint(ss,gsmlist,wcdmalist,colorlist,winlen,yy_p,yy_b,compare) { var pscmap = new Map();//键:PSC值,值:颜色集id var bcchmap=new Map();//键:PSC值,值:颜色集id var time_3g="",time_2g="",id_3g,id_2g; var colorall=[]; var arr_color=[]; var co_len=colorlist.length; for(var t=0;t<co_len;t++) { var color=colorlist[t]; arr_color.push(color.colourcode); } var psc_arr_color=[]; var arr_co_len=arr_color.length; for (var j=arr_co_len-1;j>=0;j--){ psc_arr_color.push(arr_color[j]); } var dc=colorall.concat(psc_arr_color,colorRoom);//两个颜色合并作为PSC颜色用 //指标数据 var rscp=[],ecno=[],TxPower=[],psc=[],ftpSpeed=[]; //3G for(var i=0;i<wcdmalist.length;i++) { var wcdma=wcdmalist[i]; //RSCP if(wcdma.rscp>0){ var colorid=wcdma.rscp-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'2',va:wcdma.rscp_,reltype:wcdma.realnet_type}; rscp.push(obj); } //ECNO if(wcdma.ecno>0){ var colorid=wcdma.ecno-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'2',va:wcdma.ecno_,reltype:wcdma.realnet_type}; ecno.push(obj); } //TxPower if(wcdma.txpower>0){ var colorid=wcdma.txpower-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'2',va:wcdma.txpower_,reltype:wcdma.realnet_type}; TxPower.push(obj); } //FTP if(wcdma.ftpSpeed>0){ var colorid=wcdma.ftpSpeed-1; var obj={x:wcdma.x,y:wcdma.y,color:arr_color[colorid],id:wcdma.id,type:'2',va:wcdma.ftpSpeed_,reltype:wcdma.realnet_type}; ftpSpeed.push(obj); } //PSC if(wcdma.psc){ var ij=$.inArray(wcdma.psc.toString(),yy_p); if(ij<20){ var obj={x:wcdma.x,y:wcdma.y,color:dc[ij],id:wcdma.id,type:'2',va:wcdma.psc,reltype:wcdma.realnet_type}; psc.push(obj); } } } //2G var rxlev=[],txpower_2g=[],rxqual=[],bcch=[],ci=[],mos=[]; for(var i=0;i<gsmlist.length;i++) { var gsm=gsmlist[i]; //RxLev if(gsm.rxlev>0){ var colorid=gsm.rxlev-1; var obj={x:gsm.x,y:gsm.y,color:arr_color[colorid],id:gsm.id,type:'1',va:gsm.rxlev_,reltype:gsm.realnet_type}; rxlev.push(obj); } //TxPower if(gsm.txpower>0){ var colorid=gsm.txpower-1; var obj={x:gsm.x,y:gsm.y,color:arr_color[colorid],id:gsm.id,type:'1',va:gsm.txpower_,reltype:gsm.realnet_type}; txpower_2g.push(obj); } //rxqual if(gsm.rxqual>0){ var colorid=gsm.rxqual-1; var obj={x:gsm.x,y:gsm.y,color:arr_color[colorid],id:gsm.id,type:'1',va:gsm.rxqual_,reltype:gsm.realnet_type}; rxqual.push(obj); } //ci if(gsm.ci>0){ var colorid=gsm.ci-1; var obj={x:gsm.x,y:gsm.y,color:arr_color[colorid],id:gsm.id,type:'1',va:gsm.ci_,reltype:gsm.realnet_type}; ci.push(obj); } //mos if(gsm.mos>0){ var colorid=gsm.mos-1; var obj={x:gsm.x,y:gsm.y,color:arr_color[colorid],id:gsm.id,type:'1',va:gsm.mos_,reltype:gsm.realnet_type}; mos.push(obj); } //bcch if(gsm.bcch){ var ij=$.inArray(gsm.bcch.toString(),yy_b); if(ij<20){ var obj={x:gsm.x,y:gsm.y,color:dc[ij],id:gsm.id,type:'1',va:gsm.bcch,reltype:gsm.realnet_type}; bcch.push(obj); } } } //室内轨迹点数据 var dataObj = new Object(); if(rscp.length>0){dataObj.RSCP=rscp;} if(ecno.length>0){dataObj.EcNo=ecno;} if(TxPower.length>0){dataObj.TXPOWER=TxPower;} if(psc.length>0){dataObj.PSC=psc;} if(ftpSpeed.length>0){dataObj.FTP=ftpSpeed;} if(rxlev.length>0){dataObj.RXLEV=rxlev;} if(rxqual.length>0){dataObj.RXQUAL=rxqual;} if(ci.length>0){dataObj['C/I']=ci;} if(bcch.length>0){dataObj.BCCH=bcch;} var s = new Array(); s.push("RSCP"); s.push("RXLEV"); idooorTag["data_"+ss] = s; var obj = getIdooorTagData(dataObj,s); var canvas = MyCanvas(dataObj,obj,s,"map_"+ss,"container"+ss,"imageid"+ss,"extid"+ss,"naid"+ss,"max",3000,1500,winlen,"mapdiv"+ss,false,null,null,null,null,compare); canvas.initPaper("data_"+ss); return canvas; } function getIdooorTagData(datas,vs){ var _2G = new Object(); var _3G = new Object(); if(vs.length>0){ for(var i=0;i<vs.length;i++){ // var data = datas[ss]; if(vs[i]=='RXLEV'||vs[i]=='RXQUAL'||vs[i]=='C/I'||vs[i]=='BCCH'){ if(datas[vs[i]]){ _2G[vs[i]]=datas[vs[i]]; } } if(vs[i]=='RSCP'|| vs[i]=='EcNo' || vs[i]=='TXPOWER' || vs[i]=='PSC' || vs[i]=='FTP'){ if(datas[vs[i]]){ _3G[vs[i]]=datas[vs[i]]; } } } } var obj = new Object(); obj["3G"] = _3G; obj["2G"] = _2G; return obj; } /*** * 公共选择指标加载数据 * @param wcdmalist 3g数据 * @param gsmlist 2g数据 * @param kpi用逗号隔开可多个',' * @param type 0-清除所有点,1-清除2G点,2-清除3G点 */ function chooseKpi(ss,map,wcdmalist,gsmlist,kpi,type,yy_p,yy_b){ //清除数据点 markerArr_2g=[]; markerArr_3g=[]; markerArr_2g_ex=[]; markerArr_3g_ex=[]; if(type==1){ var arr=markerMap_fliwids_2g.get(ss); if(arr){ for(var d=0;d<arr.length; d++){ map.removeOverlay(arr[d]); } } markerMap_fliwids_2g.remove(ss); markerMap_fliwids_2g_ex.remove(ss); } if(type==2){ var arr=markerMap_fliwids_3g.get(ss); if(arr){ for(var d=0;d<arr.length; d++){ map.removeOverlay(arr[d]); } } markerMap_fliwids_3g.remove(ss); markerMap_fliwids_3g_ex.remove(ss); } var pscmap = new Map();//键:PSC值,值:颜色集id var bcchmap=new Map();//键:PSC值,值:颜色集id var arr_color=[]; for(var t=0;t<colorlist.length;t++) { var color=colorlist[t]; arr_color.push(color.colourcode); } var colorall=[]; var psc_arr_color=[]; var arr_co_len=arr_color.length; for (var j=arr_co_len-1;j>=0;j--){ psc_arr_color.push(arr_color[j]); } var dc=colorall.concat(psc_arr_color,colorRoom);//两个颜色合并作为PSC颜色用 var str=kpi.split(','); var wd_len=0; if(wcdmalist){ wd_len=wcdmalist.length; } var gs_len=0; if(gsmlist) { gs_len=gsmlist.length; } for(var i=0;i<wd_len;i++){ if(wcdmalist[i].rscp>0&&$.inArray('RSCP',str)>=0){ addMarker(map,wcdmalist[i].rscp,wcdmalist[i].id,2,new BMap.Point(wcdmalist[i].lat_modi+$.inArray('RSCP',str)/(map.getZoom()*100),wcdmalist[i].lng_modi-$.inArray('RSCP',str)/(map.getZoom()*100)),i,"RSCP", new BMap.Point(wcdmalist[i].lat+$.inArray('RSCP',str)/(map.getZoom()*100),wcdmalist[i].lng-$.inArray('RSCP',str)/(map.getZoom()*100)),wcdmalist[i].rscp_,wcdmalist[i].realnet_type); } if(wcdmalist[i].ecno>0&&$.inArray('EcNo',str)>=0){ addMarker(map,wcdmalist[i].ecno,wcdmalist[i].id,2,new BMap.Point(wcdmalist[i].lat_modi+$.inArray('EcNo',str)/(map.getZoom()*100),wcdmalist[i].lng_modi-$.inArray('EcNo',str)/(map.getZoom()*100)),i,"EC/No", new BMap.Point(wcdmalist[i].lat+$.inArray('EcNo',str)/(map.getZoom()*100),wcdmalist[i].lng-$.inArray('EcNo',str)/(map.getZoom()*100)),wcdmalist[i].ecno_,wcdmalist[i].realnet_type); } if(wcdmalist[i].txpower>0&&$.inArray('TXPOWER',str)>=0){ addMarker(map,wcdmalist[i].txpower,wcdmalist[i].id,2,new BMap.Point(wcdmalist[i].lat_modi+$.inArray('TXPOWER',str)/(map.getZoom()*100),wcdmalist[i].lng_modi-$.inArray('TXPOWER',str)/(map.getZoom()*100)),i,"TxPower", new BMap.Point(wcdmalist[i].lat+$.inArray('TXPOWER',str)/(map.getZoom()*100),wcdmalist[i].lng-$.inArray('TXPOWER',str)/(map.getZoom()*100)),wcdmalist[i].txpower_,wcdmalist[i].realnet_type); } if(wcdmalist[i].ftpSpeed>0&&$.inArray('FTP',str)>=0){ addMarker(map,wcdmalist[i].ftpSpeed,wcdmalist[i].id,2,new BMap.Point(wcdmalist[i].lat_modi+$.inArray('FTP',str)/(map.getZoom()*100),wcdmalist[i].lng_modi-$.inArray('FTP',str)/(map.getZoom()*100)),i,"FTP", new BMap.Point(wcdmalist[i].lat+$.inArray('FTP',str)/(map.getZoom()*100),wcdmalist[i].lng-$.inArray('FTP',str)/(map.getZoom()*100)),wcdmalist[i].ftpSpeed_,wcdmalist[i].realnet_type); } if(wcdmalist[i].psc&&$.inArray('PSC',str)>=0) { //PSC var ij=$.inArray(wcdmalist[i].psc.toString(),yy_p); if(ij<20){ addMarker(map,dc[ij],wcdmalist[i].id,2,new BMap.Point(wcdmalist[i].lat_modi+$.inArray('PSC',str)/(map.getZoom()*100),wcdmalist[i].lng_modi-$.inArray('PSC',str)/(map.getZoom()*100)),i,"PSC", new BMap.Point(wcdmalist[i].lat+$.inArray('PSC',str)/(map.getZoom()*100),wcdmalist[i].lng-$.inArray('PSC',str)/(map.getZoom()*100)),wcdmalist[i].psc,wcdmalist[i].realnet_type); } } } for(var i=0;i<gs_len;i++){ if(gsmlist[i].rxlev>0&&$.inArray('RXLEV',str)>=0){ addMarker(map,gsmlist[i].rxlev,gsmlist[i].id,1,new BMap.Point(gsmlist[i].lat_modi+$.inArray('RXLEV',str)/(map.getZoom()*100),gsmlist[i].lng_modi-$.inArray('RXLEV',str)/(map.getZoom()*100)),i,"Rxlev", new BMap.Point(gsmlist[i].lat+$.inArray('RXLEV',str)/(map.getZoom()*100),gsmlist[i].lng-$.inArray('RXLEV',str)/(map.getZoom()*100)),gsmlist[i].rxlev_,gsmlist[i].realnet_type); } if(gsmlist[i].rxqual>0&&$.inArray('RXQUAL',str)>=0){ addMarker(map,gsmlist[i].rxqual,gsmlist[i].id,1,new BMap.Point(gsmlist[i].lat_modi+$.inArray('RXQUAL',str)/(map.getZoom()*100),gsmlist[i].lng_modi-$.inArray('RXQUAL',str)/(map.getZoom()*100)),i,"Rxqual", new BMap.Point(gsmlist[i].lat+$.inArray('RXQUAL',str)/(map.getZoom()*100),gsmlist[i].lng-$.inArray('RXQUAL',str)/(map.getZoom()*100)),gsmlist[i].rxqual_,gsmlist[i].realnet_type); } if(gsmlist[i].ci>0&&$.inArray('C/I',str)>=0){ addMarker(map,gsmlist[i].ci,gsmlist[i].id,1,new BMap.Point(gsmlist[i].lat_modi+$.inArray('C/I',str)/(map.getZoom()*100),gsmlist[i].lng_modi-$.inArray('C/I',str)/(map.getZoom()*100)),i,"C/I", new BMap.Point(gsmlist[i].lat+$.inArray('C/I',str)/(map.getZoom()*100),gsmlist[i].lng-$.inArray('C/I',str)/(map.getZoom()*100)),gsmlist[i].ci_,gsmlist[i].realnet_type); } if(gsmlist[i].bcch&&$.inArray('BCCH',str)>=0){ var ij=$.inArray(gsmlist[i].bcch.toString(),yy_b); if(ij<20){ addMarker(map,dc[ij],gsmlist[i].id,1,new BMap.Point(gsmlist[i].lat_modi+$.inArray('BCCH',str)/(map.getZoom()*100),gsmlist[i].lng_modi-$.inArray('BCCH',str)/(map.getZoom()*100)),i,"BCCH", new BMap.Point(gsmlist[i].lat+$.inArray('BCCH',str)/(map.getZoom()*100),gsmlist[i].lng-$.inArray('BCCH',str)/(map.getZoom()*100)),gsmlist[i].bcch,gsmlist[i].realnet_type); } } } if(type==1){ markerMap_fliwids_2g.put(ss,markerArr_2g); markerMap_fliwids_2g_ex.put(ss,markerArr_2g_ex); }else{ markerMap_fliwids_3g.put(ss,markerArr_3g); markerMap_fliwids_3g_ex.put(ss,markerArr_3g_ex); } } /*** * 室外添加marker方法 * @param state颜色状态 * @param id * @param type类型1-2g,2-3g * @param location_地方——偏移后 * @param exlocation地方-偏移前 * @param index顺序 * @param kpi * * @param intevl指标值 * @param realnetType真实网络状态 */ function addMarker(map,state,id,type,location_,index,kpi,exlocation,intevl,realnetType){ var location = new BMap.Point(location_.lat,location_.lng); intevl=":"+intevl; var scale=1; var icon,path,marker,strokeWeight; if(type==2){ //3g图标 //path= 'M0,0 C130,75 30,25'; path = 'w_'; strokeWeight=1; }else if(type==1){ //2G图标 path = 'g_'; strokeWeight=1; } //psc与bcch用的颜色不一样 if(kpi!='PSC'&&kpi!='BCCH'){ if(state>0){ var fil; if(realnetType!=-1){ path+=colorlist[state-1].colourcode.substring(1,colorlist[state - 1].colourcode.length); }else{ path="linxin"; } icon =new BMap.Icon(contextPath+'/images/integration/'+path+'.png'+"?t="+new Date().getTime(),new BMap.Size(14,14), {imageSize:new BMap.Size(14,14)}); marker = new BMap.Marker(location, { title : kpi + intevl, icon:icon}); map.addOverlay(marker); } }else{ if(realnetType == -1){ //无服务-菱形 path="linxin"; state=","; } icon =new BMap.Icon(contextPath+'/images/integration/'+path+state.substring(1,state.length)+'.png'+"?t="+new Date().getTime(),new BMap.Size(14,14), {imageSize:new BMap.Size(14,14)}); marker = new BMap.Marker(location, { title : kpi + intevl, icon:icon}); map.addOverlay(marker); } //把各自的点装入数组中 if(type==1){ markerArr_2g.push(marker); markerArr_2g_ex.push(exlocation); }else{ markerArr_3g.push(marker); markerArr_3g_ex.push(exlocation); } } function changeWindow(){ //计算宽度高度 var wid_len=(document.body.scrollWidth-document.body.scrollWidth*0.15)/2; var hie_len=((document.body.scrollWidth-document.body.scrollWidth*0.15)/2)*(9/16); $("#max").css("width",(wid_len+15)*2+20); $("#max").css("height",((wid_len+15)*2+20)*(9/16)); $(".computer_map_div").css("width",wid_len); $(".svg-div-main").css("width",wid_len); $(".computer_map_div").css("height",hie_len+32); $(".svg-div-main").css("width",wid_len); $(".svg-div-main").css("height",hie_len); $(".svg-div").css("height",hie_len); $(".svg-div").css("width",wid_len); $("#parentContainer").css("height",hie_len); $("#parentContainer").css("width",wid_len); $("#container").css("height",hie_len); $("#container").css("width",wid_len); var wid=(document.body.scrollWidth-document.body.scrollWidth*0.05)/2; $(".histogram_flash").css("width",wid); }<file_sep>/src/main/java/com/complaint/action/ReportConfigController.java package com.complaint.action; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.complaint.model.AreaBean; import com.complaint.model.Group; import com.complaint.model.QualityBasicConfig; import com.complaint.page.PageBean; import com.complaint.service.ReportConfigService; import com.complaint.utils.Constant; import com.complaint.utils.ExcelUtil; @Controller @RequestMapping("/reportconfig") public class ReportConfigController { private static final Logger logger = LoggerFactory .getLogger(ReportConfigController.class); @Autowired private ReportConfigService reportConfigService; /** * 分公司配置 * * @return */ @RequestMapping(value = "/grouplist", method = RequestMethod.GET) public ModelAndView getGroupInfo(HttpServletRequest request) { ModelAndView mv = new ModelAndView("/reportconfig/grouplist"); PageBean pb = this.reportConfigService .countGroups(1, Constant.PAGESIZE); mv.addObject("pb", pb); return mv; } @RequestMapping(value = "/grouplist/template") public String rolelistJson(Model model, String rolename, Integer pageIndex, HttpServletRequest request) { // List<Resource> buttons = this.roleResourceLoader.getButtons(request); try { PageBean pb = this.reportConfigService.getGroupsList(pageIndex, Constant.PAGESIZE); List<Group> list = (List<Group>) pb.getList(); model.addAttribute("contextPath", request.getContextPath()); model.addAttribute("list", list); } catch (Exception e) { e.printStackTrace(); logger.error("", e); } return "/reportconfig/groupchildlist"; } /** * 分公司管理 * * @param id * @return */ @RequestMapping(value = "/groupmanager", method = RequestMethod.GET) public ModelAndView groupedit(HttpServletRequest request, Integer type) { ModelAndView mv = new ModelAndView("/reportconfig/groupManager"); List<Group> list = reportConfigService.getGroupById(null); List<AreaBean> unlist = reportConfigService.getNotInGroupArea(); int len = 0; for(int i=0;i<list.size();i++){ Group group = list.get(i); if(i == 0){ len = ExcelUtil.getStrLength(group.getGroupname()); }else{ if(len < ExcelUtil.getStrLength(group.getGroupname())){ len = ExcelUtil.getStrLength(group.getGroupname()); } } } mv.addObject("len", len); mv.addObject("groups", list); mv.addObject("unlist", unlist); mv.addObject("type", type); return mv; } @RequestMapping(value = "/guishugroup", method = RequestMethod.POST) public @ResponseBody Map<String, Integer> groupGuishu(HttpServletRequest request, String groups) { Map<String, Integer> map = new HashMap<String, Integer>(); int msg = 0; try { reportConfigService.updateGuishu(groups); msg = 1; } catch (Exception e) { logger.error("", e); msg = 0; } map.put("msg", msg); return map; } /** * 添加 * * @param request * @return */ @RequestMapping(value = "/addgroup", method = RequestMethod.GET) public String groupAdd(HttpServletRequest request) { return "/reportconfig/addGroup"; } @RequestMapping(value = "/addgroup", method = RequestMethod.POST) public @ResponseBody Map<String, Integer> groupAdd(HttpServletRequest request, String groupname) { Map<String, Integer> map = new HashMap<String, Integer>(); int groupid = reportConfigService.getGroupSeq(); int msg = reportConfigService.addGroup(groupid, groupname); map.put("groupid", groupid); map.put("msg", msg); return map; } /** * 删除分公司 * * @param request * @param ids * @return */ @RequestMapping(value = "/deletegroup", method = RequestMethod.POST) public @ResponseBody Map<String, Integer> groupDelete(HttpServletRequest request, String ids) { Map<String, Integer> map = new HashMap<String, Integer>(); int msg = 0; try { reportConfigService.deleteGroup(ids); msg = 1; } catch (Exception e) { logger.error("", e); msg = 0; } map.put("msg", msg); return map; } /** * 修改分公司 * * @param request * @param groups * @return */ @RequestMapping(value = "/updategroup", method = RequestMethod.POST) public @ResponseBody Map<String, Integer> updateGroup(HttpServletRequest request, String groups) { Map<String, Integer> map = new HashMap<String, Integer>(); int msg = 0; try { reportConfigService.editGroup(groups); msg = 1; } catch (Exception e) { logger.error("", e); msg = 0; } map.put("msg", msg); return map; } /** * 质量报表配置 * * @param request * @param groups * @return */ @RequestMapping(value = "/qualityconfig", method = RequestMethod.GET) public ModelAndView qualityConfig(HttpServletRequest request) { ModelAndView mv = new ModelAndView("/reportconfig/qualityConfig"); List<Group> list = reportConfigService .getGroupAndQualityConfigRelationl(); List<QualityBasicConfig> basics = reportConfigService .getQualityBasicConfig(); mv.addObject("list", list); mv.addObject("basics", basics); return mv; } @RequestMapping(value = "/updatestep", method = RequestMethod.POST) public @ResponseBody Map<String, Integer> updateStep(HttpServletRequest request, String groups) { Map<String, Integer> map = new HashMap<String, Integer>(); int msg = 0; try { reportConfigService.updateStep(groups); msg = 1; } catch (Exception e) { logger.error("", e); msg = 0; } map.put("msg", msg); return map; } /** * 判断公司名称是否重复 * * @param groupname * @return */ @RequestMapping(value = "/isExsit", method = RequestMethod.POST) public @ResponseBody boolean isExsit(String groupname) { boolean bool = this.reportConfigService.isExsit(groupname); return !bool; } } <file_sep>/src/main/webapp/js/workorder/saveAll.js $(function(){ var num = 0; $("#saveAll").click(function(){ //防止快速点击递交多次 if(num==0){ num++; if(isChange>0){ //阈值验证 if(rateAndIntegrationValidate()){ isColorChange(); $("#saveAllForm").ajaxForm({ url: contextPath + "/rateconfig/saveAll", beforeSubmit:function(){ if(!$('#saveAllForm').form('validate')){ $.messager.alert("提示","数值部分格式不正确,请检查","success"); num = 0; return false; } return true; }, success:function(data){ num = 0; if(data.msg==0){ $.messager.alert("提示","保存成功","success",function(){ window.location.href = window.location.href; }); }else if(data.msg==1){ $.messager.alert("提示","颜色保存时失败","error"); }else if(data.msg==2){ $.messager.alert("提示","指标阈值保存时失败","error"); }else if(data.msg==3){ $.messager.alert("提示","综合阈值保存时失败","error"); }else{ $.messager.alert("提示","保存失败","error"); } } }); $("#saveAllForm").submit(); }else{ num = 0; } }else{ $.messager.alert("提示","没有数据变动","success"); num = 0; } } }); }); /** * 颜色是否更新 */ function isColorChange(){ var colors = $("#colorUL>li").find("input[name='colors']"); var colorChangein = $("#colorChangein"); for(var i=0,len=colors.length; i<len; i++){ var color = $(colors[i]); if(color.attr("oldval") != color.val()){ colorChangein.val(1); break; } } } /** * 指标阈值和综合阈值验证 */ function rateAndIntegrationValidate(){ if(!$('#saveAllForm').form('validate')){ return false; } //指标阈值验证 if(!validate()){ return false; } //综合阈值 if(!rankCode()){ return false; }else if(!evaluateCode()){ return false; }else if(!validateself()){ return false; }else if(!validateIntervalIntegration()){ return false; } return true; } /** *悬浮按钮 */ /*function scroll(p){ var d = document,w = window,o = d.getElementById(p.id),ie6 = /msie 6/i.test(navigator.userAgent); if(o){ o.style.cssText +=";position:"+(p.f&&!ie6?'fixed':'absolute')+";"+(p.r?'right':"right")+":50px;"+(p.t!=undefined?'bottom:'+p.t+'px':'top:0'); if(!p.f||ie6){ -function(){ var t = 500,st = d.documentElement.scrollTop||d.body.scrollTop,c; c = st - o.offsetTop + (p.t!=undefined?p.t:(w.innerHeight||d.documentElement.clientHeight)-o.offsetHeight);//如果你是html 4.01请改成d.body,这里不处理以减少代码 c!=0&&(o.style.top = (o.offsetTop + Math.ceil(Math.abs(c)/10)*(c<0?-1:1))-3 + 'px',t=10); setTimeout(arguments.callee,t) }() } } } scroll({ id:'saveButton' });*/ /** *错误单元格背景标红,3秒后移除 */ function addWrong(a,b){ if(a!=null){ $("#"+a).addClass("wrongRed"); setTimeout(function(){ $("#"+a).removeClass("wrongRed"); },3000 ); } if(b!=null){ $("#"+b).addClass("wrongRed"); setTimeout(function(){ $("#"+b).removeClass("wrongRed"); },3000 ); } } /** *根据偏移值移动下拉条 **/ function moveScroll(id){ //判断leng>0时候含有该元素 //var t = ($("#rateDom").has($("#"+id))).length; var centerDom = document.getElementById(id); var oRect = centerDom.getBoundingClientRect(); //获取可视窗口高度居中 var height = (document.documentElement.clientHeight)/2; //滚动条位置 var currScrollTop = document.documentElement.clientHight; var val; //单元格在页面可视上方以外情况 if(oRect.top<=0){ val = -oRect.top+height; document.documentElement.scrollTop = document.documentElement.scrollTop-val; } //单元格在页面可视窗口中上半部的情况 else if(oRect.top>0&oRect.top<=height){ val =height-oRect.top; document.documentElement.scrollTop = document.documentElement.scrollTop-val; } //单元格在页面可视窗口中下半部的情况 else if(oRect.top>0&oRect.top<=height*2){ val =height-oRect.top; document.documentElement.scrollTop = document.documentElement.scrollTop-val; } //单元格在页面可视窗口下方以外情况 else if(oRect.top>0&oRect.top>height*2){ val =oRect.top-height; document.documentElement.scrollTop = document.documentElement.scrollTop+val; } }<file_sep>/src/main/java/com/complaint/service/GisgradExcelDownLoadService.java package com.complaint.service; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.complaint.action.vo.CellVo; import com.complaint.action.vo.VoBean; import com.complaint.dao.BaseStationDao; import com.complaint.model.Gisgrad; import com.complaint.model.GwCasCell; import com.complaint.model.ReportCells; import com.complaint.utils.Constant; import com.complaint.utils.ExcelUtil; @Service("gisgradExcelDownLoadService") public class GisgradExcelDownLoadService { @Autowired private BaseStationService baseStationService; @Autowired private BaseStationDao baseStationDao; private static final Logger logger = LoggerFactory.getLogger(GisgradExcelDownLoadService.class); private static final int EXCELNUM=10000; /** * 创建Excel表格 * * @param gisgrads */ public void createExcel(List<Gisgrad> gisgrads, String filePath,VoBean vo) { // 创建excel和第一页 Workbook wb = new SXSSFWorkbook(100); int dex=gisgrads.size()/EXCELNUM; if(dex==0){dex+=1;} if(gisgrads.size()/EXCELNUM>0&&gisgrads.size()%EXCELNUM>0){dex+=1;} Sheet sheet = null; for(int k=0;k<dex;k++){ sheet = wb.createSheet("地图评价报表"+k); /* ----------------第一行设计列名----------------------- */ Row rowTop = null; if (sheet.getRow(0) != null) { rowTop = sheet.getRow(0); } else { rowTop = sheet.createRow(0); } CellStyle styleTop = getNormalStyle(wb, "#00ccFF"); //1开始时间 Cell stTop = rowTop.createCell(0); stTop.setCellValue("开始时间"); stTop.setCellStyle(styleTop); //2结束时间 Cell endTop = rowTop.createCell(1); endTop.setCellValue("结束时间"); endTop.setCellStyle(styleTop); //3时间类型 Cell timesTop = rowTop.createCell(2); timesTop.setCellValue("时间类型"); timesTop.setCellStyle(styleTop); // 第4列,区域 Cell areaTop = rowTop.createCell(3); areaTop.setCellValue("区域"); areaTop.setCellStyle(styleTop); // 第5列,室内外,inside Cell cellInsideTop = rowTop.createCell(4); cellInsideTop.setCellValue("室内/室外"); cellInsideTop.setCellStyle(styleTop); // 第6列 ,工间,ser Cell cellSerTop = rowTop.createCell(5); cellSerTop.setCellValue("工单号"); cellSerTop.setCellStyle(styleTop); // 第7列 ,投诉文件名 Cell flowidTop = rowTop.createCell(6); flowidTop.setCellValue("测试文件名"); flowidTop.setCellStyle(styleTop); //第8列 ,投诉类型 Cell workTop = rowTop.createCell(7); workTop.setCellValue("投诉类型"); workTop.setCellStyle(styleTop); //第9列 ,投诉电话 Cell phoneTop = rowTop.createCell(8); phoneTop.setCellValue("投诉电话"); phoneTop.setCellStyle(styleTop); // 第10列 ,受理路径,ser Cell pathTop = rowTop.createCell(9); pathTop.setCellValue("受理路径"); pathTop.setCellStyle(styleTop); // 第11列,网络 Cell cellNetTop = rowTop.createCell(10); cellNetTop.setCellValue("网络"); cellNetTop.setCellStyle(styleTop); // 第12列,测试方式 Cell netTypeTop = rowTop.createCell(11); netTypeTop.setCellValue("测试方式"); netTypeTop.setCellStyle(styleTop); // 第13列,业务类型 Cell typeTop = rowTop.createCell(12); typeTop.setCellValue("业务类型"); typeTop.setCellStyle(styleTop); // 第14列,3G网络占比 Cell G3Top = rowTop.createCell(13); G3Top.setCellValue("3G网络占比"); G3Top.setCellStyle(styleTop); // 第15列,2G网络占比 Cell G2Top = rowTop.createCell(14); G2Top.setCellValue("2G网络占比"); G2Top.setCellStyle(styleTop); // 第16列,2G网络占比 Cell nosTop = rowTop.createCell(15); nosTop.setCellValue("脱网率"); nosTop.setCellStyle(styleTop); // 第17列,指标等级,rscp Cell cellRscpTop = rowTop.createCell(16); cellRscpTop.setCellValue("Rscp"); cellRscpTop.setCellStyle(styleTop); // 第18列,指标等级,ecno Cell cellEcnoTop = rowTop.createCell(17); cellEcnoTop.setCellValue("Ec/No"); cellEcnoTop.setCellStyle(styleTop); // 第19列,指标等级,tx Cell cellTxTop = rowTop.createCell(18); cellTxTop.setCellValue("TxPower"); cellTxTop.setCellStyle(styleTop); // 第20列,指标等级,fu Cell cellFuTop = rowTop.createCell(19); cellFuTop.setCellValue("FtpUp"); cellFuTop.setCellStyle(styleTop); // 第21列,指标等级,fd Cell cellFdTop = rowTop.createCell(20); cellFdTop.setCellValue("FtpDown"); cellFdTop.setCellStyle(styleTop); // 第22列,指标等级,rx Cell cellRxTop = rowTop.createCell(21); cellRxTop.setCellValue("RxLev"); cellRxTop.setCellStyle(styleTop); // 第23列,指标等级,rq Cell cellRqTop = rowTop.createCell(22); cellRqTop.setCellValue("Rxqual"); cellRqTop.setCellStyle(styleTop); // 第23列,指标等级,ci Cell cellCiTop = rowTop.createCell(23); cellCiTop.setCellValue("C/I"); cellCiTop.setCellStyle(styleTop); // 第24列,真正等级如:优+,优- Cell cellrealgradTop = rowTop.createCell(24); cellrealgradTop.setCellValue("综合评价"); cellrealgradTop.setCellStyle(styleTop); // 第25列,场景 Cell secnTop = rowTop.createCell(25); secnTop.setCellValue("场景"); secnTop.setCellStyle(styleTop); // 第26列,接单时间 Cell jtimeTop = rowTop.createCell(26); jtimeTop.setCellValue("接单时间"); jtimeTop.setCellStyle(styleTop); // 第27列,测试时间 Cell testTop = rowTop.createCell(27); testTop.setCellValue("测试时间"); testTop.setCellStyle(styleTop); // 第28列,经度 Cell lngTop = rowTop.createCell(28); lngTop.setCellValue("经度"); lngTop.setCellStyle(styleTop); // 第29列,纬度 Cell latTop = rowTop.createCell(29); latTop.setCellValue("纬度"); latTop.setCellStyle(styleTop); // 第30列,地址,add Cell cellAddTop = rowTop.createCell(30); cellAddTop.setCellValue("地址"); cellAddTop.setCellStyle(styleTop); // 第31列,任务类型 Cell jobTop = rowTop.createCell(31); jobTop.setCellValue("任务类型"); jobTop.setCellStyle(styleTop); // 第32列,测试总数 Cell sumTop = rowTop.createCell(32); sumTop.setCellValue("测试log的点数"); sumTop.setCellStyle(styleTop); // 使单元格自动适应内容长度 for (int i = 0; i < 33; i++) { sheet.autoSizeColumn(i, true); } /* ----------------进行内容填充----------------------- */ // 当第i行时,没有行就创建,有就直接使用 int num=(k+1)*EXCELNUM; if(num>gisgrads.size()){num=gisgrads.size();} for (int i = k*EXCELNUM; i < num; i++) { Row row = null; if (sheet.getRow(i%EXCELNUM + 1) != null) { row = sheet.getRow(i%EXCELNUM + 1); } else { row = sheet.createRow(i%EXCELNUM + 1); } // 更具颜色生成一般单元格样式 CellStyle style = getBodyStyle(wb, gisgrads.get(i).getColor()); // 对该行单元格内容填充 // 第1列,开始时间 Cell cellstime = row.createCell(0); cellstime.setCellValue(vo.getStartTime()==null?"":vo.getStartTime()); cellstime.setCellStyle(style); // 第2列,结束时间 Cell cellend = row.createCell(1); cellend.setCellValue(vo.getEndTime()==null?"":vo.getEndTime()); cellend.setCellStyle(style); // 第3列,时间类型 String timetype=""; if(vo!=null&&vo.getDatatype().equals("1"))timetype="测试时间"; if(vo!=null&&vo.getDatatype().equals("2"))timetype="接单时间"; Cell celltimeType = row.createCell(2); celltimeType.setCellValue(timetype); celltimeType.setCellStyle(style); // 第4列,区域 String area = ""; if (gisgrads.get(i).getArea() != null) { area = gisgrads.get(i).getArea(); } Cell cellarea = row.createCell(3); cellarea.setCellValue(area); cellarea.setCellStyle(style); // 第5列,室内外,inside String inside = ""; if (gisgrads.get(i).getInside().equals("0")) { inside = "室外"; } else if (gisgrads.get(i).getInside().equals("1")) { inside = "室内"; } Cell cellInside = row.createCell(4); cellInside.setCellValue(inside); cellInside.setCellStyle(style); // 第6列 ,工单,ser Cell cellSer = row.createCell(5); cellSer.setCellValue(gisgrads.get(i).getSer()==null?"":gisgrads.get(i).getSer()); cellSer.setCellStyle(style); // 第7列 ,流水 Cell cellflowid = row.createCell(6); String flowid=gisgrads.get(i).getSer(); if(gisgrads.get(i).getFlowid()!=null){ flowid+="-"+gisgrads.get(i).getFlowid().substring(0,8); flowid+="-"+gisgrads.get(i).getFlowid().substring(8,14); } cellflowid.setCellValue(flowid); cellflowid.setCellStyle(style); // 第8列 ,投诉网络 Cell workphone = row.createCell(7); workphone.setCellValue(gisgrads.get(i).getNetwork()==null?"":gisgrads.get(i).getNetwork()); workphone.setCellStyle(style); // 第9列 ,投诉电话 Cell cellphone = row.createCell(8); cellphone.setCellValue(gisgrads.get(i).getPhone()==null?"":gisgrads.get(i).getPhone()); cellphone.setCellStyle(style); // 第10列 ,受理路径 Cell cellpath = row.createCell(9); cellpath.setCellValue(gisgrads.get(i).getPath()==null?"":gisgrads.get(i).getPath()); cellpath.setCellStyle(style); // 第11列,网络制式 String netType = ""; if (gisgrads.get(i).getNet().equals("1")||gisgrads.get(i).getNet().equals("4")) { netType = "GSM"; } else if (gisgrads.get(i).getNet().equals("2")||gisgrads.get(i).getNet().equals("3")) { netType = "WCDMA"; } Cell cellNet = row.createCell(10); cellNet.setCellValue(netType); cellNet.setCellStyle(style); // 第12列,测试网络 String testnet = ""; if (gisgrads.get(i).getNet().equals("1")) { testnet = "GSM锁频"; } else if (gisgrads.get(i).getNet().equals("3")||gisgrads.get(i).getNet().equals("4")) { testnet = "WCDMA自由模式"; } else if (gisgrads.get(i).getNet().equals("2")) { testnet = "WCDMA锁频"; } Cell cellNettype = row.createCell(11); cellNettype.setCellValue(testnet); cellNettype.setCellStyle(style); // 第13列,业务类型 String testtype = ""; if (gisgrads.get(i).getType() != null) { if (gisgrads.get(i).getType().equals("1")) testtype = "IDLE"; if (gisgrads.get(i).getType().equals("2")) {testtype = "语音"; if (gisgrads.get(i).getCall_type() == 1) { testtype+= "短呼"; } else if (gisgrads.get(i).getCall_type() == 2) { testtype += "长呼"; } } if (gisgrads.get(i).getType().equals("3")){ testtype = "数据"; if (gisgrads.get(i).getFtp_type() == 1) { testtype += "上行"; } else if (gisgrads.get(i).getFtp_type()== 2) { testtype += "下行"; } } } Cell celltype = row.createCell(12); celltype.setCellValue(testtype); celltype.setCellStyle(style); //14 3G占比 Cell cellg3 = row.createCell(13); cellg3.setCellValue(gisgrads.get(i).getPocent3()+"%"); cellg3.setCellStyle(style); //15 2G占比 Cell cellg2 = row.createCell(14); cellg2.setCellValue(gisgrads.get(i).getPocent2()+"%"); cellg2.setCellStyle(style); //16 脱网占比 Cell cellgtalk = row.createCell(15); cellgtalk.setCellValue(gisgrads.get(i).getTalkaround()+"%"); cellgtalk.setCellStyle(style); // 第17列,指标等级,rscp String Rscp = ""; if (gisgrads.get(i).getRscp() != null) { Rscp = gisgrads.get(i).getRscp(); } Cell cellRscp = row.createCell(16); cellRscp.setCellValue(Rscp); cellRscp.setCellStyle(style); // 第18列,指标等级,ecno String ecno = ""; if (gisgrads.get(i).getEcno() != null) { ecno = gisgrads.get(i).getEcno(); } Cell cellEcno = row.createCell(17); cellEcno.setCellValue(ecno); cellEcno.setCellStyle(style); // 第19列,指标等级,tx String tx = ""; if (gisgrads.get(i).getTx() != null) { tx = gisgrads.get(i).getTx(); } Cell cellTx = row.createCell(18); cellTx.setCellValue(tx); cellTx.setCellStyle(style); // 第20列,指标等级,fu String fu = ""; if (gisgrads.get(i).getFu() != null) { fu = gisgrads.get(i).getFu(); } Cell cellFu = row.createCell(19); cellFu.setCellValue(fu); cellFu.setCellStyle(style); // 第21列,指标等级,fd String fd = ""; if (gisgrads.get(i).getFd() != null) { fd = gisgrads.get(i).getFd(); } Cell cellFd = row.createCell(20); cellFd.setCellValue(fd); cellFd.setCellStyle(style); // 第22列,指标等级,rx String rx = ""; if (gisgrads.get(i).getRx() != null) { rx = gisgrads.get(i).getRx(); } Cell cellRx = row.createCell(21); cellRx.setCellValue(rx); cellRx.setCellStyle(style); // 第23列,指标等级,rq String rq = ""; if (gisgrads.get(i).getRq() != null) { rq = gisgrads.get(i).getRq(); } Cell cellRq = row.createCell(22); cellRq.setCellValue(rq); cellRq.setCellStyle(style); // 第24列,指标等级,ci String ci = ""; if (gisgrads.get(i).getCi() != null) { ci = gisgrads.get(i).getCi(); } Cell cellCi = row.createCell(23); cellCi.setCellValue(ci); cellCi.setCellStyle(style); // 第25列,真正等级如:优+,优- Cell cellrealgrad = row.createCell(24); cellrealgrad.setCellValue(gisgrads.get(i).getRealgrad()==null?"":gisgrads.get(i).getRealgrad()); cellrealgrad.setCellStyle(style); // 第26列,场景 String sen = ""; if (gisgrads.get(i).getSence() != null) { sen = gisgrads.get(i).getSence(); } Cell cellSen = row.createCell(25); cellSen.setCellValue(sen); cellSen.setCellStyle(style); // 第27列,接单时间 String jtime = ""; if (gisgrads.get(i).getJtime()!= null&&!gisgrads.get(i).getJtime().equals("null")) { jtime = gisgrads.get(i).getJtime(); } Cell celljtime = row.createCell(26); celljtime.setCellValue(jtime); celljtime.setCellStyle(style); // 第28列,测试时间 String testtime = ""; if (gisgrads.get(i).getTime() != null&&!gisgrads.get(i).getTime().equals("null")) { testtime = gisgrads.get(i).getTime(); } Cell celltime = row.createCell(27); celltime.setCellValue(testtime); celltime.setCellStyle(style); // 第29列,经度 Cell celllng = row.createCell(28); celllng.setCellValue(gisgrads.get(i).getLng()==null?0:gisgrads.get(i).getLng()); celllng.setCellStyle(style); // 第30列,纬度 Cell celllat = row.createCell(29); celllat.setCellValue(gisgrads.get(i).getLat()==null?0:gisgrads.get(i).getLat()); celllat.setCellStyle(style); // 第31列,地址,add Cell cellAdd = row.createCell(30); cellAdd.setCellValue(gisgrads.get(i).getAdd()==null?"":gisgrads.get(i).getAdd()); cellAdd.setCellStyle(style); // 第32列,任务类型 Cell celljob = row.createCell(31); celljob.setCellValue("投诉工单"); celljob.setCellStyle(style); // 第33列,测试总数 Cell sumjob = row.createCell(32); sumjob.setCellValue(gisgrads.get(i).getSumc()==null?"":gisgrads.get(i).getSumc()); sumjob.setCellStyle(style); } } try { // 获取一个输出流 FileOutputStream fileOut = new FileOutputStream(filePath); // 生成Excel wb.write(fileOut); // 关闭流 fileOut.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 创建Excel一般样式 */ public CellStyle getNormalStyle(Workbook wb, String bgcolor) { CellStyle style = wb.createCellStyle(); DataFormat format = wb.createDataFormat(); // 加边框线 style.setBorderBottom(CellStyle.BORDER_THIN);// 下方加边框 style.setBottomBorderColor(IndexedColors.BLACK.getIndex());// 下方边框样式 style.setBorderLeft(CellStyle.BORDER_THIN);// 左方加边框 style.setLeftBorderColor(IndexedColors.BLACK.getIndex());// 左方边框样式 style.setBorderRight(CellStyle.BORDER_THIN);// 右方加边框 style.setRightBorderColor(IndexedColors.BLACK.getIndex());// 右方边框样式 style.setBorderTop(CellStyle.BORDER_THIN);// 上方加边框 style.setTopBorderColor(IndexedColors.BLACK.getIndex());// 上方边框样式 // 设置颜色 // 16进制颜色转化成RGB // int red = Integer.valueOf(bgcolor.substring(1, 3),16); // int green = Integer.valueOf(bgcolor.substring(3, 5),16); // int blue = Integer.valueOf(bgcolor.substring(5, 7),16); // style.setFillForegroundColor(new XSSFColor(new Color(red, green, // blue)));// 设置前端颜色 // style.setFillPattern(CellStyle.SOLID_FOREGROUND);// 设置填充模式 // // 对齐方式 style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中 // 字体样式 Font font = wb.createFont();// 创建字体对象 font.setFontHeightInPoints((short) 15);// 设置字体大小 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 设置粗体 font.setFontName("宋体");// 设置为黑体字 style.setFont(font);// 将字体加入到样式对象 style.setDataFormat(format.getFormat("@")); return style; } /** * 创建Excel正文样式 */ public CellStyle getBodyStyle(Workbook wb, String bgcolor) { CellStyle style = wb.createCellStyle(); DataFormat format = wb.createDataFormat(); // 加边框线 style.setBorderBottom(CellStyle.BORDER_THIN);// 下方加边框 style.setBottomBorderColor(IndexedColors.BLACK.getIndex());// 下方边框样式 style.setBorderLeft(CellStyle.BORDER_THIN);// 左方加边框 style.setLeftBorderColor(IndexedColors.BLACK.getIndex());// 左方边框样式 style.setBorderRight(CellStyle.BORDER_THIN);// 右方加边框 style.setRightBorderColor(IndexedColors.BLACK.getIndex());// 右方边框样式 style.setBorderTop(CellStyle.BORDER_THIN);// 上方加边框 style.setTopBorderColor(IndexedColors.BLACK.getIndex());// 上方边框样式 // 设置颜色 // 16进制颜色转化成RGB // int red = Integer.valueOf(bgcolor.substring(1, 3),16); // int green = Integer.valueOf(bgcolor.substring(3, 5),16); // int blue = Integer.valueOf(bgcolor.substring(5, 7),16); // style.setFillForegroundColor(new XSSFColor(new Color(red, green, // blue)));// 设置前端颜色 // style.setFillPattern(CellStyle.SOLID_FOREGROUND);// 设置填充模式 // // 对齐方式 style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中 // 字体样式 Font font = wb.createFont();// 创建字体对象 font.setFontHeightInPoints((short) 12);// 设置字体大小 //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 设置粗体 font.setFontName("宋体");// 设置为黑体字 style.setFont(font);// 将字体加入到样式对象 style.setDataFormat(format.getFormat("@")); return style; } /*** * 创建小区信息excel * * @param cells * @param filePath */ public void createNearCellInfoExcel(List<GwCasCell> cells, String filePath) { Workbook wb = new SXSSFWorkbook(100); Sheet sheet = wb.createSheet("小区信息报表"); Row topRow = sheet.createRow(0); // 标题样式 CellStyle topStyle = getNormalStyle(wb, "#00ccFF"); int count = 0; // 创建标题 createTitle(topRow, topStyle, "城市名称", count ++); createTitle(topRow, topStyle, "行政区域", count ++); createTitle(topRow, topStyle, "区域id", count ++); createTitle(topRow, topStyle, "小区cid", count ++); createTitle(topRow, topStyle, "基站id", count ++); createTitle(topRow, topStyle, "基站名称", count ++); createTitle(topRow, topStyle, "小区名称", count ++); createTitle(topRow, topStyle, "经度", count ++); createTitle(topRow, topStyle, "纬度", count ++); createTitle(topRow, topStyle, "psc/bcch", count ++); createTitle(topRow, topStyle, "网络模式", count ++); createTitle(topRow, topStyle, "室内外", count ++); createTitle(topRow, topStyle, "天线类型", count ++); createTitle(topRow, topStyle, "天线方位角", count ++); createTitle(topRow, topStyle, "天线高度", count ++); createTitle(topRow, topStyle, "天线电子倾角", count ++); createTitle(topRow, topStyle, "天线机械倾角", count ++); createTitle(topRow, topStyle, "共用天线", count ++); createTitle(topRow, topStyle, "基站站址", count ++); createTitle(topRow, topStyle, "海拔高度", count ++); createTitle(topRow, topStyle, "设备厂商", count ++); createTitle(topRow, topStyle, "塔桅类型", count ++); createTitle(topRow, topStyle, "设备类型", count ++); createTitle(topRow, topStyle, "基站配置", count ++); createTitle(topRow, topStyle, "工程进展", count ++); createTitle(topRow, topStyle, "覆盖范围", count ++); createTitle(topRow, topStyle, "覆盖类型", count ++); createTitle(topRow, topStyle, "是否rru小区", count ++); createTitle(topRow, topStyle, "小区编号", count ++); createTitle(topRow, topStyle, "直放站数量", count ++); createTitle(topRow, topStyle, "共天馈小区", count ++); createTitle(topRow, topStyle, "共天馈属性", count ++); createTitle(topRow, topStyle, "共站名称", count ++); createTitle(topRow, topStyle, "共站属性", count ++); createTitle(topRow, topStyle, "网管运行状态", count ++); createTitle(topRow, topStyle, "行政区域类型", count ++); createTitle(topRow, topStyle, "上行频点", count ++); createTitle(topRow, topStyle, "下行频点", count ++); createTitle(topRow, topStyle, "rnc名称", count ++); createTitle(topRow, topStyle, "网元类型", count ++); createTitle(topRow, topStyle, "天线发射功率", count ++); createTitle(topRow, topStyle, "下倾角", count ++); createTitle(topRow, topStyle, "是否可以电调", count ++); createTitle(topRow, topStyle, "基站类型", count ++); createTitle(topRow, topStyle, "rru数量", count ++); createTitle(topRow, topStyle, "逻辑小区级别", count ++); createTitle(topRow, topStyle, "扇区配置的无线容量", count ++); createTitle(topRow, topStyle, "e1数量", count ++); createTitle(topRow, topStyle, "fe数量", count ++); createTitle(topRow, topStyle, "传输方式", count ++); createTitle(topRow, topStyle, "重庆区域覆盖", count ++); createTitle(topRow, topStyle, "设计无线容量", count ++); createTitle(topRow, topStyle, "基站最大发射功率", count ++); createTitle(topRow, topStyle, "内置下倾角", count ++); createTitle(topRow, topStyle, "退服时间", count ++); createTitle(topRow, topStyle, "小区的最大下行发射功率", count ++); createTitle(topRow, topStyle, "一级场景", count ++); createTitle(topRow, topStyle, "二级场景", count ++); createTitle(topRow, topStyle, "是否城区", count ++); createTitle(topRow, topStyle, "是否支持hsdpa", count ++); createTitle(topRow, topStyle, "hsdpa功能状态", count ++); createTitle(topRow, topStyle, "hs-pdsch代码", count ++); createTitle(topRow, topStyle, "小区中广播信道的功率", count ++); createTitle(topRow, topStyle, "是否支持hsupa", count ++); createTitle(topRow, topStyle, "hsupa功能状态", count ++); createTitle(topRow, topStyle, "是否支持mbms", count ++); createTitle(topRow, topStyle, "mbms功能状态", count ++); createTitle(topRow, topStyle, "mich信道数", count ++); createTitle(topRow, topStyle, "sf=16的码字数", count ++); createTitle(topRow, topStyle, "sf=128的码字数", count ++); createTitle(topRow, topStyle, "e-agch信道的初始数目", count ++); createTitle(topRow, topStyle, "e-rgch/e-hich信道的初始数目", count ++); createTitle(topRow, topStyle, "pcpich信道最大发射功率", count ++); createTitle(topRow, topStyle, "pcpich信道最小发射功率", count ++); createTitle(topRow, topStyle, "小区中使用的主导频信道的功率", count ++); createTitle(topRow, topStyle, "小区中主同步信道的下行功率", count ++); createTitle(topRow, topStyle, "单载频容纳最大用户数", count ++); createTitle(topRow, topStyle, "小区配置的载频发射功率", count ++); createTitle(topRow, topStyle, "配置的上行ce容量", count ++); createTitle(topRow, topStyle, "配置的下行ce容量", count ++); createTitle(topRow, topStyle, "iub接口atm端口的配置带宽", count ++); createTitle(topRow, topStyle, "iub接口ip端口的配置带宽", count ++); createTitle(topRow, topStyle, "iu接口atm层配置带宽", count ++); createTitle(topRow, topStyle, "iu接口ip层配置带宽", count ++); createTitle(topRow, topStyle, "iur接口atm层配置带宽", count ++); createTitle(topRow, topStyle, "iur接口ip层配置带宽", count ++); createTitle(topRow, topStyle, "备注", count ++); createTitle(topRow, topStyle, "最后更新时间", count ++); createTitle(topRow, topStyle, "rac", count ++); createTitle(topRow, topStyle, "sac", count ++); createTitle(topRow, topStyle, "rnc编号", count ++); createTitle(topRow, topStyle, "基站编号", count ++); createTitle(topRow, topStyle, "ura编号", count ++); createTitle(topRow, topStyle, "是否安装塔顶放大器", count ++); createTitle(topRow, topStyle, "扇区编号", count ++); createTitle(topRow, topStyle, "入网时间", count ++); createTitle(topRow, topStyle, "vip站", count ++); createTitle(topRow, topStyle, "室内室外", count ++); createTitle(topRow, topStyle, "bsc名称", count ++); createTitle(topRow, topStyle, "省份", count ++); createTitle(topRow, topStyle, "基站设备型号", count ++); createTitle(topRow, topStyle, "机柜类型", count ++); createTitle(topRow, topStyle, "载波类型", count ++); createTitle(topRow, topStyle, "共用馈线", count ++); createTitle(topRow, topStyle, "共用平台", count ++); createTitle(topRow, topStyle, "小区频段", count ++); createTitle(topRow, topStyle, "小区标识", count ++); createTitle(topRow, topStyle, "小区bsic", count ++); createTitle(topRow, topStyle, "tch频点", count ++); createTitle(topRow, topStyle, "配置载频数", count ++); createTitle(topRow, topStyle, "可用载频数", count ++); createTitle(topRow, topStyle, "载频最大发射功率", count ++); createTitle(topRow, topStyle, "配置控制信道数", count ++); createTitle(topRow, topStyle, "配置业务信道数", count ++); createTitle(topRow, topStyle, "sdcch可用数", count ++); createTitle(topRow, topStyle, "天线俯仰角", count ++); createTitle(topRow, topStyle, "跳频模式", count ++); createTitle(topRow, topStyle, "是否开通半速率", count ++); createTitle(topRow, topStyle, "gprs开通情况", count ++); createTitle(topRow, topStyle, "edge开通情况", count ++); createTitle(topRow, topStyle, "增强全速率开通情况", count ++); createTitle(topRow, topStyle, "网络制式", count ++); /*createTitle(topRow, topStyle, "3G邻区1", count ++); createTitle(topRow, topStyle, "3G邻区2", count ++); createTitle(topRow, topStyle, "3G邻区3", count ++); createTitle(topRow, topStyle, "3G邻区4", count ++); createTitle(topRow, topStyle, "3G邻区5", count ++); createTitle(topRow, topStyle, "3G邻区6", count ++); createTitle(topRow, topStyle, "3G邻区7", count ++); createTitle(topRow, topStyle, "3G邻区8", count ++); createTitle(topRow, topStyle, "3G邻区9", count ++); createTitle(topRow, topStyle, "3G邻区10", count ++); createTitle(topRow, topStyle, "3G邻区11", count ++); createTitle(topRow, topStyle, "3G邻区12", count ++); createTitle(topRow, topStyle, "3G邻区13", count ++); createTitle(topRow, topStyle, "3G邻区14", count ++); createTitle(topRow, topStyle, "3G邻区15", count ++); createTitle(topRow, topStyle, "3G邻区16", count ++); createTitle(topRow, topStyle, "3G邻区17", count ++); createTitle(topRow, topStyle, "3G邻区18", count ++); createTitle(topRow, topStyle, "3G邻区19", count ++); createTitle(topRow, topStyle, "3G邻区20", count ++); createTitle(topRow, topStyle, "3G邻区21", count ++); createTitle(topRow, topStyle, "3G邻区22", count ++); createTitle(topRow, topStyle, "3G邻区23", count ++); createTitle(topRow, topStyle, "3G邻区24", count ++); createTitle(topRow, topStyle, "3G邻区25", count ++); createTitle(topRow, topStyle, "3G邻区26", count ++); createTitle(topRow, topStyle, "3G邻区27", count ++); createTitle(topRow, topStyle, "3G邻区28", count ++); createTitle(topRow, topStyle, "3G邻区29", count ++); createTitle(topRow, topStyle, "3G邻区30", count ++); createTitle(topRow, topStyle, "3G邻区31", count ++); createTitle(topRow, topStyle, "3G邻区32", count ++); createTitle(topRow, topStyle, "3G邻区33", count ++); createTitle(topRow, topStyle, "3G邻区34", count ++); createTitle(topRow, topStyle, "3G邻区35", count ++); createTitle(topRow, topStyle, "3G邻区36", count ++); createTitle(topRow, topStyle, "3G邻区37", count ++); createTitle(topRow, topStyle, "3G邻区38", count ++); createTitle(topRow, topStyle, "3G邻区39", count ++); createTitle(topRow, topStyle, "3G邻区40", count ++); createTitle(topRow, topStyle, "3G邻区41", count ++); createTitle(topRow, topStyle, "3G邻区42", count ++); createTitle(topRow, topStyle, "3G邻区43", count ++); createTitle(topRow, topStyle, "3G邻区44", count ++); createTitle(topRow, topStyle, "3G邻区45", count ++); createTitle(topRow, topStyle, "3G邻区46", count ++); createTitle(topRow, topStyle, "3G邻区47", count ++); createTitle(topRow, topStyle, "3G邻区48", count ++); createTitle(topRow, topStyle, "3G邻区49", count ++); createTitle(topRow, topStyle, "3G邻区50", count ++); createTitle(topRow, topStyle, "3G邻区51", count ++); createTitle(topRow, topStyle, "3G邻区52", count ++); createTitle(topRow, topStyle, "3G邻区53", count ++); createTitle(topRow, topStyle, "3G邻区54", count ++); createTitle(topRow, topStyle, "3G邻区55", count ++); createTitle(topRow, topStyle, "3G邻区56", count ++); createTitle(topRow, topStyle, "3G邻区57", count ++); createTitle(topRow, topStyle, "3G邻区58", count ++); createTitle(topRow, topStyle, "3G邻区59", count ++); createTitle(topRow, topStyle, "3G邻区60", count ++); createTitle(topRow, topStyle, "3G邻区61", count ++); createTitle(topRow, topStyle, "3G邻区62", count ++); createTitle(topRow, topStyle, "3G邻区63", count ++); createTitle(topRow, topStyle, "3G邻区64", count ++); createTitle(topRow, topStyle, "2G邻区1", count ++); createTitle(topRow, topStyle, "2G邻区2", count ++); createTitle(topRow, topStyle, "2G邻区3", count ++); createTitle(topRow, topStyle, "2G邻区4", count ++); createTitle(topRow, topStyle, "2G邻区5", count ++); createTitle(topRow, topStyle, "2G邻区6", count ++); createTitle(topRow, topStyle, "2G邻区7", count ++); createTitle(topRow, topStyle, "2G邻区8", count ++); createTitle(topRow, topStyle, "2G邻区9", count ++); createTitle(topRow, topStyle, "2G邻区10", count ++); createTitle(topRow, topStyle, "2G邻区11", count ++); createTitle(topRow, topStyle, "2G邻区12", count ++); createTitle(topRow, topStyle, "2G邻区13", count ++); createTitle(topRow, topStyle, "2G邻区14", count ++); createTitle(topRow, topStyle, "2G邻区15", count ++); createTitle(topRow, topStyle, "2G邻区16", count ++); createTitle(topRow, topStyle, "2G邻区17", count ++); createTitle(topRow, topStyle, "2G邻区18", count ++); createTitle(topRow, topStyle, "2G邻区19", count ++); createTitle(topRow, topStyle, "2G邻区20", count ++); createTitle(topRow, topStyle, "2G邻区21", count ++); createTitle(topRow, topStyle, "2G邻区22", count ++); createTitle(topRow, topStyle, "2G邻区23", count ++); createTitle(topRow, topStyle, "2G邻区24", count ++); createTitle(topRow, topStyle, "2G邻区25", count ++); createTitle(topRow, topStyle, "2G邻区26", count ++); createTitle(topRow, topStyle, "2G邻区27", count ++); createTitle(topRow, topStyle, "2G邻区28", count ++); createTitle(topRow, topStyle, "2G邻区29", count ++); createTitle(topRow, topStyle, "2G邻区30", count ++); createTitle(topRow, topStyle, "2G邻区31", count ++); createTitle(topRow, topStyle, "2G邻区32", count ++);*/ for(int i = 0; i < cells.size(); i ++){ setValue(i+1,cells.get(i),sheet); } // 使单元格自动适应内容长度 for (int i = 0; i < 122; i++) { sheet.autoSizeColumn(i, true); } try { // 获取一个输出流 FileOutputStream fileOut = new FileOutputStream(filePath); // 生成Excel wb.write(fileOut); // 关闭流 fileOut.close(); } catch (Exception e) { e.printStackTrace(); } } /*** * 创建小区信息excel * * @param cells * @param filePath */ public void createCellInfoExcel(CellVo vo,String filePath) { Workbook wb =new SXSSFWorkbook(100); //<<<<<<< .mine // if(index == 0){ // wb = new XSSFWorkbook(); // sheet = wb.createSheet("小区信息报表"); // XSSFRow topRow = sheet.createRow(0); // // 标题样式 // CellStyle topStyle = getNormalStyle(wb, "#00ccFF"); // int count = 0; // // 创建标题 // createTitle(topRow, topStyle, "城市名称", count ++); // createTitle(topRow, topStyle, "行政区域", count ++); // createTitle(topRow, topStyle, "区域id", count ++); // createTitle(topRow, topStyle, "小区cid", count ++); // createTitle(topRow, topStyle, "基站id", count ++); // createTitle(topRow, topStyle, "基站名称", count ++); // createTitle(topRow, topStyle, "小区名称", count ++); // createTitle(topRow, topStyle, "经度", count ++); // createTitle(topRow, topStyle, "纬度", count ++); // createTitle(topRow, topStyle, "psc/bcch", count ++); // createTitle(topRow, topStyle, "网络模式", count ++); // createTitle(topRow, topStyle, "室内外", count ++); // createTitle(topRow, topStyle, "天线类型", count ++); // createTitle(topRow, topStyle, "天线方位角", count ++); // createTitle(topRow, topStyle, "天线高度", count ++); // createTitle(topRow, topStyle, "天线电子倾角", count ++); // createTitle(topRow, topStyle, "天线机械倾角", count ++); // createTitle(topRow, topStyle, "共用天线", count ++); // createTitle(topRow, topStyle, "基站站址", count ++); // createTitle(topRow, topStyle, "海拔高度", count ++); // createTitle(topRow, topStyle, "设备厂商", count ++); // createTitle(topRow, topStyle, "塔桅类型", count ++); // createTitle(topRow, topStyle, "设备类型", count ++); // createTitle(topRow, topStyle, "基站配置", count ++); // createTitle(topRow, topStyle, "工程进展", count ++); // createTitle(topRow, topStyle, "覆盖范围", count ++); // createTitle(topRow, topStyle, "覆盖类型", count ++); // createTitle(topRow, topStyle, "是否rru小区", count ++); // createTitle(topRow, topStyle, "小区编号", count ++); // createTitle(topRow, topStyle, "直放站数量", count ++); // createTitle(topRow, topStyle, "共天馈小区", count ++); // createTitle(topRow, topStyle, "共天馈属性", count ++); // createTitle(topRow, topStyle, "共站名称", count ++); // createTitle(topRow, topStyle, "共站属性", count ++); // createTitle(topRow, topStyle, "网管运行状态", count ++); // createTitle(topRow, topStyle, "行政区域类型", count ++); // createTitle(topRow, topStyle, "上行频点", count ++); // createTitle(topRow, topStyle, "下行频点", count ++); // createTitle(topRow, topStyle, "rnc名称", count ++); // createTitle(topRow, topStyle, "网元类型", count ++); // createTitle(topRow, topStyle, "天线发射功率", count ++); // createTitle(topRow, topStyle, "下倾角", count ++); // createTitle(topRow, topStyle, "是否可以电调", count ++); // createTitle(topRow, topStyle, "基站类型", count ++); // createTitle(topRow, topStyle, "rru数量", count ++); // createTitle(topRow, topStyle, "逻辑小区级别", count ++); // createTitle(topRow, topStyle, "扇区配置的无线容量", count ++); // createTitle(topRow, topStyle, "e1数量", count ++); // createTitle(topRow, topStyle, "fe数量", count ++); // createTitle(topRow, topStyle, "传输方式", count ++); // createTitle(topRow, topStyle, "重庆区域覆盖", count ++); // createTitle(topRow, topStyle, "设计无线容量", count ++); // createTitle(topRow, topStyle, "基站最大发射功率", count ++); // createTitle(topRow, topStyle, "内置下倾角", count ++); // createTitle(topRow, topStyle, "退服时间", count ++); // createTitle(topRow, topStyle, "小区的最大下行发射功率", count ++); // createTitle(topRow, topStyle, "一级场景", count ++); // createTitle(topRow, topStyle, "二级场景", count ++); // createTitle(topRow, topStyle, "是否城区", count ++); // createTitle(topRow, topStyle, "是否支持hsdpa", count ++); // createTitle(topRow, topStyle, "hsdpa功能状态", count ++); // createTitle(topRow, topStyle, "hs-pdsch代码", count ++); // createTitle(topRow, topStyle, "小区中广播信道的功率", count ++); // createTitle(topRow, topStyle, "是否支持hsupa", count ++); // createTitle(topRow, topStyle, "hsupa功能状态", count ++); // createTitle(topRow, topStyle, "是否支持mbms", count ++); // createTitle(topRow, topStyle, "mbms功能状态", count ++); // createTitle(topRow, topStyle, "mich信道数", count ++); // createTitle(topRow, topStyle, "sf=16的码字数", count ++); // createTitle(topRow, topStyle, "sf=128的码字数", count ++); // createTitle(topRow, topStyle, "e-agch信道的初始数目", count ++); // createTitle(topRow, topStyle, "e-rgch/e-hich信道的初始数目", count ++); // createTitle(topRow, topStyle, "pcpich信道最大发射功率", count ++); // createTitle(topRow, topStyle, "pcpich信道最小发射功率", count ++); // createTitle(topRow, topStyle, "小区中使用的主导频信道的功率", count ++); // createTitle(topRow, topStyle, "小区中主同步信道的下行功率", count ++); // createTitle(topRow, topStyle, "单载频容纳最大用户数", count ++); // createTitle(topRow, topStyle, "小区配置的载频发射功率", count ++); // createTitle(topRow, topStyle, "配置的上行ce容量", count ++); // createTitle(topRow, topStyle, "配置的下行ce容量", count ++); // createTitle(topRow, topStyle, "iub接口atm端口的配置带宽", count ++); // createTitle(topRow, topStyle, "iub接口ip端口的配置带宽", count ++); // createTitle(topRow, topStyle, "iu接口atm层配置带宽", count ++); // createTitle(topRow, topStyle, "iu接口ip层配置带宽", count ++); // createTitle(topRow, topStyle, "iur接口atm层配置带宽", count ++); // createTitle(topRow, topStyle, "iur接口ip层配置带宽", count ++); // createTitle(topRow, topStyle, "备注", count ++); // createTitle(topRow, topStyle, "最后更新时间", count ++); // createTitle(topRow, topStyle, "rac", count ++); // createTitle(topRow, topStyle, "sac", count ++); // createTitle(topRow, topStyle, "rnc编号", count ++); // createTitle(topRow, topStyle, "基站编号", count ++); // createTitle(topRow, topStyle, "ura编号", count ++); // createTitle(topRow, topStyle, "是否安装塔顶放大器", count ++); // createTitle(topRow, topStyle, "扇区编号", count ++); // createTitle(topRow, topStyle, "入网时间", count ++); // createTitle(topRow, topStyle, "vip站", count ++); // createTitle(topRow, topStyle, "室内室外", count ++); // createTitle(topRow, topStyle, "bsc名称", count ++); // createTitle(topRow, topStyle, "省份", count ++); // createTitle(topRow, topStyle, "基站设备型号", count ++); // createTitle(topRow, topStyle, "机柜类型", count ++); // createTitle(topRow, topStyle, "载波类型", count ++); // createTitle(topRow, topStyle, "共用馈线", count ++); // createTitle(topRow, topStyle, "共用平台", count ++); // createTitle(topRow, topStyle, "小区频段", count ++); // createTitle(topRow, topStyle, "小区标识", count ++); // createTitle(topRow, topStyle, "小区bsic", count ++); // createTitle(topRow, topStyle, "tch频点", count ++); // createTitle(topRow, topStyle, "配置载频数", count ++); // createTitle(topRow, topStyle, "可用载频数", count ++); // createTitle(topRow, topStyle, "载频最大发射功率", count ++); // createTitle(topRow, topStyle, "配置控制信道数", count ++); // createTitle(topRow, topStyle, "配置业务信道数", count ++); // createTitle(topRow, topStyle, "sdcch可用数", count ++); // createTitle(topRow, topStyle, "天线俯仰角", count ++); // createTitle(topRow, topStyle, "跳频模式", count ++); // createTitle(topRow, topStyle, "是否开通半速率", count ++); // createTitle(topRow, topStyle, "gprs开通情况", count ++); // createTitle(topRow, topStyle, "edge开通情况", count ++); // createTitle(topRow, topStyle, "增强全速率开通情况", count ++); // createTitle(topRow, topStyle, "网络制式", count ++); // /*createTitle(topRow, topStyle, "3G邻区1", count ++); // createTitle(topRow, topStyle, "3G邻区2", count ++); // createTitle(topRow, topStyle, "3G邻区3", count ++); // createTitle(topRow, topStyle, "3G邻区4", count ++); // createTitle(topRow, topStyle, "3G邻区5", count ++); // createTitle(topRow, topStyle, "3G邻区6", count ++); // createTitle(topRow, topStyle, "3G邻区7", count ++); // createTitle(topRow, topStyle, "3G邻区8", count ++); // createTitle(topRow, topStyle, "3G邻区9", count ++); // createTitle(topRow, topStyle, "3G邻区10", count ++); // createTitle(topRow, topStyle, "3G邻区11", count ++); // createTitle(topRow, topStyle, "3G邻区12", count ++); // createTitle(topRow, topStyle, "3G邻区13", count ++); // createTitle(topRow, topStyle, "3G邻区14", count ++); // createTitle(topRow, topStyle, "3G邻区15", count ++); // createTitle(topRow, topStyle, "3G邻区16", count ++); // createTitle(topRow, topStyle, "3G邻区17", count ++); // createTitle(topRow, topStyle, "3G邻区18", count ++); // createTitle(topRow, topStyle, "3G邻区19", count ++); // createTitle(topRow, topStyle, "3G邻区20", count ++); // createTitle(topRow, topStyle, "3G邻区21", count ++); // createTitle(topRow, topStyle, "3G邻区22", count ++); // createTitle(topRow, topStyle, "3G邻区23", count ++); // createTitle(topRow, topStyle, "3G邻区24", count ++); // createTitle(topRow, topStyle, "3G邻区25", count ++); // createTitle(topRow, topStyle, "3G邻区26", count ++); // createTitle(topRow, topStyle, "3G邻区27", count ++); // createTitle(topRow, topStyle, "3G邻区28", count ++); // createTitle(topRow, topStyle, "3G邻区29", count ++); // createTitle(topRow, topStyle, "3G邻区30", count ++); // createTitle(topRow, topStyle, "3G邻区31", count ++); // createTitle(topRow, topStyle, "3G邻区32", count ++); // createTitle(topRow, topStyle, "3G邻区33", count ++); // createTitle(topRow, topStyle, "3G邻区34", count ++); // createTitle(topRow, topStyle, "3G邻区35", count ++); // createTitle(topRow, topStyle, "3G邻区36", count ++); // createTitle(topRow, topStyle, "3G邻区37", count ++); // createTitle(topRow, topStyle, "3G邻区38", count ++); // createTitle(topRow, topStyle, "3G邻区39", count ++); // createTitle(topRow, topStyle, "3G邻区40", count ++); // createTitle(topRow, topStyle, "3G邻区41", count ++); // createTitle(topRow, topStyle, "3G邻区42", count ++); // createTitle(topRow, topStyle, "3G邻区43", count ++); // createTitle(topRow, topStyle, "3G邻区44", count ++); // createTitle(topRow, topStyle, "3G邻区45", count ++); // createTitle(topRow, topStyle, "3G邻区46", count ++); // createTitle(topRow, topStyle, "3G邻区47", count ++); // createTitle(topRow, topStyle, "3G邻区48", count ++); // createTitle(topRow, topStyle, "3G邻区49", count ++); // createTitle(topRow, topStyle, "3G邻区50", count ++); // createTitle(topRow, topStyle, "3G邻区51", count ++); // createTitle(topRow, topStyle, "3G邻区52", count ++); // createTitle(topRow, topStyle, "3G邻区53", count ++); // createTitle(topRow, topStyle, "3G邻区54", count ++); // createTitle(topRow, topStyle, "3G邻区55", count ++); // createTitle(topRow, topStyle, "3G邻区56", count ++); // createTitle(topRow, topStyle, "3G邻区57", count ++); // createTitle(topRow, topStyle, "3G邻区58", count ++); // createTitle(topRow, topStyle, "3G邻区59", count ++); // createTitle(topRow, topStyle, "3G邻区60", count ++); // createTitle(topRow, topStyle, "3G邻区61", count ++); // createTitle(topRow, topStyle, "3G邻区62", count ++); // createTitle(topRow, topStyle, "3G邻区63", count ++); // createTitle(topRow, topStyle, "3G邻区64", count ++); // createTitle(topRow, topStyle, "2G邻区1", count ++); // createTitle(topRow, topStyle, "2G邻区2", count ++); // createTitle(topRow, topStyle, "2G邻区3", count ++); // createTitle(topRow, topStyle, "2G邻区4", count ++); // createTitle(topRow, topStyle, "2G邻区5", count ++); // createTitle(topRow, topStyle, "2G邻区6", count ++); // createTitle(topRow, topStyle, "2G邻区7", count ++); // createTitle(topRow, topStyle, "2G邻区8", count ++); // createTitle(topRow, topStyle, "2G邻区9", count ++); // createTitle(topRow, topStyle, "2G邻区10", count ++); // createTitle(topRow, topStyle, "2G邻区11", count ++); // createTitle(topRow, topStyle, "2G邻区12", count ++); // createTitle(topRow, topStyle, "2G邻区13", count ++); // createTitle(topRow, topStyle, "2G邻区14", count ++); // createTitle(topRow, topStyle, "2G邻区15", count ++); // createTitle(topRow, topStyle, "2G邻区16", count ++); // createTitle(topRow, topStyle, "2G邻区17", count ++); // createTitle(topRow, topStyle, "2G邻区18", count ++); // createTitle(topRow, topStyle, "2G邻区19", count ++); // createTitle(topRow, topStyle, "2G邻区20", count ++); // createTitle(topRow, topStyle, "2G邻区21", count ++); // createTitle(topRow, topStyle, "2G邻区22", count ++); // createTitle(topRow, topStyle, "2G邻区23", count ++); // createTitle(topRow, topStyle, "2G邻区24", count ++); // createTitle(topRow, topStyle, "2G邻区25", count ++); // createTitle(topRow, topStyle, "2G邻区26", count ++); // createTitle(topRow, topStyle, "2G邻区27", count ++); // createTitle(topRow, topStyle, "2G邻区28", count ++); // createTitle(topRow, topStyle, "2G邻区29", count ++); // createTitle(topRow, topStyle, "2G邻区30", count ++); // createTitle(topRow, topStyle, "2G邻区31", count ++); // createTitle(topRow, topStyle, "2G邻区32", count ++);*/ // }else{ // Long d1=new Date().getTime(); // FileInputStream fis = null; // try { // fis = new FileInputStream(filePath); // } catch (FileNotFoundException e) { // logger.error("Gis download when get Excel",e); //======= // 标题样式 CellStyle topStyle = getNormalStyle(wb, "#00ccFF"); Sheet sheet = null; List<GwCasCell> cells = null; //type 0 框选导出 1小区导出 2 邻区导出 int index =0;//每次开始写入行数 int num = baseStationService.getPage(vo); int nowR =0; if(vo.getReport_type() == 1){ for(int i = 0;i<num;i++){ if(nowR == 0){//当前行数为0就创建新页并创建titl sheet = wb.createSheet("小区信息报表"+(index/Constant.SHEET_ROW==0?1:index/Constant.SHEET_ROW+1)); Row topRow = sheet.createRow(0); getTitle(topRow,topStyle ,sheet); for (int j = 0; j < 122; j++) { sheet.autoSizeColumn(j, true); } nowR++; } cells = new ArrayList<GwCasCell>(); cells = baseStationService.getRegiondown(vo,filePath,i); for(int j = nowR; j < cells.size()+nowR; j++){ setValue(j,cells.get(j-nowR),sheet); } index =(i+1)*Constant.READ_ROW; nowR += Constant.READ_ROW; if((nowR-1)%Constant.SHEET_ROW ==0 && i !=0){ nowR =0; } } }else if(vo.getReport_type() == 0){ for(int i = 0;i<num;i++){ if(nowR == 0){//当前行数为0就创建新页并创建titl sheet = wb.createSheet("小区信息报表"+(index/Constant.SHEET_ROW==0?1:index/Constant.SHEET_ROW+1)); Row topRow = sheet.createRow(0); getTitle(topRow,topStyle ,sheet); for (int j = 0; j < 122; j++) { sheet.autoSizeColumn(j, true); } nowR++; } cells = new ArrayList<GwCasCell>(); cells = baseStationService.getRegiondownCell(vo,filePath ,i); for(int j = nowR; j < cells.size()+nowR; j++){ setValue(j,cells.get(j-nowR),sheet); } index =(i+1)*Constant.READ_ROW; nowR += Constant.READ_ROW; if((nowR-1)%Constant.SHEET_ROW ==0 && i !=0){ nowR =0; } } //System.out.println(new Date().getTime()-d1+"==========="+cells.size()); }else if(vo.getReport_type() == 2){ sheet = wb.createSheet("小区信息报表"); Row topRow = sheet.createRow(0); getTitle(topRow,topStyle ,sheet); for (int j = 0; j < 122; j++) { sheet.autoSizeColumn(j, true); } cells = baseStationService.getReportNearCell(vo); for(int j = index; j < cells.size()+index; j++){ GwCasCell gw = cells.get(j-index); setValue(j+1,cells.get(j-index),sheet); if(gw.getColor_type() != null && (gw.getColor_type().equals("0")||gw.getColor_type().equals("1")|| gw.getColor_type().equals("2")||gw.getColor_type().equals("3"))){ XSSFCellStyle style = ExcelUtil.setBackColorByCustom(wb, gw.getColor()); Row row = sheet.getRow(j+1); Cell cell = null; for(int k = 0;k < 122;k ++){ cell = row.getCell(k); cell.setCellStyle(style); } } } } //System.out.println(sheet+"========="); try { // 获取一个输出流 FileOutputStream fileOut = new FileOutputStream(filePath); // 生成Excel wb.write(fileOut); // 关闭流 fileOut.close(); } catch (Exception e) { e.printStackTrace(); } } /* * 创建标题 */ private void createTitle(Row topRow, CellStyle topStyle, String value, int index) { Cell cell = topRow.createCell(index); cell.setCellValue(value); cell.setCellStyle(topStyle); } /** * 单元格赋值 * @param rownum * @param data * @param sheet */ private void setValue(int rownum,GwCasCell data,Sheet sheet){ Row row = sheet.createRow(rownum); int count = 0; //城市名称 Cell cell1 = row.createCell(count++); cell1.setCellValue(data.getCityName()==null?"":data.getCityName()); //行政区域 Cell cell2 = row.createCell(count++); cell2.setCellValue(data.getAdminRegion()==null?"":data.getAdminRegion()); //区域id Cell cell3 = row.createCell(count++); cell3.setCellValue(data.getAreaId()==null?"":data.getAreaId().toString()); //小区cid Cell cell4 = row.createCell(count++); cell4.setCellValue(data.getCid()==null?"":data.getCid().toString()); //基站id Cell cell5 = row.createCell(count++); cell5.setCellValue(data.getBid()==null?"":data.getBid().toString()); //基站名称 Cell cell6 = row.createCell(count++); cell6.setCellValue(data.getBaseName()==null?"":data.getBaseName()); //小区名称 Cell cell7 = row.createCell(count++); cell7.setCellValue(data.getCellName()==null?"":data.getCellName()); //经度 Cell cell8 = row.createCell(count++); cell8.setCellValue(data.getLongitude()==null?"":data.getLongitude().toString()); //纬度 Cell cell9 = row.createCell(count++); cell9.setCellValue(data.getLatitude()==null?"":data.getLatitude().toString()); //扰码psc Cell cell10 = row.createCell(count++); cell10.setCellValue(data.getPsc().toString()==null?"":data.getPsc().toString()); //网络模式 Cell cell11 = row.createCell(count++); cell11.setCellValue(data.getModeType()==(short)0?"3G":"2G"); //室内外 Cell cell12 = row.createCell(count++); cell12.setCellValue(data.getIndoor()==(short)0?"室外":"室内"); //天线类型 Cell cell13 = row.createCell(count++); cell13.setCellValue(data.getAntType()==null?"":data.getAntType()); //天线方位角 Cell cell14 = row.createCell(count++); cell14.setCellValue(data.getAntAzimuth()==null?"":data.getAntAzimuth().toString()); //天线高度 Cell cell15 = row.createCell(count++); cell15.setCellValue(data.getAntHigh()==null?"":data.getAntHigh().toString()); //天线电子倾角 Cell cell16 = row.createCell(count++); cell16.setCellValue(data.getAntElectAngle()==null?"":data.getAntElectAngle().toString()); //天线机械倾角 Cell cell17 = row.createCell(count++); cell17.setCellValue(data.getAntMachAngle()==null?"":data.getAntMachAngle().toString()); //共用天线 Cell cell18 = row.createCell(count++); cell18.setCellValue(data.getSharedAnt()==null?"":data.getSharedAnt()); //基站站址 Cell cell19 = row.createCell(count++); cell19.setCellValue(data.getBaseAddress()==null?"":data.getBaseAddress()); //海拔高度 Cell cell20 = row.createCell(count++); cell20.setCellValue(data.getAltitude()==null?"":data.getAltitude().toString()); //设备厂商 Cell cell21 = row.createCell(count++); cell21.setCellValue(data.getDevVendor()==null?"":data.getDevVendor()); //塔桅类型 Cell cell22 = row.createCell(count++); cell22.setCellValue(data.getTowerMastType()==null?"":data.getTowerMastType()); //设备类型 Cell cell23 = row.createCell(count++); cell23.setCellValue(data.getDevType()==null?"":data.getDevType()); //基站配置 Cell cell24 = row.createCell(count++); cell24.setCellValue(data.getBaseConf()==null?"":data.getBaseConf()); //工程进展 Cell cell25 = row.createCell(count++); cell25.setCellValue(data.getProgress()==null?"":data.getProgress()); //覆盖范围 Cell cell26 = row.createCell(count++); cell26.setCellValue(data.getCoverRange()==null?"":data.getCoverRange()); //覆盖类型 Cell cell27 = row.createCell(count++); cell27.setCellValue(data.getCoverType()==null?"":data.getCoverType()); //是否rru小区 Cell cell28 = row.createCell(count++); cell28.setCellValue(data.getRruCellBool()==null?"":data.getRruCellBool()); //小区编号 Cell cell29 = row.createCell(count++); cell29.setCellValue(data.getCellId()==null?"":data.getCellId().toString()); //直放站数量 Cell cell30 = row.createCell(count++); cell30.setCellValue(data.getRepeaterCnt()==null?"":data.getRepeaterCnt().toString()); //共天馈小区 Cell cell31 = row.createCell(count++); cell31.setCellValue(data.getSharedAntCell()==null?"":data.getSharedAntCell()); //共天馈属性 Cell cell32 = row.createCell(count++); cell32.setCellValue(data.getSharedAntProp()==null?"":data.getSharedAntProp()); //共站名称 Cell cell33 = row.createCell(count++); cell33.setCellValue(data.getSharedBaseName()==null?"":data.getSharedBaseName()); //共站属性 Cell cell34 = row.createCell(count++); cell34.setCellValue(data.getSharedBaseProp()==null?"":data.getSharedBaseProp()); //网管运行状态 Cell cell35 = row.createCell(count++); cell35.setCellValue(data.getNetmanStat()==null?"":data.getNetmanStat()); //行政区域类型 Cell cell36 = row.createCell(count++); cell36.setCellValue(data.getAdminRegionType()==null?"":data.getAdminRegionType()); //上行频点 Cell cell37 = row.createCell(count++); cell37.setCellValue(data.getUpFreq()==null?"":String.valueOf(data.getUpFreq())); //下行频点 Cell cell38 = row.createCell(count++); cell38.setCellValue(data.getDownFreq()==null?"":String.valueOf(data.getDownFreq())); //rnc名称 Cell cell39 = row.createCell(count++); cell39.setCellValue(data.getRncName()==null?"":data.getRncName()); //网元类型 Cell cell40 = row.createCell(count++); cell40.setCellValue(data.getNeType()==null?"":data.getNeType()); //天线发射功率 Cell cell41 = row.createCell(count++); cell41.setCellValue(data.getAntPower()==null?"":data.getAntPower().toString()); //下倾角 Cell cell42 = row.createCell(count++); cell42.setCellValue(data.getTilt()==null?"":data.getTilt().toString()); //是否可以电调 Cell cell43 = row.createCell(count++); cell43.setCellValue(data.getEscBool()==null?"":data.getEscBool()); //基站类型 Cell cell44 = row.createCell(count++); cell44.setCellValue(data.getBaseType()==null?"":data.getBaseType()); //rru数量 Cell cell45 = row.createCell(count++); cell45.setCellValue(data.getRruCnt()==null?"":data.getRruCnt().toString()); //逻辑小区级别 Cell cell46 = row.createCell(count++); cell46.setCellValue(data.getLogicCellLevel()==null?"":data.getLogicCellLevel()); //扇区配置的无线容量 Cell cell47 = row.createCell(count++); cell47.setCellValue(data.getSectorWifiCapac()==null?"":data.getSectorWifiCapac().toString()); //e1数量 Cell cell48 = row.createCell(count++); cell48.setCellValue(data.getE1Cnt()==null?"":data.getE1Cnt().toString()); //fe数量 Cell cell49 = row.createCell(count++); cell49.setCellValue(data.getFeCnt()==null?"":data.getFeCnt().toString()); //传输方式 Cell cell50 = row.createCell(count++); cell50.setCellValue(data.getTransmission()==null?"":data.getTransmission()); //重庆区域覆盖 Cell cell51 = row.createCell(count++); cell51.setCellValue(data.getCqAreaCover()==null?"":data.getCqAreaCover()); //设计无线容量 Cell cell52 = row.createCell(count++); cell52.setCellValue(data.getWifiCapac()==null?"":data.getWifiCapac().toString()); //基站最大发射功率 Cell cell53 = row.createCell(count++); cell53.setCellValue(data.getBaseMaxPower()==null?"":data.getBaseMaxPower().toString()); //内置下倾角 Cell cell54 = row.createCell(count++); cell54.setCellValue(data.getInnerTilt()==null?"":data.getInnerTilt().toString()); //退服时间 Cell cell55 = row.createCell(count++); cell55.setCellValue(data.getOffServiceTime()==null?"":this.getTime(data.getOffServiceTime())); //小区的最大下行发射功率 Cell cell56 = row.createCell(count++); cell56.setCellValue(data.getDownMaxPower()==null?"":data.getDownMaxPower().toString()); //一级场景 Cell cell57 = row.createCell(count++); cell57.setCellValue(data.getSceneA()==null?"":data.getSceneA()); //二级场景 Cell cell58 = row.createCell(count++); cell58.setCellValue(data.getSceneB()==null?"":data.getSceneB()); //是否城区 Cell cell59 = row.createCell(count++); cell59.setCellValue(data.getTownBool()==null?"":data.getTownBool()); //是否支持hsdpa Cell cell60 = row.createCell(count++); cell60.setCellValue(data.getHsdpaBool()==null?"":data.getHsdpaBool()); //hsdpa功能状态 Cell cell61 = row.createCell(count++); cell61.setCellValue(data.getHsdpaStat()==null?"":data.getHsdpaStat()); //hs-pdsch代码 Cell cell62 = row.createCell(count++); cell62.setCellValue(data.getHsPdschCode()==null?"":data.getHsPdschCode()); //小区中广播信道的功率 Cell cell63 = row.createCell(count++); cell63.setCellValue(data.getBroadcastChannPower()==null?"":data.getBroadcastChannPower().toString()); //是否支持hsupa Cell cell64 = row.createCell(count++); cell64.setCellValue(data.getHsupaBool()==null?"":data.getHsupaBool()); //hsupa功能状态 Cell cell65 = row.createCell(count++); cell65.setCellValue(data.getHsupaStat()==null?"":data.getHsupaStat()); //是否支持mbms Cell cell66 = row.createCell(count++); cell66.setCellValue(data.getMbmsBool()==null?"":data.getMbmsBool()); //mbms功能状态 Cell cell67 = row.createCell(count++); cell67.setCellValue(data.getMbmsStat()==null?"":data.getMbmsStat()); //mich信道数 Cell cell68 = row.createCell(count++); cell68.setCellValue(data.getMichChannCnt()==null?"":data.getMichChannCnt().toString()); //sf=16的码字数 Cell cell69 = row.createCell(count++); cell69.setCellValue(data.getSf16CodeCnt()==null?"":data.getSf16CodeCnt().toString()); //sf=128的码字数 Cell cell70= row.createCell(count++); cell70.setCellValue(data.getSf128CodeCnt()==null?"":data.getSf128CodeCnt().toString()); //e-agch信道的初始数目 Cell cell71= row.createCell(count++); cell71.setCellValue(data.geteAgchChannCnt()==null?"":data.geteAgchChannCnt().toString()); //e-rgch/e-hich信道的初始数目 Cell cell72= row.createCell(count++); cell72.setCellValue(data.geteRgchEHichChannCnt()==null?"":data.geteRgchEHichChannCnt().toString()); //pcpich信道最大发射功率 Cell cell73= row.createCell(count++); cell73.setCellValue(data.getPcpichChannMaxPower()==null?"":data.getPcpichChannMaxPower().toString()); //pcpich信道最小发射功率 Cell cell74= row.createCell(count++); cell74.setCellValue(data.getPcpichChannMinPower()==null?"":data.getPcpichChannMinPower().toString()); //小区中使用的主导频信道的功率 Cell cell75= row.createCell(count++); cell75.setCellValue(data.getDominFreqChannPower()==null?"":data.getDominFreqChannPower().toString()); //小区中主同步信道的下行功率 Cell cell76= row.createCell(count++); cell76.setCellValue(data.getSyncChannDownPower()==null?"":data.getSyncChannDownPower().toString()); //单载频容纳最大用户数 Cell cell77= row.createCell(count++); cell77.setCellValue(data.getSingleCarrFreqMaxUser()==null?"":data.getSingleCarrFreqMaxUser().toString()); //小区配置的载频发射功率 Cell cell78= row.createCell(count++); cell78.setCellValue(data.getCarrFreqMaxPower()==null?"":data.getCarrFreqMaxPower().toString()); //配置的上行ce容量 Cell cell79= row.createCell(count++); cell79.setCellValue(data.getUpCeCapac()==null?"":data.getUpCeCapac().toString()); //配置的下行ce容量 Cell cell80= row.createCell(count++); cell80.setCellValue(data.getDownCeCapac()==null?"":data.getDownCeCapac().toString()); //iub接口atm端口的配置带宽 Cell cell81= row.createCell(count++); cell81.setCellValue(data.getIubAtmBandwidth()==null?"":data.getIubAtmBandwidth().toString()); //iub接口ip端口的配置带宽 Cell cell82= row.createCell(count++); cell82.setCellValue(data.getIubIpBandwidth()==null?"":data.getIubIpBandwidth().toString()); //iu接口atm层配置带宽 Cell cell83= row.createCell(count++); cell83.setCellValue(data.getIuAtmBandwidth()==null?"":data.getIuAtmBandwidth().toString()); //iu接口ip层配置带宽 Cell cell84= row.createCell(count++); cell84.setCellValue(data.getIuIpBandwidth()==null?"":data.getIuIpBandwidth().toString()); //iur接口atm层配置带宽 Cell cell85= row.createCell(count++); cell85.setCellValue(data.getIurAtmBandwidth()==null?"":data.getIurAtmBandwidth().toString()); //iur接口ip层配置带宽 Cell cell86= row.createCell(count++); cell86.setCellValue(data.getIurIpBandwidth()==null?"":data.getIurIpBandwidth().toString()); //备注 Cell cell87= row.createCell(count++); cell87.setCellValue(data.getRemark()==null?"":data.getRemark()); //最后更新时间 Cell cell88= row.createCell(count++); cell88.setCellValue(data.getLastUpdateTime()==null?"":this.getTime(data.getLastUpdateTime())); //rac Cell cell89= row.createCell(count++); cell89.setCellValue(data.getRac()==null?"":data.getRac().toString()); //sac Cell cell90= row.createCell(count++); cell90.setCellValue(data.getSac()==null?"":data.getSac().toString()); //rnc编号 Cell cell91= row.createCell(count++); cell91.setCellValue(data.getRncId()==null?"":data.getRncId().toString()); //基站编号 Cell cell92= row.createCell(count++); cell92.setCellValue(data.getBaseId()==null?"":data.getBaseId().toString()); //ura编号 Cell cell93= row.createCell(count++); cell93.setCellValue(data.getUraId()==null?"":data.getUraId().toString()); //是否安装塔顶放大器 Cell cell94= row.createCell(count++); cell94.setCellValue(data.getTowerAmpliBool()==null?"":data.getTowerAmpliBool()); //扇区编号 Cell cell95= row.createCell(count++); cell95.setCellValue(data.getSectorId()==null?"":data.getSectorId().toString()); //入网时间 Cell cell96= row.createCell(count++); cell96.setCellValue(data.getNetworkTime()==null?"":this.getTime(data.getNetworkTime())); //vip站 Cell cell97= row.createCell(count++); cell97.setCellValue(data.getVipBase()==null?"":data.getVipBase()); //室内室外 Cell cell98= row.createCell(count++); cell98.setCellValue(data.getInside()==null?"":data.getInside()); //bsc名称 Cell cell99= row.createCell(count++); cell99.setCellValue(data.getBscName()==null?"":data.getBscName()); //省份 Cell cell100= row.createCell(count++); cell100.setCellValue(data.getProvince()==null?"":data.getProvince()); //基站设备型号 Cell cell101= row.createCell(count++); cell101.setCellValue(data.getDevModel()==null?"":data.getDevModel()); //机柜类型 Cell cell102= row.createCell(count++); cell102.setCellValue(data.getCabinetType()==null?"":data.getCabinetType()); //载波类型 Cell cell103= row.createCell(count++); cell103.setCellValue(data.getCarrierType()==null?"":data.getCarrierType()); //共用馈线 Cell cell104= row.createCell(count++); cell104.setCellValue(data.getSharedFeeder()==null?"":data.getSharedFeeder()); //共用平台 Cell cell105= row.createCell(count++); cell105.setCellValue(data.getSharedPlatform()==null?"":data.getSharedPlatform()); //小区频段 Cell cell106= row.createCell(count++); cell106.setCellValue(data.getCellBand()==null?"":data.getCellBand().toString()); //小区标识 Cell cell107= row.createCell(count++); cell107.setCellValue(data.getCellMark()==null?"":data.getCellMark()); //小区bsic Cell cell108= row.createCell(count++); cell108.setCellValue(data.getBsic()==null?"":data.getBsic().toString()); //tch频点 Cell cell109= row.createCell(count++); cell109.setCellValue(data.getTchFreq()==null?"":data.getTchFreq()); //配置载频数 Cell cell110= row.createCell(count++); cell110.setCellValue(data.getCarrFreqCnt()==null?"":data.getCarrFreqCnt().toString()); //可用载频数 Cell cell111= row.createCell(count++); cell111.setCellValue(data.getCarrFreqAvailCnt()==null?"":data.getCarrFreqAvailCnt().toString()); //载频最大发射功率 Cell cell112= row.createCell(count++); cell112.setCellValue(data.getCarrFreqMaxPower()==null?"":data.getCarrFreqMaxPower().toString()); //配置控制信道数 Cell cell113= row.createCell(count++); cell113.setCellValue(data.getCtrlChannCnt()==null?"":data.getCtrlChannCnt().toString()); //配置业务信道数 Cell cell114= row.createCell(count++); cell114.setCellValue(data.getBusiChannCnt()==null?"":data.getBusiChannCnt().toString()); //sdcch可用数 Cell cell115= row.createCell(count++); cell115.setCellValue(data.getSdcchAvailCnt()==null?"":data.getSdcchAvailCnt().toString()); //天线俯仰角 Cell cell116= row.createCell(count++); cell116.setCellValue(data.getAntElevAngle()==null?"":data.getAntElevAngle().toString()); //跳频模式 Cell cell117= row.createCell(count++); cell117.setCellValue(data.getHoppingPattern()==null?"":data.getHoppingPattern()); //是否开通半速率 Cell cell118= row.createCell(count++); cell118.setCellValue(data.getHalfRateBool()==null?"":data.getHalfRateBool()); //gprs开通情况 Cell cell119= row.createCell(count++); cell119.setCellValue(data.getGprsBool()==null?"":data.getGprsBool()); //edge开通情况 Cell cell120= row.createCell(count++); cell120.setCellValue(data.getEdgeBool()==null?"":data.getEdgeBool()); //增强全速率开通情况 Cell cell121= row.createCell(count++); cell121.setCellValue(data.getEnfullRateBool()==null?"":data.getEnfullRateBool()); //网络制式 Cell cell122= row.createCell(count++); cell122.setCellValue(data.getModeType()==(short)0?"3G":"2G"); //3G邻区1-64 //2G邻区1-32 } public void createReportLoadCell(List<ReportCells> cells, String filePath ){ Workbook wb =new SXSSFWorkbook(100);; Sheet sheet = wb.createSheet("加载小区邻区信息报表"); Row topRow = sheet.createRow(0); // 标题样式 CellStyle topStyle = getNormalStyle(wb, "#00ccFF"); int count = 0; // 创建标题 createTitle(topRow, topStyle, "Lac", count++); createTitle(topRow, topStyle, "Cid", count++); createTitle(topRow, topStyle, "区域", count++); createTitle(topRow, topStyle, "小区名称", count++); createTitle(topRow, topStyle, "PSC/BCCH", count++); createTitle(topRow, topStyle, "BSC(2G)", count++); createTitle(topRow, topStyle, "BSIC(2G)", count++); createTitle(topRow, topStyle, "天线方向角", count++); createTitle(topRow, topStyle, "电子倾角", count++); createTitle(topRow, topStyle, "经度", count++); createTitle(topRow, topStyle, "纬度", count++); createTitle(topRow, topStyle, "上行频点", count++); createTitle(topRow, topStyle, "下行频点", count++); createTitle(topRow, topStyle, "小区频段", count++); createTitle(topRow, topStyle, "天线共用情况", count++); for(int i = count;i < 96 + count; i++ ){ createTitle(topRow, topStyle, "邻区", i); } int cellnum = 96 + count; for (int i = 0; i < cellnum; i++) { sheet.autoSizeColumn(i, true); } //设置三种填充excel单元格背景颜色style XSSFCellStyle styleLay1 = (XSSFCellStyle)wb.createCellStyle(); XSSFCellStyle styleLay2=(XSSFCellStyle)wb.createCellStyle(); XSSFCellStyle styleLay3=(XSSFCellStyle)wb.createCellStyle(); styleLay1 = ExcelUtil.setBackColorByCustom(wb, "#00c321"); styleLay2 = ExcelUtil.setBackColorByCustom(wb, "#1499da"); styleLay3 = ExcelUtil.setBackColorByCustom(wb, "#ffa200"); // styleLay1.setBorderTop(CellStyle.BORDER_THIN); // styleLay1.setBorderBottom(CellStyle.BORDER_THIN); // styleLay1.setBorderLeft(CellStyle.BORDER_THIN); // styleLay1.setBorderRight(CellStyle.BORDER_THIN); // styleLay2.setBorderTop(CellStyle.BORDER_THIN); // styleLay2.setBorderBottom(CellStyle.BORDER_THIN); // styleLay2.setBorderLeft(CellStyle.BORDER_THIN); // styleLay2.setBorderRight(CellStyle.BORDER_THIN); // styleLay3.setBorderTop(CellStyle.BORDER_THIN); // styleLay3.setBorderBottom(CellStyle.BORDER_THIN); // styleLay3.setBorderLeft(CellStyle.BORDER_THIN); // styleLay3.setBorderRight(CellStyle.BORDER_THIN); //循环填充每行数据 for(int i = 0; i < cells.size(); i ++){ ReportCells gw = cells.get(i); Row row = sheet.createRow(i+1); //调用赋值方法 setCellRelValue(row,gw,styleLay1,styleLay2,styleLay3,cellnum); } try { // 获取一个输出流 FileOutputStream fileOut = new FileOutputStream(filePath); // 生成Excel wb.write(fileOut); // 关闭流 fileOut.close(); } catch (Exception e) { e.printStackTrace(); } } private void setNearValue(String value,Row row,int count,CellStyle styleLay1,CellStyle styleLay2,CellStyle styleLay3){ String[] temp = null; Cell cell = row.getCell(count); if(cell == null){ cell = row.createCell(count); } if(value != null && !value.equals("")){ temp = value.split("_"); cell.setCellValue(temp[0] + "_" + temp[1]); if(temp[2].equals("0")){ cell.setCellStyle(styleLay1); }else if(temp[2].equals("1")){ cell.setCellStyle(styleLay2); }else if(temp[2].equals("2")){ cell.setCellStyle(styleLay3); } }else{ cell.setCellValue(""); } } private void setCellRelValue(Row row,ReportCells rc,CellStyle styleLay1,CellStyle styleLay2,CellStyle styleLay3,int cellnum){ int count = 0; //先创建列 for(int i = 0; i < cellnum; i++){ row.createCell(i); } //lac Cell cell1 = row.getCell(count++); cell1.setCellValue(rc.getLac()); //cid Cell cell2 = row.getCell(count++); cell2.setCellValue(rc.getCid()); //区域 Cell cell3 = row.getCell(count++); cell3.setCellValue(rc.getAreaname()==null?"":rc.getAreaname()); //小区名称 Cell cell4 = row.getCell(count++); cell4.setCellValue(rc.getCellname()==null?"":rc.getCellname()); //PSC/BCCH Cell cell5 = row.getCell(count++); cell5.setCellValue(rc.getPsc() == null?"":rc.getPsc().toString()); //BSC名称 Cell cell6 = row.getCell(count++); cell6.setCellValue(rc.getBscname() == null?"":rc.getBscname()); //BSIC名称 Cell cell7 = row.getCell(count++); cell7.setCellValue(rc.getBsic() == null?"":rc.getBsic().toString()); //天线方向角 Cell cell8 = row.getCell(count++); cell8.setCellValue(rc.getAnt_azimuth() == null?"":rc.getAnt_azimuth().toString()); //电子倾角 Cell cell9 = row.getCell(count++); cell9.setCellValue(rc.getAnt_elect_angle() == null?"":rc.getAnt_elect_angle().toString()); //经度 Cell cell10 = row.getCell(count++); cell10.setCellValue(rc.getLongitude() == null?"":rc.getLongitude().toString()); //纬度 Cell cell11 = row.getCell(count++); cell11.setCellValue(rc.getLatitude() == null?"":rc.getLatitude().toString()); //上行频点 Cell cell12 = row.getCell(count++); cell12.setCellValue(rc.getUpfreq() == null?"":rc.getUpfreq().toString()); //下行频点 Cell cell13 = row.getCell(count++); cell13.setCellValue(rc.getDownfreq() == null?"":rc.getDownfreq().toString()); //小区频段 Cell cell14 = row.getCell(count++); cell14.setCellValue(rc.getCellband() == null?"":rc.getCellband().toString()); //天线公用情况 Cell cell15 = row.getCell(count++); cell15.setCellValue(rc.getSharedant() == null?"":rc.getSharedant()); //邻区赋值 setNearValue(rc.getA1_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA2_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA3_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA4_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA5_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA6_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA7_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA8_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA9_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA10_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA11_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA12_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA13_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA14_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA15_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA16_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA17_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA18_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA19_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA20_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA21_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA22_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA23_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA24_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA25_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA26_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA27_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA28_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA29_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA30_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA31_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA32_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA33_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA34_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA35_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA36_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA37_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA38_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA39_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA40_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA41_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA42_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA43_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA44_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA45_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA46_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA47_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA48_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA49_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA50_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA51_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA52_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA53_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA54_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA55_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA56_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA57_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA58_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA59_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA60_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA61_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA62_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA63_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA64_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA65_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA66_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA67_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA68_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA69_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA70_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA71_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA72_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA73_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA74_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA75_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA76_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA77_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA78_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA79_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA80_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA81_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA82_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA83_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA84_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA85_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA86_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA87_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA88_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA89_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA90_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA91_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA92_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA93_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA94_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA95_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); setNearValue(rc.getA96_lac_cid(),row,count++,styleLay1,styleLay2,styleLay3); /** for(GwCasCell gcc : gw.getList()){ Cell cell = null; //XSSFCellStyle style = (XSSFCellStyle)wb.createCellStyle(); String val = gcc.getLac_cid(); //System.out.println("w_count" + w_count + "g_count" +g_count); if(gcc.getModeType() == 0){ cell = row.getCell(w_count ++); }else{ cell = row.getCell(g_count ++); } cell.setCellValue(val); //System.out.println(gcc.getNearrel()); if(gcc.getNearrel() == 0){ //style = ExcelUtil.setBackColorByCustom(style, "#00c321"); //styleLay1.setFillForegroundColor(HSSFColor.GREEN.index); // 设置填充模式 //styleLay1.setFillPattern(CellStyle.SOLID_FOREGROUND); cell.setCellStyle(styleLay1); }else if(gcc.getNearrel() == 1){ //style = ExcelUtil.setBackColorByCustom(style, "#1499da"); //styleLay2.setFillForegroundColor(HSSFColor.BLUE.index); //styleLay2.setFillPattern(CellStyle.SOLID_FOREGROUND); cell.setCellStyle(styleLay2); }else if(gcc.getNearrel() == 2){ //style = ExcelUtil.setBackColorByCustom(style, "#ffa200"); //styleLay3.setFillForegroundColor(HSSFColor.YELLOW.index); //styleLay3.setFillPattern(CellStyle.SOLID_FOREGROUND); cell.setCellStyle(styleLay3); } }* */ //填充单元格边框 // for(int i = w_count;i < 66; i ++){ // Cell cell = row.getCell(i); //// XSSFCellStyle style = (XSSFCellStyle)wb.createCellStyle(); //// style.setBorderTop(XSSFCellStyle.BORDER_THIN); //// style.setBorderBottom(XSSFCellStyle.BORDER_THIN); //// style.setBorderLeft(XSSFCellStyle.BORDER_THIN); //// style.setBorderRight(XSSFCellStyle.BORDER_THIN); //// cell.setCellStyle(style); // } // for(int i = g_count;i < 98; i ++){ // Cell cell = row.getCell(i); //// XSSFCellStyle style = (XSSFCellStyle)wb.createCellStyle(); //// style.setBorderTop(XSSFCellStyle.BORDER_THIN); //// style.setBorderBottom(XSSFCellStyle.BORDER_THIN); //// style.setBorderLeft(XSSFCellStyle.BORDER_THIN); //// style.setBorderRight(XSSFCellStyle.BORDER_THIN); //// cell.setCellStyle(style); // } } /** * 格式化时间 */ public static String getTime(Date date){ SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd HH:mm:ss"); String str = formatter.format(date); return str; } /** * 创建title */ public void getTitle(Row topRow,CellStyle topStyle,Sheet sheet){ // 创建标题 int count =0; createTitle(topRow, topStyle, "城市名称", count ++); createTitle(topRow, topStyle, "行政区域", count ++); createTitle(topRow, topStyle, "区域id", count ++); createTitle(topRow, topStyle, "小区cid", count ++); createTitle(topRow, topStyle, "基站id", count ++); createTitle(topRow, topStyle, "基站名称", count ++); createTitle(topRow, topStyle, "小区名称", count ++); createTitle(topRow, topStyle, "经度", count ++); createTitle(topRow, topStyle, "纬度", count ++); createTitle(topRow, topStyle, "psc/bcch", count ++); createTitle(topRow, topStyle, "网络模式", count ++); createTitle(topRow, topStyle, "室内外", count ++); createTitle(topRow, topStyle, "天线类型", count ++); createTitle(topRow, topStyle, "天线方位角", count ++); createTitle(topRow, topStyle, "天线高度", count ++); createTitle(topRow, topStyle, "天线电子倾角", count ++); createTitle(topRow, topStyle, "天线机械倾角", count ++); createTitle(topRow, topStyle, "共用天线", count ++); createTitle(topRow, topStyle, "基站站址", count ++); createTitle(topRow, topStyle, "海拔高度", count ++); createTitle(topRow, topStyle, "设备厂商", count ++); createTitle(topRow, topStyle, "塔桅类型", count ++); createTitle(topRow, topStyle, "设备类型", count ++); createTitle(topRow, topStyle, "基站配置", count ++); createTitle(topRow, topStyle, "工程进展", count ++); createTitle(topRow, topStyle, "覆盖范围", count ++); createTitle(topRow, topStyle, "覆盖类型", count ++); createTitle(topRow, topStyle, "是否rru小区", count ++); createTitle(topRow, topStyle, "小区编号", count ++); createTitle(topRow, topStyle, "直放站数量", count ++); createTitle(topRow, topStyle, "共天馈小区", count ++); createTitle(topRow, topStyle, "共天馈属性", count ++); createTitle(topRow, topStyle, "共站名称", count ++); createTitle(topRow, topStyle, "共站属性", count ++); createTitle(topRow, topStyle, "网管运行状态", count ++); createTitle(topRow, topStyle, "行政区域类型", count ++); createTitle(topRow, topStyle, "上行频点", count ++); createTitle(topRow, topStyle, "下行频点", count ++); createTitle(topRow, topStyle, "rnc名称", count ++); createTitle(topRow, topStyle, "网元类型", count ++); createTitle(topRow, topStyle, "天线发射功率", count ++); createTitle(topRow, topStyle, "下倾角", count ++); createTitle(topRow, topStyle, "是否可以电调", count ++); createTitle(topRow, topStyle, "基站类型", count ++); createTitle(topRow, topStyle, "rru数量", count ++); createTitle(topRow, topStyle, "逻辑小区级别", count ++); createTitle(topRow, topStyle, "扇区配置的无线容量", count ++); createTitle(topRow, topStyle, "e1数量", count ++); createTitle(topRow, topStyle, "fe数量", count ++); createTitle(topRow, topStyle, "传输方式", count ++); createTitle(topRow, topStyle, "重庆区域覆盖", count ++); createTitle(topRow, topStyle, "设计无线容量", count ++); createTitle(topRow, topStyle, "基站最大发射功率", count ++); createTitle(topRow, topStyle, "内置下倾角", count ++); createTitle(topRow, topStyle, "退服时间", count ++); createTitle(topRow, topStyle, "小区的最大下行发射功率", count ++); createTitle(topRow, topStyle, "一级场景", count ++); createTitle(topRow, topStyle, "二级场景", count ++); createTitle(topRow, topStyle, "是否城区", count ++); createTitle(topRow, topStyle, "是否支持hsdpa", count ++); createTitle(topRow, topStyle, "hsdpa功能状态", count ++); createTitle(topRow, topStyle, "hs-pdsch代码", count ++); createTitle(topRow, topStyle, "小区中广播信道的功率", count ++); createTitle(topRow, topStyle, "是否支持hsupa", count ++); createTitle(topRow, topStyle, "hsupa功能状态", count ++); createTitle(topRow, topStyle, "是否支持mbms", count ++); createTitle(topRow, topStyle, "mbms功能状态", count ++); createTitle(topRow, topStyle, "mich信道数", count ++); createTitle(topRow, topStyle, "sf=16的码字数", count ++); createTitle(topRow, topStyle, "sf=128的码字数", count ++); createTitle(topRow, topStyle, "e-agch信道的初始数目", count ++); createTitle(topRow, topStyle, "e-rgch/e-hich信道的初始数目", count ++); createTitle(topRow, topStyle, "pcpich信道最大发射功率", count ++); createTitle(topRow, topStyle, "pcpich信道最小发射功率", count ++); createTitle(topRow, topStyle, "小区中使用的主导频信道的功率", count ++); createTitle(topRow, topStyle, "小区中主同步信道的下行功率", count ++); createTitle(topRow, topStyle, "单载频容纳最大用户数", count ++); createTitle(topRow, topStyle, "小区配置的载频发射功率", count ++); createTitle(topRow, topStyle, "配置的上行ce容量", count ++); createTitle(topRow, topStyle, "配置的下行ce容量", count ++); createTitle(topRow, topStyle, "iub接口atm端口的配置带宽", count ++); createTitle(topRow, topStyle, "iub接口ip端口的配置带宽", count ++); createTitle(topRow, topStyle, "iu接口atm层配置带宽", count ++); createTitle(topRow, topStyle, "iu接口ip层配置带宽", count ++); createTitle(topRow, topStyle, "iur接口atm层配置带宽", count ++); createTitle(topRow, topStyle, "iur接口ip层配置带宽", count ++); createTitle(topRow, topStyle, "备注", count ++); createTitle(topRow, topStyle, "最后更新时间", count ++); createTitle(topRow, topStyle, "rac", count ++); createTitle(topRow, topStyle, "sac", count ++); createTitle(topRow, topStyle, "rnc编号", count ++); createTitle(topRow, topStyle, "基站编号", count ++); createTitle(topRow, topStyle, "ura编号", count ++); createTitle(topRow, topStyle, "是否安装塔顶放大器", count ++); createTitle(topRow, topStyle, "扇区编号", count ++); createTitle(topRow, topStyle, "入网时间", count ++); createTitle(topRow, topStyle, "vip站", count ++); createTitle(topRow, topStyle, "室内室外", count ++); createTitle(topRow, topStyle, "bsc名称", count ++); createTitle(topRow, topStyle, "省份", count ++); createTitle(topRow, topStyle, "基站设备型号", count ++); createTitle(topRow, topStyle, "机柜类型", count ++); createTitle(topRow, topStyle, "载波类型", count ++); createTitle(topRow, topStyle, "共用馈线", count ++); createTitle(topRow, topStyle, "共用平台", count ++); createTitle(topRow, topStyle, "小区频段", count ++); createTitle(topRow, topStyle, "小区标识", count ++); createTitle(topRow, topStyle, "小区bsic", count ++); createTitle(topRow, topStyle, "tch频点", count ++); createTitle(topRow, topStyle, "配置载频数", count ++); createTitle(topRow, topStyle, "可用载频数", count ++); createTitle(topRow, topStyle, "载频最大发射功率", count ++); createTitle(topRow, topStyle, "配置控制信道数", count ++); createTitle(topRow, topStyle, "配置业务信道数", count ++); createTitle(topRow, topStyle, "sdcch可用数", count ++); createTitle(topRow, topStyle, "天线俯仰角", count ++); createTitle(topRow, topStyle, "跳频模式", count ++); createTitle(topRow, topStyle, "是否开通半速率", count ++); createTitle(topRow, topStyle, "gprs开通情况", count ++); createTitle(topRow, topStyle, "edge开通情况", count ++); createTitle(topRow, topStyle, "增强全速率开通情况", count ++); createTitle(topRow, topStyle, "网络制式", count ++); /*createTitle(topRow, topStyle, "3G邻区1", count ++); createTitle(topRow, topStyle, "3G邻区2", count ++); createTitle(topRow, topStyle, "3G邻区3", count ++); createTitle(topRow, topStyle, "3G邻区4", count ++); createTitle(topRow, topStyle, "3G邻区5", count ++); createTitle(topRow, topStyle, "3G邻区6", count ++); createTitle(topRow, topStyle, "3G邻区7", count ++); createTitle(topRow, topStyle, "3G邻区8", count ++); createTitle(topRow, topStyle, "3G邻区9", count ++); createTitle(topRow, topStyle, "3G邻区10", count ++); createTitle(topRow, topStyle, "3G邻区11", count ++); createTitle(topRow, topStyle, "3G邻区12", count ++); createTitle(topRow, topStyle, "3G邻区13", count ++); createTitle(topRow, topStyle, "3G邻区14", count ++); createTitle(topRow, topStyle, "3G邻区15", count ++); createTitle(topRow, topStyle, "3G邻区16", count ++); createTitle(topRow, topStyle, "3G邻区17", count ++); createTitle(topRow, topStyle, "3G邻区18", count ++); createTitle(topRow, topStyle, "3G邻区19", count ++); createTitle(topRow, topStyle, "3G邻区20", count ++); createTitle(topRow, topStyle, "3G邻区21", count ++); createTitle(topRow, topStyle, "3G邻区22", count ++); createTitle(topRow, topStyle, "3G邻区23", count ++); createTitle(topRow, topStyle, "3G邻区24", count ++); createTitle(topRow, topStyle, "3G邻区25", count ++); createTitle(topRow, topStyle, "3G邻区26", count ++); createTitle(topRow, topStyle, "3G邻区27", count ++); createTitle(topRow, topStyle, "3G邻区28", count ++); createTitle(topRow, topStyle, "3G邻区29", count ++); createTitle(topRow, topStyle, "3G邻区30", count ++); createTitle(topRow, topStyle, "3G邻区31", count ++); createTitle(topRow, topStyle, "3G邻区32", count ++); createTitle(topRow, topStyle, "3G邻区33", count ++); createTitle(topRow, topStyle, "3G邻区34", count ++); createTitle(topRow, topStyle, "3G邻区35", count ++); createTitle(topRow, topStyle, "3G邻区36", count ++); createTitle(topRow, topStyle, "3G邻区37", count ++); createTitle(topRow, topStyle, "3G邻区38", count ++); createTitle(topRow, topStyle, "3G邻区39", count ++); createTitle(topRow, topStyle, "3G邻区40", count ++); createTitle(topRow, topStyle, "3G邻区41", count ++); createTitle(topRow, topStyle, "3G邻区42", count ++); createTitle(topRow, topStyle, "3G邻区43", count ++); createTitle(topRow, topStyle, "3G邻区44", count ++); createTitle(topRow, topStyle, "3G邻区45", count ++); createTitle(topRow, topStyle, "3G邻区46", count ++); createTitle(topRow, topStyle, "3G邻区47", count ++); createTitle(topRow, topStyle, "3G邻区48", count ++); createTitle(topRow, topStyle, "3G邻区49", count ++); createTitle(topRow, topStyle, "3G邻区50", count ++); createTitle(topRow, topStyle, "3G邻区51", count ++); createTitle(topRow, topStyle, "3G邻区52", count ++); createTitle(topRow, topStyle, "3G邻区53", count ++); createTitle(topRow, topStyle, "3G邻区54", count ++); createTitle(topRow, topStyle, "3G邻区55", count ++); createTitle(topRow, topStyle, "3G邻区56", count ++); createTitle(topRow, topStyle, "3G邻区57", count ++); createTitle(topRow, topStyle, "3G邻区58", count ++); createTitle(topRow, topStyle, "3G邻区59", count ++); createTitle(topRow, topStyle, "3G邻区60", count ++); createTitle(topRow, topStyle, "3G邻区61", count ++); createTitle(topRow, topStyle, "3G邻区62", count ++); createTitle(topRow, topStyle, "3G邻区63", count ++); createTitle(topRow, topStyle, "3G邻区64", count ++); createTitle(topRow, topStyle, "2G邻区1", count ++); createTitle(topRow, topStyle, "2G邻区2", count ++); createTitle(topRow, topStyle, "2G邻区3", count ++); createTitle(topRow, topStyle, "2G邻区4", count ++); createTitle(topRow, topStyle, "2G邻区5", count ++); createTitle(topRow, topStyle, "2G邻区6", count ++); createTitle(topRow, topStyle, "2G邻区7", count ++); createTitle(topRow, topStyle, "2G邻区8", count ++); createTitle(topRow, topStyle, "2G邻区9", count ++); createTitle(topRow, topStyle, "2G邻区10", count ++); createTitle(topRow, topStyle, "2G邻区11", count ++); createTitle(topRow, topStyle, "2G邻区12", count ++); createTitle(topRow, topStyle, "2G邻区13", count ++); createTitle(topRow, topStyle, "2G邻区14", count ++); createTitle(topRow, topStyle, "2G邻区15", count ++); createTitle(topRow, topStyle, "2G邻区16", count ++); createTitle(topRow, topStyle, "2G邻区17", count ++); createTitle(topRow, topStyle, "2G邻区18", count ++); createTitle(topRow, topStyle, "2G邻区19", count ++); createTitle(topRow, topStyle, "2G邻区20", count ++); createTitle(topRow, topStyle, "2G邻区21", count ++); createTitle(topRow, topStyle, "2G邻区22", count ++); createTitle(topRow, topStyle, "2G邻区23", count ++); createTitle(topRow, topStyle, "2G邻区24", count ++); createTitle(topRow, topStyle, "2G邻区25", count ++); createTitle(topRow, topStyle, "2G邻区26", count ++); createTitle(topRow, topStyle, "2G邻区27", count ++); createTitle(topRow, topStyle, "2G邻区28", count ++); createTitle(topRow, topStyle, "2G邻区29", count ++); createTitle(topRow, topStyle, "2G邻区30", count ++); createTitle(topRow, topStyle, "2G邻区31", count ++); createTitle(topRow, topStyle, "2G邻区32", count ++);*/ // 使单元格自动适应内容长度 for (int i = 0; i < 122; i++) { sheet.autoSizeColumn(i, true); } } } <file_sep>/src/main/java/com/complaint/model/AssignAccess.java package com.complaint.model; import java.util.List; public class AssignAccess { private int id; private String text; private String state; // open or closed private boolean checked; private int attributes; private List<AssignAccess> children; public int getAttributes() { return attributes; } public void setAttributes(int attributes) { this.attributes = attributes; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getState() { return state; } public void setState(String state) { this.state = state; } public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } public List<AssignAccess> getChildren() { return children; } public void setChildren(List<AssignAccess> accesses) { this.children = accesses; } } <file_sep>/src/main/webapp/js/report/trck.js /******************************************************************************* * 单次测试室内外地图 * * @author czj */ var map; var colorlist; var gsmlist, wcdmalist,ltelist; var first_id, first_type;// 第一个点ID var last_id, last_type;// 最后一个点ID var exlatAndlngMap_3g = new Map();// 封装Markerr 的偏移前经纬度KEY:marker;value:偏移前经纬度 var latAndlngMap_3g = new Map();// 封装Markerr 的偏移后经纬度KEY:marker;value:偏移后经纬度 var exlatAndlngMap_2g = new Map();// 封装Markerr 的偏移前经纬度KEY:marker;value:偏移前经纬度 var latAndlngMap_2g = new Map();// 封装Markerr 的偏移后经纬度KEY:marker;value:偏移后经纬度 var exlatAndlngMap_4g = new Map();// 封装Markerr 的偏移前经纬度KEY:marker;value:偏移前经纬度 var latAndlngMap_4g = new Map();// 封装Markerr 的偏移后经纬度KEY:marker;value:偏移后经纬度 var cenetr_lat_lng;// 中心位置 var zNodes = []; var zTree; /** * 对轨迹点数据进行处理判断室内外类型分别加载地图、图例 * 并根据数据对各指标是否进行测试判断生成指标的下拉菜单选择器(默认2G-Rxlev、3G-RSCP)并进行事件绑定、 * 生成叠加数据功能里的树形指标菜单与事件绑定 * 判断轨迹的第一个点(以时间判断)并默认展示轨迹点详细数据 * * * @param flowid * @param type * @param inside * @param flist */ function queryPoint(flowid, type, inside, flist) { var idooorTag=[]; var psc_xlist, bcch_xlist,pci_xlist; for ( var t = 0; t < flist.length; t++) { if (flist[t].kpiId == 20) { psc_xlist = flist[t].x; } if (flist[t].kpiId == '21') { bcch_xlist = flist[t].x; } if (flist[t].kpiId == 26) { pci_xlist = flist[t].x; } } $("#demo_div").html(""); flay = true; $(".case_tu p").css({ 'background-image' : 'url(../images/case_tu_s.png)' }); $(".case_zhi").hide(); $("#d_s_id").show(); flag = true; $ .ajax({ type : "post", url : contextPath + "/report/showPoint", data : ({ flowid : flowid, areaid:$("#areaid").val(), type : type }), success : function(data) { $('#div_page').html(""); if (data) { gsmlist = data.gsmlist; wcdmalist = data.wcdmalist; ltelist = data.ltelist; var sum = 0;//全部点 // 无服务点统计 var gmsnssum = 0;//2g无服务点 var wcdmanssum = 0;//3g无服务点 var gmssum = 0;//2g点 var wcdmasum = 0;//3G点 var ltenssum = 0;//4g无服务点 var ltesum = 0;//4g点 // 2g,3g,4g无服务 var noService = 0; var gsmProp =0; var wcdmaProp = 0; var lteProp = 0; var centers=[]; if (gsmlist) { sum += gsmlist.length; gmssum = gsmlist.length; // 统计自由模式2G无服务点 for(var i = 0;i < gsmlist.length;i++){ if(gsmlist[i].realnet_type == -1){ gmsnssum += 1; } if(gsmlist[i].lat_modi>0&&gsmlist[i].lng_modi>0){ centers.push(new BMap.Point(gsmlist[i].lng_modi,gsmlist[i].lat_modi)); } } } if (wcdmalist) { sum += wcdmalist.length; wcdmasum = wcdmalist.length; // 统计自由模式3G无服务点 for(var i = 0;i < wcdmalist.length;i++){ if(wcdmalist[i].realnet_type == -1){ wcdmanssum += 1; } if(wcdmalist[i].lat_modi>0&&wcdmalist[i].lng_modi>0){ centers.push(new BMap.Point(wcdmalist[i].lng_modi,wcdmalist[i].lat_modi)); } } } if (ltelist) { sum += ltelist.length; ltesum = ltelist.length; // 统计自由模式4G无服务点 for(var i = 0;i < ltelist.length;i++){ if(ltelist[i].realnet_type == -1){ ltenssum += 1; } if(ltelist[i].lat_modi>0&&ltelist[i].lng_modi>0){ centers.push(new BMap.Point(ltelist[i].lng_modi,ltelist[i].lat_modi)); } } } // 用来去分是否为WCDMA自由模式 var netType = $(".combo-text").val().split("_"); // 统计自由模式无服务占比 // 统计3g 2g ,4g以及无服务占比,如果采点总数为0让他各项为初始值0 if(sum!=0){ // noService noService = ((wcdmanssum+gmsnssum+ltenssum)/sum)*100; // 2G占比 gsmProp = ((gmssum-gmsnssum)/sum)*100; // 3G占比 wcdmaProp = ((wcdmasum-wcdmanssum)/sum)*100; // 4G占比 lteProp = ((ltesum-ltenssum)/sum)*100; } // 判断noService是否为0有没有必要添加 var noServiceLast = ""; var gsm_net =""; var wcdma_net =""; var lte_net =""; if(noService!=0){ noServiceLast = NumOptimize(noService.toFixed(2))+"%"; }else{ noServiceLast = "0%"; } if(gsmProp.toFixed(2)!=0){ gsm_net = NumOptimize(gsmProp.toFixed(2))+"%"; }else{ gsm_net = "0%"; } if(wcdmaProp.toFixed(2)!=0){ wcdma_net = NumOptimize(wcdmaProp.toFixed(2))+"%"; }else{ wcdma_net = "0%"; } if(lteProp.toFixed(2)!=0){ lte_net = NumOptimize(lteProp.toFixed(2))+"%"; }else{ lte_net = "0%"; } // 页面添加无服务行 $("#wcdmaScale").html(wcdma_net); $("#gsmScale").html(gsm_net); $("#lteScale").html(lte_net);//4G占比 $("#noServiceScale").html(noServiceLast); $("#sum_count").html("采样点:" + sum); colorlist = data.colorlist; // 根据数据显示下拉 // 3G下拉 zNodes指标下拉列表里去掉id为1、2,3的,其他ID+3 zNodes = []; $("#s_sel1").hide(); $("#s_sel2").hide(); $("#s_sel3").hide(); var dd = [], dd_id = [],dd_id_1=[],dd_id_2=[], child = []; kpi_choose(wcdmalist,gsmlist,ltelist,dd, dd_id ,dd_id_1,dd_id_2, child); $("#forms_data_id").show(); if (inside == 1) { // 室内 $("#expand").show(); $("#narrow").show(); if (map) { $("#div_point").html(div_html); } var aaf= showIndoorPoint(gsmlist, wcdmalist,ltelist, colorlist, psc_xlist, bcch_xlist,pci_xlist,idooorTag); if (dd_id_1.length > 0) { $("#SelectBox1") .combobox( { onSelect : function(n, o) { select_change(dd_id,dd_id_1,dd_id_2,flowid,flist,wcdmalist, gsmlist,ltelist,idooorTag,aaf); } }); } // 下拉列表3G点击事件 if (dd_id.length > 0) { $("#SelectBox2") .combobox( { onSelect : function(n, o) { select_change(dd_id,dd_id_1,dd_id_2,flowid,flist,wcdmalist, gsmlist,ltelist,idooorTag,aaf); } }); } if (dd_id_2.length > 0) { $("#SelectBox3") .combobox( { onSelect : function(n, o) { select_change(dd_id,dd_id_1,dd_id_2,flowid,flist,wcdmalist, gsmlist,ltelist,idooorTag,aaf); } }); } } else if (inside == 0) { // 室外 $("#expand").hide(); $("#narrow").hide(); initMap(wcdmalist, gsmlist, ltelist,centers, psc_xlist, bcch_xlist,pci_xlist); // 下拉列表2G点击事件 if (dd_id_1.length > 0) { $("#SelectBox1") .combobox( { onSelect : function(n, o) { chooseKpi( wcdmalist, gsmlist,ltelist, $("#SelectBox1") .combobox( "getValue"), "1", psc_xlist, bcch_xlist,pci_xlist); if ($("#demo_div") .html()) { choose_demo( flowid, flist, $( "#SelectBox1") .combobox( "getValue"), $( "#SelectBox2") .combobox( "getValue"),$( "#SelectBox3") .combobox( "getValue"), $( "#SelectBox1") .combobox( "getText"), $( "#SelectBox2") .combobox( "getText"),$( "#SelectBox3") .combobox( "getText"), "#demo_div", wcdmalist, gsmlist,ltelist); } } }); } if (dd_id_2.length > 0) { $("#SelectBox3") .combobox( { onSelect : function(n, o) { chooseKpi( wcdmalist, gsmlist,ltelist, $("#SelectBox3") .combobox( "getValue"), "3", psc_xlist, bcch_xlist,pci_xlist); if ($("#demo_div") .html()) { choose_demo( flowid, flist, $( "#SelectBox1") .combobox( "getValue"), $( "#SelectBox2") .combobox( "getValue"),$( "#SelectBox3") .combobox( "getValue"), $( "#SelectBox1") .combobox( "getText"), $( "#SelectBox2") .combobox( "getText"),$( "#SelectBox3") .combobox( "getText"), "#demo_div", wcdmalist, gsmlist,ltelist); } } }); } // 下拉列表3G点击事件 if (dd_id.length > 0) { $("#SelectBox2") .combobox( { onSelect : function(n, o) { chooseKpi( wcdmalist, gsmlist,ltelist, $("#SelectBox2") .combobox( "getValue"), "2", psc_xlist, bcch_xlist,pci_xlist); if ($("#demo_div") .html()) { choose_demo( flowid, flist, $( "#SelectBox1") .combobox( "getValue"), $( "#SelectBox2") .combobox( "getValue"),$( "#SelectBox3") .combobox( "getValue"), $( "#SelectBox1") .combobox( "getText"), $( "#SelectBox2") .combobox( "getText"),$( "#SelectBox3") .combobox( "getText"), "#demo_div", wcdmalist, gsmlist,ltelist); } } }); } } // 图例比例显示点击事件 $('#img_demo') .die() .live( "click", function(e) { $(".case_tu") .css("background", "none repeat scroll 0 0 #fff"); $(".case_tu").css("border-bottom", "1px solid #979797"); $(".case_tu").css("border-right", "1px solid #979797"); var sel1 = 0, sel2 = 0,sel3 = 0; var sel1_n = "", sel2_n = "",sel3_n = ""; if (dd_id_1.length > 0) { sel1 = $("#SelectBox1") .combobox("getValue"); sel1_n = $("#SelectBox1") .combobox("getText"); } if (dd_id.length > 0) { sel2 = $("#SelectBox2") .combobox("getValue"); sel2_n = $("#SelectBox2") .combobox("getText"); } if (dd_id_2.length > 0) { sel3 = $("#SelectBox3") .combobox("getValue"); sel3_n = $("#SelectBox3") .combobox("getText"); } if (flay == true) { choose_demo(flowid, flist, sel1, sel2,sel3, sel1_n, sel2_n,sel3_n, "#demo_div", wcdmalist, gsmlist,ltelist); $(".case_tu p") .css( { 'background-image' : 'url(../images/case_tu.png)' }); flay = false; } else { $(".case_tu").css("background", ""); $(".case_tu").css( "border-bottom", ""); $(".case_tu").css( "border-right", ""); $("#demo_div").html(""); flay = true; $(".case_tu p") .css( { 'background-image' : 'url(../images/case_tu_s.png)' }); } }); // 轨迹叠加选择 $('.twoG') .click( function(e) { $(".easyui-linkbutton").show(); var sel1 = 0, sel2 = 0, sel3 = 0; $("#zhibiao").dialog({ height : 200, width : 380, title : "测试指标选择", modal : true, closed : false }); $("#tul").tree({ data : zNodes, animate : true, checkbox : true, onlyLeafCheck : true }); if (dd_id_1.length > 0) { sel1 = $("#SelectBox1") .combobox("getValue"); } if (dd_id.length > 0) { sel2 = $("#SelectBox2") .combobox("getValue"); } if (dd_id_2.length > 0) { sel3 = $("#SelectBox3") .combobox("getValue"); } for (i in zNodes) { child = zNodes[i].children; for (j in child) { if (child[j].id == (parseInt(sel1) + 3)) { var no = $("#tul") .tree( "find", child[j].id); $("#tul").tree( "remove", no.target); } if (child[j].id == (parseInt(sel2) + 3)) { var no = $("#tul") .tree( "find", child[j].id); $("#tul").tree( "remove", no.target); } if (child[j].id == (parseInt(sel3) + 3)) { var no = $("#tul") .tree( "find", child[j].id); $("#tul").tree( "remove", no.target); } } } $('#zhibiao').dialog('open'); $.parser.parse('#zhibiao'); }); // 树形确定事件 $('.treeb').unbind("click").click( function(e) { var sel1 = 0, sel2 = 0, sel3 = 0; if (dd_id_1.length > 0) { sel1 = $("#SelectBox1").combobox( "getValue"); } if (dd_id.length > 0) { sel2 = $("#SelectBox2").combobox( "getValue"); } if (dd_id_2.length > 0) { sel3 = $("#SelectBox3").combobox( "getValue"); } var nodes = $('#zhibiao') .tree('getChecked'); var v = "", id_v = "",str = ""; for ( var i = 0; i < nodes.length; i++) { if (v != '') { v += ','; id_v += ','; } str = nodes[i].text; if (i != nodes.length - 1) { v += str + ","; id_v += nodes[i].id + ","; } else { v += str; id_v += nodes[i].id; } } if (nodes.length == 0) { $.messager.alert("warning", "至少选择一个指标!", "warning"); return; } var idd = ""; if (sel2) { idd += (parseInt(sel2) + 3) + ","; } if (sel1) { idd += (parseInt(sel1) + 3) + ","; } if (sel3) { idd += (parseInt(sel3) + 3) + ","; } idd += id_v; $("#undata").val(v); $("#undata_id").val(idd); if (inside == 1) { if (sel1) { if (dd_id_1.length > 0) { str = $("#SelectBox1").combobox( "getText"); v = str + "," + v; } } if (sel2) { if (dd_id.length > 0) { str = $("#SelectBox2").combobox( "getText"); v = str + "," + v; } } if (sel3) { if (dd_id_2.length > 0) { str = $("#SelectBox3").combobox( "getText"); v = str + "," + v; } } var vs = new Array(); var vs1 = new Array(); vs = v.split(","); for (var x=0;x<vs.length;x++){ if($.inArray(vs[x], idooorTag)<0){ idooorTag.push(vs[x]); vs1.push(vs[x]); } } if(vs1.length>0){ var obj=getindoorName(aaf.dfobj,vs1); initData(obj,vs1,aaf.firstId,aaf.firstType,aaf.lastId,aaf.lastType,aaf.wl.wid,aaf.wl.hie,idooorTag); } display(vs); } else if (inside == 0) { outclick(wcdmalist, gsmlist,ltelist,psc_xlist, bcch_xlist,pci_xlist); } $('#zhibiao').dialog('close'); }); $("#div_point").show(); $("#background").hide(); $("#bar_id").hide(); $(document).css({ "overflow" : "auto" }); } } }); } // 树型菜单 var setting = { check : { enable : true }, data : { simpleData : { enable : true } }, callback : { onCheck : onCheck } }; function onCheck(e, treeId, treeNode) { } /** * 生成室内地图并对数据进行处理并调用Raphael相关画图JS方法 * 对2G、3G数据分别传入 * 判断第一个点并默认展示RSCP、RXLEV的轨迹 * @param gsmlist * @param wcdmalist * @param colorlist * @param psc_xlist * @param bcch_xlist */ function showIndoorPoint(gsmlist, wcdmalist,ltelist, colorlist, psc_xlist, bcch_xlist,pci_xlist,idooorTag) { var time_3g = "", time_2g = "",time_4g = "", id_3g,id_4g, id_2g; var real_t_3g, real_t_2g,real_t_4g; var time_3g_last = "", time_2g_last = "", id_3g_last,time_4g_last = "", id_4g_last, id_2g_last; var colorall = []; var arr_color = []; for ( var t = 0; t < colorlist.length; t++) { var color = colorlist[t]; arr_color.push(color.colourcode); } var psc_arr_color = []; for ( var j = arr_color.length - 1; j >= 0; j--) { psc_arr_color.push(arr_color[j]); } var dc = colorall.concat(psc_arr_color, colorRoom);// 两个颜色合并作为PSC颜色用 // 指标数据 var rscp = [], ecno = [], TxPower = [], psc = [], ftpSpeed = []; // 3G for ( var i = 0; i < wcdmalist.length; i++) { var wcdma = wcdmalist[i]; // RSCP if (wcdma.rscp != 0) { var colorid = wcdma.rscp - 1; var obj = { x : wcdma.x, y : wcdma.y, color : arr_color[colorid], id : wcdma.id, type : '2', va : wcdma.rscp_, reltype : wcdma.realnet_type }; rscp.push(obj); } // ECNO if (wcdma.ecno != 0) { var colorid = wcdma.ecno - 1; var obj = { x : wcdma.x, y : wcdma.y, color : arr_color[colorid], id : wcdma.id, type : '2', va : wcdma.ecno_, reltype : wcdma.realnet_type }; ecno.push(obj); } // TxPower if (wcdma.txpower != 0) { var colorid = wcdma.txpower - 1; var obj = { x : wcdma.x, y : wcdma.y, color : arr_color[colorid], id : wcdma.id, type : '2', va : wcdma.txpower_, reltype : wcdma.realnet_type }; TxPower.push(obj); } // FTP if (wcdma.ftpSpeed != 0) { var colorid = wcdma.ftpSpeed - 1; var obj = { x : wcdma.x, y : wcdma.y, color : arr_color[colorid], id : wcdma.id, type : '2', va : wcdma.ftpSpeed_, reltype : wcdma.realnet_type }; ftpSpeed.push(obj); } // PSC if (wcdma.psc) { var ij = $.inArray(wcdma.psc.toString(), psc_xlist); if (ij < 20) { var obj = { x : wcdma.x, y : wcdma.y, color : dc[ij], id : wcdma.id, type : '2', va : wcdma.psc, reltype : wcdma.realnet_type }; psc.push(obj); } } // 取第一个点 if (i == 0) { time_3g = wcdma.eptime; id_3g = wcdma.id; real_t_3g = wcdma.realnet_type; } if (i == wcdmalist.length-1) { time_3g_last = wcdma.eptime; id_3g_last = wcdma.id; } } // 指标数据 var rsrp = [], rsrq = [], snr = [], pci = [],ftpSpeed_4g=[]; //ftpSpeed=[]; // 4G for ( var i = 0; i < ltelist.length; i++) { var lte = ltelist[i]; // RSRP if (lte.rsrp != 0) { var colorid = lte.rsrp- 1; var obj = { x : lte.x, y : lte.y, color : arr_color[colorid], id : lte.id, type : '3', va : lte.rsrp_, reltype : lte.realnet_type }; rsrp.push(obj); } // RSRQ if (lte.rsrq != 0) { var colorid = lte.rsrq - 1; var obj = { x : lte.x, y : lte.y, color : arr_color[colorid], id : lte.id, type : '3', va : lte.rsrq_, reltype : lte.realnet_type }; rsrq.push(obj); } // SNR if (lte.snr != 0) { var colorid = lte.snr - 1; var obj = { x : lte.x, y : lte.y, color : arr_color[colorid], id : lte.id, type : '3', va : lte.snr_, reltype : lte.realnet_type }; snr.push(obj); } // FTP if (lte.ftpSpeed != 0) { var colorid = lte.ftpSpeed - 1; var obj = { x : lte.x, y : lte.y, color : arr_color[colorid], id : lte.id, type : '3', va : lte.ftpSpeed_, reltype : lte.realnet_type }; ftpSpeed_4g.push(obj); } // PCI if (lte.pci) { var ij = $.inArray(lte.pci.toString(), pci_xlist); if (ij < 20) { var obj = { x : lte.x, y : lte.y, color : dc[ij], id : lte.id, type : '3', va : lte.pci, reltype : lte.realnet_type }; pci.push(obj); } } // 取第一个点 if (i == 0) { time_4g = lte.eptime; id_4g = lte.id; real_t_4g = lte.realnet_type; } if (i == ltelist.length-1) { time_4g_last = lte.eptime; id_4g_last = lte.id; } } // 2G var rxlev = [], txpower_2g = [], rxqual = [], bcch = [], ci = [], mos = []; for ( var i = 0; i < gsmlist.length; i++) { var gsm = gsmlist[i]; // RxLev if (gsm.rxlev > 0) { var colorid = gsm.rxlev - 1; var obj = { x : gsm.x, y : gsm.y, color : arr_color[colorid], id : gsm.id, type : '1', va : gsm.rxlev_, reltype : gsm.realnet_type }; rxlev.push(obj); } // TxPower if (gsm.txpower > 0) { var colorid = gsm.txpower - 1; var obj = { x : gsm.x, y : gsm.y, color : arr_color[colorid], id : gsm.id, type : '1', va : gsm.txpower_, reltype : gsm.realnet_type }; txpower_2g.push(obj); } // rxqual if (gsm.rxqual > 0) { var colorid = gsm.rxqual - 1; var obj = { x : gsm.x, y : gsm.y, color : arr_color[colorid], id : gsm.id, type : '1', va : gsm.rxqual_, reltype : gsm.realnet_type }; rxqual.push(obj); } // ci if (gsm.ci > 0) { var colorid = gsm.ci - 1; var obj = { x : gsm.x, y : gsm.y, color : arr_color[colorid], id : gsm.id, type : '1', va : gsm.ci_, reltype : gsm.realnet_type }; ci.push(obj); } // mos if (gsm.mos > 0) { var colorid = gsm.mos - 1; var obj = { x : gsm.x, y : gsm.y, color : arr_color[colorid], id : gsm.id, type : '1', va : gsm.mos_, reltype : gsm.realnet_type }; mos.push(obj); } // bcch if (gsm.bcch) { var ij = $.inArray(gsm.bcch.toString(), bcch_xlist); if (ij < 20) { var obj = { x : gsm.x, y : gsm.y, color : dc[ij], id : gsm.id, type : '1', va : gsm.bcch, reltype : gsm.realnet_type }; bcch.push(obj); } } // 取第一个点 if (i == 0) { time_2g = gsm.eptime; id_2g = gsm.id; real_t_2g = gsm.realnet_type; } // 去最后一个点 if (i == gsmlist.length-1) { time_2g_last = gsm.eptime; id_2g_last = gsm.id; } } // 第一个比较时间大小,默认显示点 if (time_3g || time_2g||time_4g) { var tt_ty=""; if(time_3g!=''&&time_2g!=''){tt_ty=time_3g>time_2g?time_2g:time_3g;}else{if(time_3g!='')tt_ty=time_3g;if(time_2g!='')tt_ty=time_2g}; if(time_4g!=''&&tt_ty!=''){tt_ty=time_4g>tt_ty?tt_ty:time_4g;}else{if(tt_ty=="")tt_ty=time_4g;} if(tt_ty==time_3g){first_type=2;first_id=id_3g;clickPoint(first_type,first_id,real_t_3g);}; if(tt_ty==time_2g){first_type=1;first_id=id_2g;clickPoint(first_type,first_id,real_t_2g);}; if(tt_ty==time_4g){first_type=3;first_id=id_4g;clickPoint(first_type,first_id,real_t_4g);}; } // 最后一个点比较时间大小,默认显示点 if (time_3g_last|| time_2g_last||time_4g_last) { var tt_ty_la=""; if(time_3g_last!=''&&time_2g_last!=''){tt_ty_la=time_3g_last>time_2g_last?time_3g_last:time_2g_last;}else{if(time_3g_last!='')tt_ty_la=time_3g_last;if(time_2g_last!='')tt_ty_la=time_2g_last}; if(time_4g_last!=''&&tt_ty_la!=''){tt_ty_la=time_4g_last>tt_ty_la?time_4g_last:tt_ty_la;}else{if(tt_ty_la=="")tt_ty_la=time_4g_last} if(tt_ty_la==time_3g_last){last_type=2;last_id=id_3g_last;}; if(tt_ty_la==time_2g_last){last_type=1;last_id=id_2g_last;}; if(tt_ty_la==time_4g_last){last_type=3;last_id=id_4g_last;}; } var svgData = { // 入口的经纬度 origin : [ 106.54252000, 29.56392000 ], station : {} }; // 室内轨迹点数据 // var dd = new Object(); var dfobj=new Object(); if (rscp.length > 0) { dfobj.RSCP = rscp; } if (ecno.length > 0) { dfobj.EcNo = ecno; } if (TxPower.length > 0) { dfobj.TXPOWER = TxPower; } if (rsrp.length > 0) { dfobj.RSRP = rsrp; } if (rsrq.length > 0) { dfobj.RSRQ = rsrq; } if (snr.length > 0) { dfobj.SINR = snr; } if (psc.length > 0) { dfobj.PSC = psc; } if (pci.length > 0) { dfobj.PCI = pci; } if (ftpSpeed.length > 0) { dfobj.FTP3G = ftpSpeed; } if (ftpSpeed_4g.length > 0) { dfobj.FTP4G = ftpSpeed_4g; } //var db = new Object(); if (rxlev.length > 0) { dfobj.RXLEV = rxlev; } if (rxqual.length > 0) { dfobj.RXQUAL = rxqual; } if (ci.length > 0) { dfobj['C/I'] = ci; } if (bcch.length > 0) { dfobj.BCCH = bcch; } var s = new Array(); s.push("RSCP"); s.push("RXLEV"); s.push("RSRP"); idooorTag.push("RSCP"); idooorTag.push("RXLEV"); idooorTag.push("RSRP"); var aaf=new Object(); aaf.firstId=first_id; aaf.firstType=first_type; aaf.lastId=last_id; aaf.lastType=last_type; var obj=getindoorName(dfobj,s); svgData.datas = obj; var wl=initPaper(svgData.datas, s, first_id, first_type,last_id,last_type); aaf.wl=wl; aaf.dfobj=dfobj; return aaf; } function getindoorName(datas,vs){ var newObj=new Object(); var newObj2=new Object(); var newObj3=new Object(); if(vs.length>0){ for(var i=0;i<vs.length;i++){ if(vs[i]=='RSCP'||vs[i]=='EcNo'||vs[i]=='TXPOWER'||vs[i]=='PSC'||vs[i]=='FTP3G'){ if(datas[vs[i]])newObj[vs[i]]=datas[vs[i]];} if(vs[i]=='RSRP'||vs[i]=='RSRQ'||vs[i]=='SINR'||vs[i]=='PCI'||vs[i]=='FTP4G'){ if(datas[vs[i]])newObj3[vs[i]]=datas[vs[i]];} if(vs[i]=='RXLEV'||vs[i]=='RXQUAL'||vs[i]=='C/I'||vs[i]=='BCCH') {if(datas[vs[i]]) newObj2[vs[i]]=datas[vs[i]];} // if(vs[i]=='FTP'){ // if(datas[vs[i]]){ // if(datas[vs[i]][0].type==3) // newObj3[vs[i]]=datas[vs[i]]; // if(datas[vs[i]][0].type==2) // newObj[vs[i]]=datas[vs[i]]; // } // } } } var obj = new Object(); obj["3G"] = newObj; obj["2G"] = newObj2; obj["4G"] = newObj3; return obj; } /** * 点击地图中某一轨迹点时查询并展示详细数据 * * @param id * 点ID * @param type:2-WCDMA或是1-GSM * @realnet_type -1无服务 */ function clickPoint(type, id, realnet_type) { // 点图缩小时列表 if (realnet_type != -1) { $.ajax({ type : "post", url : contextPath + "/report/wcdmaOrGsm", data : ({ id : id, areaid:$("#areaid").val(), type : type }), success : function(data) { $('#div_page').html(data.content); // $('#div_page_max').html(data.contentMax); } }); } else { $('#div_page').html('<div class="noservice">No Service</div>'); } // 点图放大时列表 } /** * 室外多选对指标ID进行字符组装并调用chooseKpi方法 * @param doc */ function outclick(wcdmalist, gsmlist,ltelist,psc_xlist, bcch_xlist,pci_xlist) { $('.wrapper,#dialData').hide(); var obj_id = $("#undata_id").attr("value"); var sid = obj_id.split(","); var g3 = "",g2 = "",g4=""; for ( var i = 0; i < sid.length; i++) { switch (parseInt(sid[i])) { case 4: g3 += ",1"; break; case 5: g3 += ",2"; break; case 6: g3 += ",3"; break; case 7: g3 += ",4"; //g4 += ",4"; break; case 23: g3 += ",20"; break; case 9: g2 += ",6"; break; case 10: g2 += ",7"; break; case 11: g2 += ",8"; break; case 12: g2 += ",9"; break; case 24: g2 += ",21"; break; case 26: g4 += ",23"; break; case 27: g4 += ",24"; break; case 28: g4 += ",25"; break; case 29: g4 += ",26"; break; case 74: g4 += ",71"; break; default: break; } } g2 = g2.length > 0 ? g2.substring(1, g2.length) : ""; g3 = g3.length > 0 ? g3.substring(1, g3.length) : ""; g4 = g4.length > 0 ? g4.substring(1, g4.length) : ""; if (g2 != "") { chooseKpi(wcdmalist, gsmlist,ltelist, g2, "1", psc_xlist, bcch_xlist,pci_xlist); } else { for (i in markerArr_2g) { var m = markerArr_2g[i]; m.setMap(null); } markerArr_2g = []; exlatAndlngMap_2g.clear(); latAndlngMap_2g.clear(); } if (g3 != ""&&wcdmalist.length>0) { chooseKpi(wcdmalist, gsmlist,ltelist, g3, "2", psc_xlist, bcch_xlist,pci_xlist); } else { for (i in markerArr_3g) { var m = markerArr_3g[i]; m.setMap(null); } markerArr_3g = []; exlatAndlngMap_3g.clear(); latAndlngMap_3g.clear(); } if (g4 != ""&&ltelist.length>0) { chooseKpi(wcdmalist, gsmlist,ltelist, g4, "3", psc_xlist, bcch_xlist,pci_xlist); } else { for (i in markerArr_4g) { var m = markerArr_4g[i]; m.setMap(null); } markerArr_4g = []; exlatAndlngMap_4g.clear(); latAndlngMap_4g.clear(); } } /** * 计算页面宽度并改变页面里的地图与比例图组件宽度与高度 */ function changeWionw() { //计算宽度高度 var wid_len = (document.body.scrollWidth); var hie_len = wid_len * (9 / 16); $("#div_left").css("width", wid_len * 0.98); $("#div_left").css("height", hie_len); $("#div_point").css("width", (wid_len) * 0.98); $("#div_point").css("height", hie_len); $(".svg-div").css("width", wid_len); $(".svg-div").css("height", hie_len); $(".svg-div-main").css("width", wid_len); $(".svg-div-main").css("height", hie_len); $(".svg-main").css("width", wid_len * 3); $(".svg-main").css("height", hie_len * 3); $(".case_zhi").css("height", hie_len); $("#div_czj").css("height", hie_len); var wid = (document.body.scrollWidth - document.body.scrollWidth * 0.05) / 2; $(".histogram_flash").css("width", wid); } /** * 小数优化,把位数占位的0去掉,返回类型为string **/ function NumOptimize(num){ // 判断是否位小数 var param =/^\d+[.]\d+$/; if(param.test(num)){ var str = num.split("."); var lastNum; if(str.length=2){ var strSecond =str[1]; // 排除1.后面没有数的情况 for(var i=0;i<strSecond.length;i++){ var tempNum = strSecond.substring(strSecond.length-i-1,strSecond.length-i); if(parseInt(tempNum)!=0){ var index = strSecond.length-i; lastNum = str[0]+"."+strSecond.substring(0,index); return lastNum; } if(i==strSecond.length-1){ lastNum = str[0]; return lastNum; } } } }else{ return num; } } <file_sep>/src/main/java/com/complaint/service/TestMasterlogService.java package com.complaint.service; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.math.NumberUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.complaint.dao.BaseDao; import com.complaint.dao.GsmOwnLogDao; import com.complaint.dao.GsmTaskLogDao; import com.complaint.dao.LogSubmanualGsmDao; import com.complaint.dao.LteTrackLogDao; import com.complaint.dao.TestMasterlogDao; import com.complaint.dao.WcdmsOwnLogDao; import com.complaint.dao.WcdmsTaskLogDao; import com.complaint.dao.WcdmsTrackLogDao; import com.complaint.dao.WorkOrderDao; import com.complaint.mina.MinaServerHandler; import com.complaint.model.LogSubmanualGsm; import com.complaint.model.LogSubmanualLte; import com.complaint.model.MyLLOffset; import com.complaint.model.TCasCell; import com.complaint.model.TestMasterlog; import com.complaint.model.WcdmsTrackLog; import com.complaint.model.WorkOrder; import com.complaint.utils.DateUtils; import com.complaint.utils.MapUtil; import cn.zhugefubin.maptool.ConverterTool; import cn.zhugefubin.maptool.Point; @Service("testMasterlogService") public class TestMasterlogService { private static final Logger logger = LoggerFactory.getLogger(MinaServerHandler.class); private static Integer sequence; private static Map<Integer, String> netTypeMap; @Autowired private BaseDao baseDao; @Autowired private TestMasterlogDao testMasterlogDao; @Autowired private WorkOrderDao workOrderDao; @Autowired private LogSubmanualGsmDao logSubmanualGsmDao; @Autowired private WcdmsTrackLogDao wcdmsTrackLogDao; @Autowired private LteTrackLogDao lteTrackLogDao; @Autowired private GsmTaskLogDao gsmTaskLogDao; @Autowired private WcdmsTaskLogDao wcdmsTaskLogDao; @Autowired private GsmOwnLogDao gsmOwnLogDao; @Autowired private WcdmsOwnLogDao wcdmsOwnLogDao; // @Autowired // private WcdmsTrackLogDao wcdmsTrackLogDao; public void initNetTypeList(){ netTypeMap = new HashMap<Integer, String>(); netTypeMap.put(0, "3G"); netTypeMap.put(1, "2G"); netTypeMap.put(2, "2G"); netTypeMap.put(3, "3G"); netTypeMap.put(4, "2G"); netTypeMap.put(5, "3G"); netTypeMap.put(6, "3G"); netTypeMap.put(7, "3G"); netTypeMap.put(8, "3G"); netTypeMap.put(9, "3G"); netTypeMap.put(10, "3G"); netTypeMap.put(11, "3G"); netTypeMap.put(12, "3G"); netTypeMap.put(13, "4G");//LTE为4G netTypeMap.put(14, "3G"); netTypeMap.put(15, "3G"); } private String getSerialNo(){ return DateUtils.getNowByFormat("yyyyMMddHHmmss") + this.querySequence(); } private synchronized int querySequence(){ if(sequence == null || sequence % 100 == 0){ sequence = this.testMasterlogDao.querySequence(); sequence = sequence * 100 + 1; }else{ sequence++; } return sequence; } @Transactional public void addTestReport(JSONObject json) throws RuntimeException{ logger.debug("get in =====>addTestReport"); //插入测试头部信息 TestMasterlog master = new TestMasterlog(); master = init(json, master); this.addReportHead(master); //插入测试明细信息 this.addReportBody(json,master); //修改投诉工单表里的测试次数 if(json.get("stype")==null||json.get("stype").toString().equals("1")){ this.modifyOrderstatus(master); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); logger.debug("ReciveUpTestData====>id:"+master.getId()+"|serialno:"+master.getSerialno()+"|flowid:"+master.getFlowid()+"|test_num:"+ master.getTestNumber()+"|uuid:"+master.getImei()+"|test_phone:"+master.getTestphone()+ "|test_adress:"+master.getTestaddress()+"|test_time:"+sdf.format(master.getTesttime())+"|test_endtime:"+sdf.format(master.getTestendtime())); } private TestMasterlog init(JSONObject json,TestMasterlog master){ master.setFlowid(this.getSerialNo()); //测试流水号 String sno = json.get("sno").toString(); logger.debug("当前测试工单号:" + sno); master.setSerialno(sno);//工单号 master.setTestphone(json.get("pid")+""); //测试手机号码 master.setId(json.get("id")==null?"":json.get("id").toString());//工单流水号 master.setAreaid(Integer.parseInt(json.get("areaid")==null?"":json.get("areaid").toString()));//测试区域 master.setOrderType(Short.parseShort(json.get("stype")!=null?json.get("stype").toString():"1")); //工单类型 //判断上报测试工单的类型(1投诉工单 2 任务工单 3自主测试工单) if(json.get("stype")==null||json.get("stype").toString().equals("1")){ master.setOrders((short)(this.testMasterlogDao.queryOrderNum(sno) + 1));//当前第几次测试 }else if(json.get("stype").toString().equals("2")){ master.setOrders((short)(this.testMasterlogDao.queryTaskOrderNum(sno) + 1));//当前第几次测试 }else if(json.get("stype").toString().equals("3")){ master.setOrders((short)(this.testMasterlogDao.queryOwnOrderNum(sno) + 1));//当前第几次测试 //取出工单创建时间和测试环节 master.setCreateDate(getDateByLong(Long.parseLong(json.get("scti").toString()))); master.setBreakflag(Short.parseShort(json.get("breakflag").toString())); } master.setTesttime(getDateByLong(Long.parseLong(json.get("ti").toString())));//测试时间 master.setImei(json.get("imei").toString()); //唯一标识 master.setFailure(json.get("fail")+""); //故障 short inside = Short.parseShort(json.get("is").toString()); master.setInside(inside);//1室内 0室外 master.setTestaddress(json.get("tsa")+""); //测试地址 master.setSceneid(Short.parseShort(json.get("si").toString()));//情景id master.setDensity(Short.parseShort(json.get("ds").toString()));//0占位 1 密集 2稀疏 master.setIsindoor(Short.parseShort(json.get("idr").toString())); //室分,室内专用 0占位 1有 2无 master.setObstruct(Short.parseShort(json.get("ob").toString()));//0 无阻挡 1 有阻挡 master.setDescription(json.get("de") == null ? null : json.get("de").toString());//描述 master.setIsRepair(json.get("isRepair") == null?-1:Integer.parseInt(json.get("isRepair").toString()));//是否修复 master.setVersion(json.get("version") == null?"1.2.0":json.get("version").toString());//版本号 String dtp = null; try { dtp = json.get("dtp").toString(); } catch (Exception e) { dtp = "0"; } master.setRoom_type(Integer.parseInt(dtp));//0表示其他, 1表示2G室分, 2表示3G室分,3 表示 2g+3g室分,4表示4g,5表示2g+3g+4g Object o = json.get("ltgt"); if(o != null){ master.setGpsType(Short.parseShort(o.toString()));//经纬度类型 1 百度 0 google BigDecimal lng = new BigDecimal(NumberUtils.toDouble(json.get("lng")+"")); //经度 BigDecimal lat = new BigDecimal(NumberUtils.toDouble(json.get("lat")+"")); //纬度 MyLLOffset myLLOffset = MapUtil.getMyLLOffset(master.getGpsType(), lng, lat); master.setLongitudeModify(myLLOffset.getNewLng()); //纠偏后经度 master.setLatitudeModify(myLLOffset.getNewLat()); //纠偏后纬度 if(master.getLatitudeModify()!=null&&master.getLongitudeModify()!=null){ ConverterTool ctl=new ConverterTool(); Point point = ctl.GG2BD(master.getLongitudeModify().doubleValue(), master.getLatitudeModify().doubleValue()); master.setLongitudeBmap(new BigDecimal(point.getLongitude())); //百度纠偏后经度 master.setLatitudeBmap(new BigDecimal(point.getLatitude())); //百度纠偏后纬度 } master.setLongitude(myLLOffset.getOldLng()); //室外原始经度 master.setLatitude(myLLOffset.getOldLat()); //室外原始纬度 } master.setNetsystem(Short.parseShort(json.get("ns").toString())); //网络制式:1 联通gsm锁频 2 wcdma锁频 3 wcdma 自由模式 4 lte锁频 5 lte自由模式 master.setTeststatus(Short.parseShort(json.get("ts").toString())); //手机状态:1表示Idle,2表示语音服务,3表示数据业务 master.setCalltype(Short.parseShort(json.get("ct").toString())); //长呼叫, 0占位 1 短呼 2 长呼 short ftptype = Short.parseShort(json.get("fud").toString()); //ftp上行或下行, 1 上行 2 下行 0 未测试数据业务 master.setFtpUpdown(ftptype); //有ftp业务时 if(ftptype != 0){ master.setFtpMaxSpeed(BigDecimal.valueOf(Double.parseDouble(json.get("fma").toString()))); //ftp最大速度 master.setFtpMinSpeed(BigDecimal.valueOf(Double.parseDouble(json.get("fmi").toString()))); //ftp最小速度 master.setFtpAvgSpeed(BigDecimal.valueOf(Double.parseDouble(json.get("fvg").toString()))); //ftp平均速度 master.setFtpMaxSpeedLte(BigDecimal.valueOf(json.get("fmat")!=null?Double.parseDouble(json.get("fmat").toString()):-9999)); //LTE ftp最大速度 master.setFtpMinSpeedLte(BigDecimal.valueOf(json.get("fmit")!=null?Double.parseDouble(json.get("fmit").toString()):-9999)); //LTE ftp最小速度 master.setFtpAvgSpeedLte(BigDecimal.valueOf(json.get("fvgt")!=null?Double.parseDouble(json.get("fvgt").toString()):-9999)); //LTE ftp平均速度 master.setPinglo(Double.parseDouble(json.get("pl").toString())); //PING丢包率 master.setPingdmax(Double.parseDouble(json.get("pma").toString())); //ping最大延迟 master.setPingdmix(Double.parseDouble(json.get("pmi").toString())); //ping最小延迟 master.setPingdavg(Double.parseDouble(json.get("pav").toString())); //ping平均延迟 master.setHttptmax(Double.parseDouble(json.get("hmac").toString())); //HTTP最大响应时间 master.setHttptmix(Double.parseDouble(json.get("hmic").toString())); //HTTP最小响应时间 master.setHttptavg(Double.parseDouble(json.get("havc").toString())); //HTTP平均响应时间 master.setHttpsmax(Double.parseDouble(json.get("hmad").toString())); //HTTP最大下载速度 master.setHttpsmin(Double.parseDouble(json.get("hmid").toString())); //HTTP最小下载速度 master.setHttpsavg(Double.parseDouble(json.get("havd").toString())); //HTTP平均下载速度 } master.setTestphone(json.get("pid").toString()); //测试手机号码 master.setTestendtime(getDateByLong(Long.parseLong(json.get("tedt").toString()))); if(master.getCalltype() != 0){ master.setCallphone(json.get("cph").toString()); if(master.getCalltype() == 1){ //短呼才有下面 1为短呼 master.setSpace(new BigDecimal(Double.parseDouble(json.get("spce").toString()))); master.setDuration(new BigDecimal(Double.parseDouble(json.get("dura").toString()))); } } return master; } private void addReportHead(TestMasterlog master) throws RuntimeException { logger.debug("========>ready to insert master"); try { //判断不同类型的工单测试入不同的测试总表 if(master.getOrderType()==1){//投诉工单 this.testMasterlogDao.insert(master); }else if(master.getOrderType()==2){//任务工单 this.testMasterlogDao.insertTask(master); }else if(master.getOrderType()==3){//自主工单 //如果是自主工单的第一次上报,先把上报的自主工单存入自主工单表 if(master.getOrders()==1){ workOrderDao.insertOwnWorkOrder(master); } //自主工单测试总表 this.testMasterlogDao.insertOwn(master); } } catch (Exception e) { logger.error("addReportHead invoke error。"+e.getMessage(), e); //判断不同类型的工单,执行不同的回退方式 if(master.getOrderType()==1){//投诉工单 this.deleteDataByFlowid(master.getFlowid()); }else if(master.getOrderType()==2){//任务工单 this.deleteTaskByFlowid(master.getFlowid()); }else if(master.getOrderType()==3){//自主工单 this.deleteOwnByFlowid(master.getFlowid()); } throw new RuntimeException(e); } } private void modifyOrderstatus(TestMasterlog master) throws RuntimeException { try { WorkOrder wo = new WorkOrder(); wo.setSerialno(master.getSerialno()); wo.setTestNumber(1); wo.setIsDeal((short)1); wo.setAreaId(master.getAreaid()); wo.setId(master.getId()); workOrderDao.updateWOTestNumber(wo); } catch (Exception e) { logger.error("modifyOrderstatus invoke error。"+e.getMessage(), e); this.deleteDataByFlowid(master.getFlowid()); throw new RuntimeException(e); } } private void addReportBody(JSONObject json,TestMasterlog master) throws RuntimeException{ JSONArray array = (JSONArray)json.get("ctt"); JSONObject subJson = null; List<LogSubmanualGsm> gsmList = new ArrayList<LogSubmanualGsm>(); List<WcdmsTrackLog> wcdmList = new ArrayList<WcdmsTrackLog>(); List<LogSubmanualLte> lteList = new ArrayList<LogSubmanualLte>(); Map<String, Object> map = new HashMap<String, Object>(); for(int i=0;i<array.size();i++){ subJson = (JSONObject)array.get(i); if("2G".equals(this.checkNetType(Integer.parseInt(subJson.get("nt").toString())))){ this.addGsmToList(gsmList,subJson,master); }else if(subJson.get("nt").toString().equals("-1")){ if(subJson.get("rsr")!=null&&subJson.get("rsr").toString().equals("-9998")){ this.addLteToList(lteList,subJson,master); }else if(subJson.get("rscp")!=null&&subJson.get("rscp").toString().equals("-9998")){ this.addWcdmsToList(wcdmList,subJson,master,map); }else if(subJson.get("rlf")!=null&&subJson.get("rlf").toString().equals("-9998")){ this.addGsmToList(gsmList,subJson,master); } }else if("4G".equals(this.checkNetType(Integer.parseInt(subJson.get("nt").toString())))){ //4G数据入库 this.addLteToList(lteList,subJson,master); }else{ this.addWcdmsToList(wcdmList,subJson,master,map); } } /*for (int i = 0; i < gsmList.size(); i++) { //if(gsmList.size()>0){ logSubmanualGsmDao.insert(gsmList.get(i)); //} } for (int i = 0; i < wcdmList.size(); i++) { wcdmsTrackLogDao.insert(wcdmList.get(i)); }*/ try { //根据不同的工单类型判断不同的批量插入 if(master.getOrderType()==1){//投诉工单 baseDao.batchInsert(LogSubmanualGsmDao.class, gsmList, 300); baseDao.batchInsert(WcdmsTrackLogDao.class, wcdmList, 300); baseDao.batchInsert(LteTrackLogDao.class, lteList, 300); }else if(master.getOrderType()==2){//任务工单 baseDao.batchInsert(GsmTaskLogDao.class, gsmList, 300); baseDao.batchInsert(WcdmsTaskLogDao.class, wcdmList, 300); }else if(master.getOrderType()==3){//自主工单 baseDao.batchInsert(GsmOwnLogDao.class, gsmList, 300); baseDao.batchInsert(WcdmsOwnLogDao.class, wcdmList, 300); } } catch (Exception e) { logger.error("batchInsert error!message["+e.getMessage()+"]", e); String flowid = ""; WcdmsTrackLog wcdmaLog = wcdmList.get(0); if(wcdmaLog == null){ LogSubmanualGsm gsmLog = gsmList.get(0); flowid = gsmLog == null ? "" : gsmLog.getFlowid(); }else{ flowid = wcdmaLog.getFlowid(); } if(!"".equals(flowid)){ //判断不同类型的工单,执行不同的回退方式 if(master.getOrderType()==1){//投诉工单 this.deleteDataByFlowid(master.getFlowid()); }else if(master.getOrderType()==2){//任务工单 this.deleteTaskByFlowid(master.getFlowid()); }else if(master.getOrderType()==3){//自主工单 this.deleteOwnByFlowid(master.getFlowid()); } } throw new RuntimeException(e.getMessage()); } logger.debug("===>insert success!"); } //投诉工单的回滚 @Transactional private void deleteDataByFlowid(String flowid){ if(flowid != null && !"".equals(flowid)){ wcdmsTrackLogDao.delWcdmaByFlowid(flowid); logSubmanualGsmDao.delGsmByFlowid(flowid); } } //任务工单的回滚 @Transactional private void deleteTaskByFlowid(String flowid){ if(flowid != null && !"".equals(flowid)){ wcdmsTaskLogDao.delTaskWcdmaByFlowid(flowid); gsmTaskLogDao.delTaskGsmByFlowid(flowid); } } //自主工单的回滚 @Transactional private void deleteOwnByFlowid(String flowid){ if(flowid != null && !"".equals(flowid)){ wcdmsOwnLogDao.delOwnWcdmaByFlowid(flowid); gsmOwnLogDao.delOwnGsmByFlowid(flowid); } } private String checkNetType(Integer typeid){ if(netTypeMap == null) this.initNetTypeList(); return netTypeMap.get(typeid); } private void addGsmToList(List<LogSubmanualGsm> gsmList,JSONObject json,TestMasterlog master){ LogSubmanualGsm gsm = new LogSubmanualGsm(); gsm.setFlowid(master.getFlowid()); //当前测试流水号 gsm.setUuid(master.getImei()); //终端唯一标识 gsm.setInside(master.getInside()); //室内/室外 gsm.setEpTime(getDateByLong(NumberUtils.toLong(json.get("td").toString()))); //终端时间 gsm.setTesttime(master.getTesttime());//测试时间与测试总表一致 gsm.setAreaid(master.getAreaid()); if(master.getInside() == 0){ //0为室外 室外才有 BigDecimal lng = new BigDecimal((json.get("lng").toString())); //室外 原始经度 BigDecimal lat = new BigDecimal((json.get("lat").toString())); //室外 原始纬度 short gpsType = Short.parseShort(json.get("ltgt").toString()); gsm.setGpsType(gpsType); MyLLOffset myLLOffset = MapUtil.getMyLLOffset(gpsType, lng, lat); gsm.setLongitudeModify(myLLOffset.getNewLng()); //室外 纠正经度 gsm.setLatitudeModify(myLLOffset.getNewLat()); // 室外 纠正纬度 if(gsm.getLatitudeModify()!=null&&gsm.getLongitudeModify()!=null){ ConverterTool ctl=new ConverterTool(); Point point = ctl.GG2BD(gsm.getLongitudeModify().doubleValue(), gsm.getLatitudeModify().doubleValue()); gsm.setLongitudeBmap(new BigDecimal(point.getLongitude())); //百度纠偏后经度 gsm.setLatitudeBmap(new BigDecimal(point.getLatitude())); //百度纠偏后纬度 } gsm.setLongitude(myLLOffset.getOldLng()); //室外原始经度 gsm.setLatitude(myLLOffset.getOldLat()); //室外原始纬度 } else if(master.getInside() == 1){ //室内才有 1为室内 gsm.setPositionX(new BigDecimal(Double.parseDouble(json.get("px").toString()))); //室内 x轴坐标 gsm.setPositionY(new BigDecimal(Double.parseDouble(json.get("py").toString()))); //室内 y轴坐标 } gsm.setRealnetType(Short.parseShort(json.get("nt").toString())); //实际网络 gsm.setLac(Long.parseLong(json.get("lac").toString())); //lac gsm.setCid(Long.parseLong(json.get("cid").toString())); //cid gsm.setBsic((Long)json.get("bsic")); //bsic gsm.setBcch((Long)json.get("bcch")); //bcch gsm.setRxlevSub((Long)json.get("rls")); //rxLev_sub gsm.setRxlevFull((Long)json.get("rlf")); //rxLev_full if(json.get("rqs") != null){ gsm.setRxqualSub(new BigDecimal(Double.parseDouble(json.get("rqs").toString()))); //rxQual_sub } if(json.get("rqf") != null){ gsm.setRxqualFull(new BigDecimal(Double.parseDouble(json.get("rqf").toString()))); //rxQual_full } if(json.get("ci") != null){ gsm.setcI(new BigDecimal(Double.parseDouble(json.get("ci").toString()))); //c/i } if(json.get("tp") != null){ gsm.setTxpower(new BigDecimal(Double.parseDouble(json.get("tp").toString()))); //txpower } gsm.setMos((Long)json.get("mos")); //mos gsm.setTa(json.get("ta") == null ? null : Integer.parseInt(json.get("ta").toString()));//ta gsm.setBsic1((Long)json.get("bs1")); //bsic_1 gsm.setBsic2((Long)json.get("bs2")); //bsic_2 gsm.setBsic3((Long)json.get("bs3")); //bsic_3 gsm.setBsic4((Long)json.get("bs4")); //bsic_4 gsm.setBsic5((Long)json.get("bs5")); //bsic_5 gsm.setBsic6((Long)json.get("bs6")); //bsic_6 gsm.setBcch1((Long)json.get("bc1")); //bcch_1 gsm.setBcch2((Long)json.get("bc2")); //bcch_2 gsm.setBcch3((Long)json.get("bc3")); //bcch_3 gsm.setBcch4((Long)json.get("bc4")); //bcch_4 gsm.setBcch5((Long)json.get("bc5")); //bcch_5 gsm.setBcch6((Long)json.get("bc6")); //bcch_6 gsm.setRxlev1((Long)json.get("rx1")); //rxlev_1 gsm.setRxlev2((Long)json.get("rx2")); //rxlev_2 gsm.setRxlev3((Long)json.get("rx3")); //rxlev_3 gsm.setRxlev4((Long)json.get("rx4")); //rxlev_4 gsm.setRxlev5((Long)json.get("rx5")); //rxlev_5 gsm.setRxlev6((Long)json.get("rx6")); //rxlev_6 gsm.setC1(json.get("c1") == null ? null : Integer.parseInt(json.get("c1").toString()));//c1 gsm.setC2(json.get("c2") == null ? null : Integer.parseInt(json.get("c2").toString()));//c2 gsm.setC11(json.get("c1_1") == null ? null : Integer.parseInt(json.get("c1_1").toString()));//c11 gsm.setC21(json.get("c2_1") == null ? null : Integer.parseInt(json.get("c2_1").toString()));//c21 gsm.setC12(json.get("c1_2") == null ? null : Integer.parseInt(json.get("c1_2").toString()));//c12 gsm.setC22(json.get("c2_2") == null ? null : Integer.parseInt(json.get("c2_2").toString()));//c22 gsm.setC13(json.get("c1_3") == null ? null : Integer.parseInt(json.get("c1_3").toString()));//c13 gsm.setC23(json.get("c2_3") == null ? null : Integer.parseInt(json.get("c2_3").toString()));//c23 gsm.setC14(json.get("c1_4") == null ? null : Integer.parseInt(json.get("c1_4").toString()));//c14 gsm.setC24(json.get("c2_4") == null ? null : Integer.parseInt(json.get("c2_4").toString()));//c24 gsm.setC15(json.get("c1_5") == null ? null : Integer.parseInt(json.get("c1_5").toString()));//c15 gsm.setC25(json.get("c2_5") == null ? null : Integer.parseInt(json.get("c2_5").toString()));//c25 gsm.setC16(json.get("c1_6") == null ? null : Integer.parseInt(json.get("c1_6").toString()));//c16 gsm.setC26(json.get("c2_6") == null ? null : Integer.parseInt(json.get("c2_6").toString()));//c26 gsmList.add(gsm); } private void addWcdmsToList(List<WcdmsTrackLog> wcdmList,JSONObject json,TestMasterlog master,Map map){ short inside = master.getInside(); //找到前一个CID与LAC TCasCell cell=null; //当业务态下要看前一条数据计算CID、LAC WcdmsTrackLog wcdm = new WcdmsTrackLog(); WcdmsTrackLog wt=null; if(wcdmList!=null&&wcdmList.size()>0&&json.get("tp") != null){ map.put("lac", wcdmList.get(wcdmList.size()-1).getLac()); map.put("cid", wcdmList.get(wcdmList.size()-1).getCid()); map.put("psc", Integer.parseInt(json.get("psc").toString())); cell=this.testMasterlogDao.updateCidLac(map); if(cell!=null){ map.put("celllat", cell.getCelllat()); map.put("celllng", cell.getCelllng()); if(inside == 0){ map.put("lat", json.get("lat").toString()); map.put("lng", json.get("lng").toString()); }else{ map.put("lat", master.getLatitude()); map.put("lng", master.getLongitude()); } wt=this.testMasterlogDao.updateCidLacBylatlng(map); if(wt!=null&&cell.getLac().equals(wt.getLac())&&cell.getCellId().equals(wt.getCid())){ wcdm.setIsequal((short) 0); }else{ wcdm.setIsequal((short) 1); } }else{ wcdm.setIsequal((short) 0); } wcdm.setLac_1(cell==null?Long.parseLong(json.get("lac").toString()):cell.getLac()); //lac wcdm.setCid_1(cell==null?Long.parseLong(json.get("cid").toString()):cell.getCellId()); //cid wcdm.setLac_2(wt==null?Long.parseLong(json.get("lac").toString()):wt.getLac()); //lac wcdm.setCid_2(wt==null?Long.parseLong(json.get("cid").toString()):wt.getCid()); //cid wcdm.setRange(wt==null?0:wt.getRange()); }else{ wcdm.setLac_1(Long.parseLong(json.get("lac").toString())); //lac wcdm.setCid_1(Long.parseLong(json.get("cid").toString())); //cid wcdm.setLac_2(Long.parseLong(json.get("lac").toString())); //lac wcdm.setCid_2(Long.parseLong(json.get("cid").toString())); //cid wcdm.setRange((long) 0); wcdm.setIsequal((short) 0); } wcdm.setFlowid(master.getFlowid());//当前测试流水号 wcdm.setUuid(master.getImei()); //终端唯一标识 wcdm.setAreaid(master.getAreaid()); wcdm.setInside(inside); //室内/室外 wcdm.setFtptype(master.getFtpUpdown()); //ftp上传下载 wcdm.setEpTime(getDateByLong(NumberUtils.toLong(json.get("td").toString()))); //终端时间 wcdm.setTesttime(master.getTesttime());//测试时间与总表一致 //0室外 if(inside == 0){ // 1 百度 0 google short gpsType = Short.parseShort(json.get("ltgt").toString()); wcdm.setGpsType(gpsType); BigDecimal lng = new BigDecimal(Double.parseDouble(json.get("lng").toString())); //室外 原始经度 BigDecimal lat = new BigDecimal(Double.parseDouble(json.get("lat").toString())); //室外 原始纬度 MyLLOffset myLLOffset = MapUtil.getMyLLOffset(gpsType, lng, lat); wcdm.setLongitudeModify(myLLOffset.getNewLng()); //室外 纠正经度 wcdm.setLatitudeModify(myLLOffset.getNewLat()); // 室外 纠正纬度 if(wcdm.getLatitudeModify()!=null&&wcdm.getLongitudeModify()!=null){ ConverterTool ctl=new ConverterTool(); Point point = ctl.GG2BD(wcdm.getLongitudeModify().doubleValue(), wcdm.getLatitudeModify().doubleValue()); wcdm.setLongitudeBmap(new BigDecimal(point.getLongitude())); //百度纠偏后经度 wcdm.setLatitudeBmap(new BigDecimal(point.getLatitude())); //百度纠偏后纬度 } wcdm.setLongitude(myLLOffset.getOldLng()); //室外原始经度 wcdm.setLatitude(myLLOffset.getOldLat()); //室外原始纬度 }else{ wcdm.setPositionX(new BigDecimal(Double.parseDouble(json.get("px").toString()))); //室内 x轴坐标 wcdm.setPositionY(new BigDecimal(Double.parseDouble(json.get("py").toString()))); //室内 y轴坐标 } wcdm.setRealnetType(Short.parseShort(json.get("nt").toString())); //实际网络 wcdm.setLac(Long.parseLong(json.get("lac").toString())); //lac wcdm.setCid(Long.parseLong(json.get("cid").toString())); //cid wcdm.setPsc(Integer.parseInt(json.get("psc").toString())); //psc wcdm.setFrequl(Integer.parseInt(json.get("afup").toString())); //freq_ul wcdm.setFreqdl(Integer.parseInt(json.get("afdn").toString())); //freq_dl wcdm.setRscp(Integer.parseInt(json.get("rscp").toString())); //rscp wcdm.setEcNo(Integer.parseInt(json.get("ecno").toString())); //ecno if(json.get("tp") != null){ wcdm.setTxpower(new BigDecimal(Double.parseDouble(json.get("tp").toString()))); //txpower } if(json.get("fs") != null){ wcdm.setFtpSpeed(new BigDecimal(Double.parseDouble(json.get("fs").toString()))); //ftp_speed } wcdm.setType(json.get("ltp")!=null?Short.parseShort(json.get("ltp").toString()):0); //0-正常3G测试数据 1- LTE模式获取不完整测试数据类型 wcdm.setaPsc1(json.get("pa1") == null? null : Integer.parseInt(json.get("pa1").toString())); //a_psc_1 wcdm.setaPsc2(json.get("pa2") == null? null : Integer.parseInt(json.get("pa2").toString())); //a_psc_2 wcdm.setaPsc3(json.get("pa3") == null? null : Integer.parseInt(json.get("pa3").toString())); //a_psc_3 wcdm.setmPsc1(json.get("pm1") == null? null : Integer.parseInt(json.get("pm1").toString())); //m_psc_1 wcdm.setmPsc2(json.get("pm2") == null? null : Integer.parseInt(json.get("pm2").toString())); //m_psc_2 wcdm.setmPsc3(json.get("pm3") == null? null : Integer.parseInt(json.get("pm3").toString())); //m_psc_3 wcdm.setmPsc4(json.get("pm4") == null? null : Integer.parseInt(json.get("pm4").toString())); //m_psc_4 wcdm.setmPsc5(json.get("pm5") == null? null : Integer.parseInt(json.get("pm5").toString())); //m_psc_5 wcdm.setmPsc6(json.get("pm6") == null? null : Integer.parseInt(json.get("pm6").toString())); //m_psc_6 wcdm.setdPsc1(json.get("pd1") == null? null : Integer.parseInt(json.get("pd1").toString())); //d_psc_1 wcdm.setdPsc2(json.get("pd2") == null? null : Integer.parseInt(json.get("pd2").toString())); //d_psc_2 wcdm.setaRscp1(json.get("ra1") == null? null : Integer.parseInt(json.get("ra1").toString())); //a_rscp_1 wcdm.setaRscp2(json.get("ra2") == null? null : Integer.parseInt(json.get("ra2").toString())); //a_rscp_2 wcdm.setaRscp3(json.get("ra3") == null? null : Integer.parseInt(json.get("ra3").toString())); //a_rscp_3 wcdm.setmRscp1(json.get("rm1") == null? null : Integer.parseInt(json.get("rm1").toString())); //m_rscp_1 wcdm.setmRscp2(json.get("rm2") == null? null : Integer.parseInt(json.get("rm2").toString())); //m_rscp_2 wcdm.setmRscp3(json.get("rm3") == null? null : Integer.parseInt(json.get("rm3").toString())); //m_rscp_3 wcdm.setmRscp4(json.get("rm4") == null? null : Integer.parseInt(json.get("rm4").toString())); //m_rscp_4 wcdm.setmRscp5(json.get("rm5") == null? null : Integer.parseInt(json.get("rm5").toString())); //m_rscp_5 wcdm.setmRscp6(json.get("rm6") == null? null : Integer.parseInt(json.get("rm6").toString())); //m_rscp_6 wcdm.setdRscp1(json.get("rd1") == null? null : Integer.parseInt(json.get("rd1").toString())); //d_rscp_1 wcdm.setdRscp2(json.get("rd2") == null? null : Integer.parseInt(json.get("rd2").toString())); //d_rscp_2 wcdm.setaEcNo1(json.get("ea1") == null? null : Integer.parseInt(json.get("ea1").toString())); //a_ec/no_1 wcdm.setaEcNo2(json.get("ea2") == null? null : Integer.parseInt(json.get("ea2").toString())); //a_ec/no_2 wcdm.setaEcNo3(json.get("ea3") == null? null : Integer.parseInt(json.get("ea3").toString())); //a_ec/no_3 wcdm.setmEcNo1(json.get("em1") == null? null : Integer.parseInt(json.get("em1").toString())); //m_ec_no_1 wcdm.setmEcNo2(json.get("em2") == null? null : Integer.parseInt(json.get("em2").toString())); //m_ec_no_2 wcdm.setmEcNo3(json.get("em3") == null? null : Integer.parseInt(json.get("em3").toString())); //m_ec_no_3 wcdm.setmEcNo4(json.get("em4") == null? null : Integer.parseInt(json.get("em4").toString())); //m_ec_no_4 wcdm.setmEcNo5(json.get("em5") == null? null : Integer.parseInt(json.get("em5").toString())); //m_ec_no_5 wcdm.setmEcNo6(json.get("em6") == null? null : Integer.parseInt(json.get("em6").toString())); //m_ec_no_6 wcdm.setdEcNo1(json.get("ed1") == null? null : Integer.parseInt(json.get("ed1").toString())); //d_ec_no_1 wcdm.setdEcNo2(json.get("ed2") == null? null : Integer.parseInt(json.get("ed2").toString())); //d_ec_no_2 wcdm.setaArfcn1(json.get("aa1") == null? null : Integer.parseInt(json.get("aa1").toString())); //a_arfcn_1 wcdm.setaArfcn2(json.get("aa2") == null? null : Integer.parseInt(json.get("aa2").toString())); //a_arfcn_2 wcdm.setaArfcn3(json.get("aa3") == null? null : Integer.parseInt(json.get("aa3").toString())); //a_arfcn_3 wcdm.setmArfcn1(json.get("am1") == null? null : Integer.parseInt(json.get("am1").toString())); //m_arfcn_1 wcdm.setmArfcn2(json.get("am2") == null? null : Integer.parseInt(json.get("am2").toString())); //m_arfcn_2 wcdm.setmArfcn3(json.get("am3") == null? null : Integer.parseInt(json.get("am3").toString())); //m_arfcn_3 wcdm.setmArfcn4(json.get("am4") == null? null : Integer.parseInt(json.get("am4").toString())); //m_arfcn_4 wcdm.setmArfcn5(json.get("am5") == null? null : Integer.parseInt(json.get("am5").toString())); //m_arfcn_5 wcdm.setmArfcn6(json.get("am6") == null? null : Integer.parseInt(json.get("am6").toString())); //m_arfcn_6 wcdm.setdArfcn1(json.get("ad1") == null? null : Integer.parseInt(json.get("ad1").toString())); //d_arfcn_1 wcdm.setdArfcn2(json.get("ad2") == null? null : Integer.parseInt(json.get("ad2").toString())); //d_arfcn_2 wcdmList.add(wcdm); } /** * 4G数据组装 * @param lteList * @param json * @param master * @param map */ private void addLteToList(List<LogSubmanualLte> lteList,JSONObject json,TestMasterlog master){ LogSubmanualLte lte = new LogSubmanualLte(); lte.setFlowid(master.getFlowid()); //当前测试流水号 lte.setUuid(master.getImei()); //终端唯一标识 lte.setInside(master.getInside()); //室内/室外 lte.setEpTime(getDateByLong(NumberUtils.toLong(json.get("td").toString()))); //终端时间 lte.setTesttime(master.getTesttime());//测试时间与测试总表一致 lte.setAreaid(master.getAreaid()); if(master.getInside() == 0){ //0为室外 室外才有 BigDecimal lng = new BigDecimal((json.get("lng").toString())); //室外 原始经度 BigDecimal lat = new BigDecimal((json.get("lat").toString())); //室外 原始纬度 short gpsType = Short.parseShort(json.get("ltgt").toString()); lte.setGpsType(gpsType); MyLLOffset myLLOffset = MapUtil.getMyLLOffset(gpsType, lng, lat); lte.setLongitudeModify(myLLOffset.getNewLng()); //室外 纠正经度 lte.setLatitudeModify(myLLOffset.getNewLat()); // 室外 纠正纬度 if(lte.getLatitudeModify()!=null&&lte.getLongitudeModify()!=null){ ConverterTool ctl=new ConverterTool(); Point point = ctl.GG2BD(lte.getLongitudeModify().doubleValue(), lte.getLatitudeModify().doubleValue()); lte.setLongitudeBmap(new BigDecimal(point.getLongitude())); //百度纠偏后经度 lte.setLatitudeBmap(new BigDecimal(point.getLatitude())); //百度纠偏后纬度 } lte.setLongitude(myLLOffset.getOldLng()); //室外原始经度 lte.setLatitude(myLLOffset.getOldLat()); //室外原始纬度 } else if(master.getInside() == 1){ //室内才有 1为室内 lte.setPositionX(new BigDecimal(Double.parseDouble(json.get("px").toString()))); //室内 x轴坐标 lte.setPositionY(new BigDecimal(Double.parseDouble(json.get("py").toString()))); //室内 y轴坐标 } lte.setRealnetType(Short.parseShort(json.get("nt").toString())); //实际网络 lte.setTac(Long.parseLong(json.get("tac").toString())); //tac lte.setCid(Long.parseLong(json.get("cid").toString())); //cid if(json.get("rsr") != null){ lte.setRsrp(new BigDecimal(Double.parseDouble(json.get("rsr").toString()))); //rsrp } lte.setRsrq((Long)json.get("rrq")); //Rsrq if(json.get("snr") != null){ lte.setSnr(new BigDecimal(Double.parseDouble(json.get("snr").toString()))); //sinr } lte.setCqi((Long)json.get("cqi")); //cqi lte.setPci((Long)json.get("pci")); //rxLev_full lte.setEbid((Long)json.get("ebd")); //ebid lte.setFtptype(master.getFtpUpdown()); //ftp上传下载 if(json.get("fs") != null){ lte.setFtpSpeed(new BigDecimal(Double.parseDouble(json.get("fs").toString()))); //ftp_speed } lteList.add(lte); } private static Date getDateByLong(long timeForMilli){ Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(timeForMilli); return cal.getTime(); } public void testNonTransactional(){ logger.debug("------>nonTransactional"); } public int updateAdress(TestMasterlog testMasterlog){ return this.testMasterlogDao.updateAdress(testMasterlog); } public TestMasterlog selectByPrimaryKey(String flowid){ return this.testMasterlogDao.selectByPrimaryKey(flowid); } } <file_sep>/src/main/java/com/complaint/dao/LteTrackLogDao.java package com.complaint.dao; import com.complaint.model.LogSubmanualLte; public interface LteTrackLogDao extends BatchDao{ void insert(LogSubmanualLte logSubmanualLte); void delLteByFlowid(String flowid); } <file_sep>/src/main/java/com/complaint/model/User.java package com.complaint.model; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.simple.JSONStreamAware; import org.json.simple.JSONValue; import org.springframework.security.core.userdetails.UserDetails; import com.complaint.security.Authority; public class User implements java.io.Serializable,UserDetails,JSONStreamAware{ private static final long serialVersionUID = 1L; private Integer userid; private String userName; private Integer sex; private String password; private String name; private Integer roleid; private Integer islock; private String email; private String phone; private String rolename; private List<Authority> authorities = new ArrayList<Authority>(); public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public User() { super(); } public User(Integer userid, String userName, Integer sex, String password, String name, Integer roleid, Integer islock, String email, String phone, String rolename) { super(); this.userid = userid; this.userName = userName; this.sex = sex; this.password = <PASSWORD>; this.name = name; this.roleid = roleid; this.islock = islock; this.email = email; this.phone = phone; this.rolename = rolename; } public String getRolename() { return rolename; } public void setRolename(String rolename) { this.rolename = rolename; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getRoleid() { return roleid; } public void setRoleid(Integer roleid) { this.roleid = roleid; } public Integer getIslock() { return islock; } public void setIslock(Integer islock) { this.islock = islock; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public void setAuthorities(List<Authority> authorities) { this.authorities = authorities; } @Override public Collection<Authority> getAuthorities() { return authorities; } @Override public String getUsername() { return this.userName; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { if(this.islock == null || this.islock == 1){ return false; } return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } @Override public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } @Override public int hashCode(){ return this.userid.hashCode(); } @Override public boolean equals(Object obj){ User user = (User)obj; return this.userid.equals(user.userid); } @Override public void writeJSONString(Writer out) throws IOException { Map<String,Object> obj = new HashMap<String,Object>(); obj.put("id", this.userid); obj.put("email", this.email); JSONValue.writeJSONString(obj, out); } } <file_sep>/src/main/java/com/complaint/dao/SysConfigDao.java package com.complaint.dao; import java.util.List; import java.util.Map; import com.complaint.model.Sysconfig; public interface SysConfigDao { String queryData(String configkey); void updateData(Map<String, Object> map); //查询角度配置 Sysconfig getAngleconfig(String configkey); //保存角度配置 void saveAngleconfig(Map map); //查询累计网络投诉工单量 public List<Map> getTotalSer(Map map); } <file_sep>/src/main/java/com/complaint/service/BaseStationService.java package com.complaint.service; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.complaint.action.vo.CellVo; import com.complaint.dao.BaseStationDao; import com.complaint.dao.SysConfigDao; import com.complaint.model.BaseStation; import com.complaint.model.CenterZoom; import com.complaint.model.GwCasCell; import com.complaint.model.Sysconfig; import com.complaint.model.TCasCell; import com.complaint.model.ReportCells; import com.complaint.utils.Constant; @Service("baseStationService") public class BaseStationService { @Autowired private GisgradExcelDownLoadService gisgradExcelDownLoadService; @Autowired private BaseStationDao baseStationDao; @Autowired private SysConfigDao sysConfigDao; private static final Logger logger = LoggerFactory .getLogger(BaseStationService.class); public List<BaseStation> getAllCell(CellVo vo) { Sysconfig sysconfig = new Sysconfig(); try { sysconfig = this.sysConfigDao.getAngleconfig("cell_angle_config"); } catch (Exception e) { logger.error("cell_angle_config", e); } String[] str = sysconfig.getConfigvalue().split("="); String type = str[1].substring(0, 1); String angle = str[2]; Map<String, Object> param = new HashMap<String, Object>(); param.put("areaids", vo.getAreas()); param.put("modetypes", vo.getModetypes()); param.put("cellBands", vo.getCellBands()); param.put("indoor", vo.getIndoor()); List<BaseStation> bsList = baseStationDao.queryBaseStationData(param); return bsList; } public CenterZoom getCenter(String areaids) { Map<String, Object> param = new HashMap<String, Object>(); Integer areaid = Integer.parseInt(areaids.split(",")[0]); param.put("areaid", areaid); return baseStationDao.queryCenter(param); } public BaseStation getBaseStationById(Integer bid) { Sysconfig sysconfig = new Sysconfig(); try { sysconfig = this.sysConfigDao.getAngleconfig("cell_angle_config"); } catch (Exception e) { logger.error("cell_angle_config", e); } String[] str = sysconfig.getConfigvalue().split("="); String type = str[1].substring(0, 1); return baseStationDao.queryBaseStationById(type, bid); } public Map<String, Object> getNearCell(CellVo vo) { Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> param = new HashMap<String, Object>(); param.put("lac", Integer.parseInt(vo.getLac_cid().split("_")[0])); param.put("cid", Integer.parseInt(vo.getLac_cid().split("_")[1])); param.put("areaids", vo.getAreas()); param.put("indoor", vo.getIndoor()); param.put("modetypes", vo.getModetypes()); param.put("cellBands", vo.getCellBands()); param.put("lac_cid", vo.getLac_cid()); List<TCasCell> list = new ArrayList<TCasCell>(); TCasCell tccell = baseStationDao.queryCell(param); List<TCasCell> nearlist = baseStationDao.queryNearCell(param); List<TCasCell> otherlist = baseStationDao.queryNearCellOther(param); for (TCasCell tcc : nearlist) { tcc.setNeartype(1); // 判断网络 if (tccell.getModetype() == tcc.getModetype()) { // 3G根据上下行频点判断同频、异频 if (tccell.getModetype() == 0) { if (tccell.getUpfreq() != null && tccell.getDownfreq() != null && tccell.getUpfreq().equals(tcc.getUpfreq()) && tccell.getDownfreq().equals(tcc.getDownfreq())) { // 同频 tcc.setNearrel(1); } else { // 异频 tcc.setNearrel(2); } } else { //2G根据频段判断同频、异频 if (tccell.getCellBand() != null && tccell.getCellBand().equals(tcc.getCellBand())) { // 同频 tcc.setNearrel(1); }else { // 异频 tcc.setNearrel(2); } } } else { // 异网络 tcc.setNearrel(3); } list.add(tcc); } for (TCasCell tccother : otherlist) { boolean flag = false; for (TCasCell tcc : list) { // 判断是否是双向 if (tccother.getLac().equals(tcc.getLac()) && tccother.getCellId().equals(tcc.getCellId())) { tcc.setNeartype(3); flag = true; break; } } if (!flag) { tccother.setNeartype(2); if (tccell.getModetype() == tccother.getModetype()) { // 3G根据上下行频点判断同频、异频 if (tccell.getModetype() == 0) { if (tccell.getUpfreq() != null && tccell.getDownfreq() != null && tccell.getUpfreq().equals(tccother.getUpfreq()) && tccell.getDownfreq().equals(tccother.getDownfreq())) { // 同频 tccother.setNearrel(1); } else { // 异频 tccother.setNearrel(2); } } else { //2G根据频段判断同频、异频 if (tccell.getCellBand() != null && tccell.getCellBand().equals(tccother.getCellBand())) { // 同频 tccother.setNearrel(1); }else { // 异频 tccother.setNearrel(2); } } } else { tccother.setNearrel(3); } list.add(tccother); } } map.put("list", list); map.put("tcc", tccell); return map; } /*** * * * @Title: queryCellById * * @Description: 根据CID、LAC查询显示该小区信息 * * @param lac * @param cid * @return * * @return: List<TCasCell> */ public TCasCell queryCellById(Long lac, Long cid) { Map<String, Object> map = new HashMap<String, Object>(); map.put("lac", lac); map.put("cid", cid); TCasCell cell = this.baseStationDao.queryCellById(map); return cell; } /*** * * * @Title: queryCellByIdOriginal * * @Description: 根据CID、LAC查询显示该小区信息,获取经纬度为原始经纬度 * * @param lac * @param cid * @return * * @return: List<TCasCell> */ public TCasCell queryCellByIdOriginal(Long lac, Long cid) { Map<String, Object> map = new HashMap<String, Object>(); map.put("lac", lac); map.put("cid", cid); TCasCell cell = this.baseStationDao.queryCellByIdOriginal(map); return cell; } /** * query cell position * * @param @param params * @return List<Map<String,Object>> * @throws */ public List<Map<String, Object>> queryAreaPosition( Map<String, Object> params) { return this.baseStationDao.queryAreaPosition(params); } /** * @Title: setAreaCenter * @param @param areaid * @param @param bigLat * @param @param biglng * @return void 返回类型 * @throws */ public void setAreaCenter(String areaid, BigDecimal bigLat, BigDecimal biglng) { Map<String, Object> params = new HashMap<String, Object>(); params.put("areaid", Integer.valueOf(areaid)); params.put("longitude", bigLat); params.put("latitude", biglng); this.baseStationDao.setAreaCenter(params); } /** * 导出小区信息 * @param areaids * @return */ public List<GwCasCell> getRegiondown(CellVo vo,String filePath,Integer page) { Map<String, Object> params = new HashMap<String, Object>(); params.put("areaids", vo.getAreas()); params.put("modetypes", vo.getModetypes()); params.put("cellBands", vo.getCellBands()); params.put("indoor", vo.getIndoor()); params.put("lbound", Constant.READ_ROW*page); params.put("mbound", Constant.READ_ROW*(page+1)); List<GwCasCell> list = new ArrayList<GwCasCell>(); list = this.baseStationDao.queryRegiondown(params); return list; } /** * 导出点击小区 * @param vo * @return */ public List<GwCasCell> getReportNearCell(CellVo vo){ Long lac = Long.parseLong(vo.getLac_cid().split("_")[0]); Long cid = Long.parseLong(vo.getLac_cid().split("_")[1]); Map<String, Object> param = new HashMap<String, Object>(); param.put("lac", lac); param.put("cid", cid); param.put("lac_cid", vo.getLac_cid()); param.put("areaids", vo.getAreas()); param.put("modetypes", vo.getModetypes()); param.put("cellBands", vo.getCellBands()); param.put("indoor", vo.getIndoor()); //查询正向邻区 List<GwCasCell> nearlist = this.baseStationDao.queryReportNearCell(param); //查询反向邻区 List<GwCasCell> otherlist = this.baseStationDao.queryReportNearCellOther(param); //查询当当前的邻区 GwCasCell tccell = this.baseStationDao.queryReportCellById(param); List<GwCasCell> list = new ArrayList<GwCasCell>(); tccell.setColor_type("0"); tccell.setColor("#FF0000"); String color1 ="#00c321";//同频颜色 String color2 ="#1499da";//异频颜色 String color3 ="#ffa200";//异网颜色 List<GwCasCell> list1 = new ArrayList<GwCasCell>();//同频集合 List<GwCasCell> list2 = new ArrayList<GwCasCell>();//异频集合 List<GwCasCell> list3 = new ArrayList<GwCasCell>();//异网络集合 list.add(tccell); for (GwCasCell tcc : nearlist) { // 判断网络 if (tccell.getModeType() == tcc.getModeType()) { // 3G根据上下行频点判断同频、异频 if (tccell.getModeType() == 0) { if (tccell.getUpFreq() != null && tccell.getDownFreq() != null && tccell.getUpFreq().equals(tcc.getUpFreq()) && tccell.getDownFreq().equals(tcc.getDownFreq())) { // 同频 if (vo.getCellrel().indexOf("0") >= 0) { tcc.setColor_type("1"); tcc.setColor(color1); list.add(tcc); list1.add(tcc); } } else { // 异频 if (vo.getCellrel().indexOf("1") >= 0) { tcc.setColor_type("2"); tcc.setColor(color2); list.add(tcc); list2.add(tcc); } // tcc.setNearrel(2); } } else { // 2G根据频段判断同频、异频 if (tccell.getCellBand() != null && tccell.getCellBand().equals(tcc.getCellBand())) { // 同频 if (vo.getCellrel().indexOf("0") >= 0) { tcc.setColor_type("1"); tcc.setColor(color1); list.add(tcc); list1.add(tcc); } } else { // 异频 if (vo.getCellrel().indexOf("1") >= 0) { tcc.setColor_type("2"); tcc.setColor(color2); list.add(tcc); list2.add(tcc); } } } } else { // 异网络 if (vo.getCellrel().indexOf("2") >= 0) { tcc.setColor_type("3"); tcc.setColor(color3); list.add(tcc); list3.add(tcc); } } } for (GwCasCell tccother : otherlist) { boolean flag = false; for (GwCasCell tcc : list) { // 判断是否是双向 if (tccother.getLac().equals(tcc.getLac()) && tccother.getCid().equals(tcc.getCid())) { flag = true; break; } } if (!flag) { if (tccell.getModeType() == tccother.getModeType()) { // 3G根据上下行频点判断同频、异频 if (tccell.getModeType() == 0) { if (tccell.getUpFreq() != null && tccell.getDownFreq() != null && tccell.getUpFreq().equals( tccother.getUpFreq()) && tccell.getDownFreq().equals( tccother.getDownFreq())) { // 同频 // tccother.setNearrel(1); if (vo.getCellrel().indexOf("0") >= 0) { tccother.setColor_type("1"); tccother.setColor(color1); list1.add(tccother); } } else { // 异频 if (vo.getCellrel().indexOf("1") >= 0) { tccother.setColor_type("2"); tccother.setColor(color2); list2.add(tccother); } } } else { // 2G根据频段判断同频、异频 if (tccell.getCellBand() != null && tccell.getCellBand().equals( tccother.getCellBand())) { // 同频 if (vo.getCellrel().indexOf("0") >= 0) { tccother.setColor_type("1"); tccother.setColor(color1); list1.add(tccother); } } else { // 异频 if (vo.getCellrel().indexOf("1") >= 0) { tccother.setColor_type("2"); tccother.setColor(color2); list2.add(tccother); } } } } else { if (vo.getCellrel().indexOf("2") >= 0) { tccother.setColor_type("3"); tccother.setColor(color3); list3.add(tccother); } } } } list = new ArrayList<GwCasCell>(); list.add(tccell); list.addAll(list1); list.addAll(list2); list.addAll(list3); return list; } /** * 框选导出 * @param vo * @return */ public List<GwCasCell> getRegiondownCell(CellVo vo ,String filePath ,Integer page){ Map<String, Object> param = new HashMap<String, Object>(); param.put("areaids",vo.getAreas()); param.put("modetypes", vo.getModetypes()); param.put("cellBands", vo.getCellBands()); param.put("maxlat", vo.getMaxlat()); param.put("minlat", vo.getMinlat()); param.put("minlng", vo.getMinlng()); param.put("maxlng", vo.getMaxlng()); param.put("indoor", vo.getIndoor()); param.put("lbound", Constant.READ_ROW*page); param.put("mbound", Constant.READ_ROW*(page+1)); List<GwCasCell> list = new ArrayList<GwCasCell>(); list = this.baseStationDao.queryRegiondown(param); /*List<GwCasCell> nearl = new ArrayList<GwCasCell>(); if(vo.getLac_cid()!=null && vo.getCellrel()!=null){//获取不再当前查询区域的邻区 nearl = this.getRegionNear(vo.getLac_cid(), vo.getCellrel(), vo.getAreas(),vo.getMaxlat(),vo.getMinlat(),vo.getMaxlng(),vo.getMinlng()); } if(nearl.size()>0){//如果有邻区就加入集合 list.addAll(nearl); }*/ return list; } /** * 框选邻区排除当前areaid public List<GwCasCell> getRegionNear(String lac_cid ,String cellrel ,String areaid ,double maxlat ,double minlat ,double maxlng ,double minlng){ String[] areas = areaid.split(",");//多个区域需要分割 List<GwCasCell> near = this.getReportNearCell(lac_cid ,cellrel); Iterator<GwCasCell> iter = near.iterator(); while(iter.hasNext()){ GwCasCell gcc = iter.next(); boolean flag = false;//判断是否已经移除 for(String ar:areas){//如果在查询区域内就移除 if(String.valueOf(gcc.getAreaId()).equals(ar)){ iter.remove(); flag =true; break; } } if(flag){//若果已经移除,则跳出当前 continue; } if(gcc.getLatitudeModify().compareTo(BigDecimal.valueOf(minlat))==-1||gcc.getLatitudeModify().compareTo(BigDecimal.valueOf(maxlat))==1){ //纬度不再框选内的移除 iter.remove(); continue; } if(gcc.getLongitudeModify().compareTo(BigDecimal.valueOf(minlng))==-1||gcc.getLongitudeModify().compareTo(BigDecimal.valueOf(maxlng))==1){ //经度不再框选内的移除 iter.remove(); continue; } } return near; }*/ /** * 需要查询的页数 */ public Integer getPage(CellVo vo){ Map<String, Object> params = new HashMap<String, Object>(); params.put("areaids", vo.getAreas()); params.put("modetypes", vo.getModetypes()); params.put("cellBands", vo.getCellBands()); params.put("indoor", vo.getIndoor()); int num = this.baseStationDao.countRegiondown(params); int page = 0; if(num%500!=0){ page = num/500+1; }else{ page = num/500; } return page; } public List<ReportCells> getReportLoadCells(CellVo vo){ Map<String, Object> param = new HashMap<String, Object>(); List<ReportCells> list = new ArrayList<ReportCells>(); param.put("modetypes", vo.getModetypes()); param.put("cellBands", vo.getCellBands()); param.put("indoor", vo.getIndoor()); param.put("nearrel", vo.getCellrel()); param.put("areaids", vo.getAreas()); list = this.baseStationDao.queryReportLoadCells(param); return list; } public static void main(String[] args) { for(int i=1;i<=96;i++){ System.out.print(i +" as a"+i +","); if(i%10==0){ System.out.println(); } } } } <file_sep>/src/main/java/com/complaint/model/TCasCell.java package com.complaint.model; import java.math.BigDecimal; public class TCasCell { private Long lac; private Long cellId; private BigDecimal celllat; private BigDecimal celllng; private String bid;// 基站id private BigDecimal ant_azimuth;//原始 方位角 private BigDecimal self_azimuth;//修正 方位角 private int flag; private Integer upfreq;//上行频点 private Integer downfreq;//下行频点 private String nears;//邻区 private int neartype;//邻区关系 1、正向 2、反向 3、双向 private int nearrel;//邻区类型 1、同频2、异频3、异网络 private int modetype;//网络状态 private String adminRegion;//行政区 private String rncname;//RNC名称 private String baseName;//基站名称 private String cellName;//小区名称 private String neType;//网元类型 private int psc; private BigDecimal antElectAngle;//电子倾角 private BigDecimal antMathAngle;//机械倾角 private int tilt;//下倾角 private String antType;//天线类型 private String sharedAnt;//天线共用情况 private int indoor;//0室外 1室内 private String sharedPlatform;//共用平台 private String devType;//基站设备类型 private int bsic; private String coverRange;//覆盖范围 private String bscName;//BSC private Integer cellBand;//小区频段 public BigDecimal getAnt_azimuth() { return ant_azimuth; } public void setAnt_azimuth(BigDecimal ant_azimuth) { this.ant_azimuth = ant_azimuth; } public BigDecimal getSelf_azimuth() { return self_azimuth; } public void setSelf_azimuth(BigDecimal self_azimuth) { this.self_azimuth = self_azimuth; } public int getIndoor() { return indoor; } public void setIndoor(int indoor) { this.indoor = indoor; } public int getModetype() { return modetype; } public void setModetype(int modetype) { this.modetype = modetype; } public int getNearrel() { return nearrel; } public void setNearrel(int nearrel) { this.nearrel = nearrel; } public String getNears() { return nears; } public void setNears(String nears) { this.nears = nears; } public Integer getUpfreq() { return upfreq; } public void setUpfreq(Integer upfreq) { this.upfreq = upfreq; } public Integer getDownfreq() { return downfreq; } public void setDownfreq(Integer downfreq) { this.downfreq = downfreq; } public int getNeartype() { return neartype; } public void setNeartype(int neartype) { this.neartype = neartype; } public int getFlag() { return flag; } public void setFlag(int flag) { this.flag = flag; } public Long getLac() { return lac; } public void setLac(Long lac) { this.lac = lac; } public Long getCellId() { return cellId; } public void setCellId(Long cellId) { this.cellId = cellId; } public BigDecimal getCelllat() { return celllat; } public void setCelllat(BigDecimal celllat) { this.celllat = celllat; } public BigDecimal getCelllng() { return celllng; } public void setCelllng(BigDecimal celllng) { this.celllng = celllng; } public String getBid() { return bid; } public void setBid(String bid) { this.bid = bid; } public String getAdminRegion() { return adminRegion; } public void setAdminRegion(String adminRegion) { this.adminRegion = adminRegion; } public String getRncname() { return rncname; } public void setRncname(String rncname) { this.rncname = rncname; } public String getBaseName() { return baseName; } public void setBaseName(String baseName) { this.baseName = baseName; } public String getCellName() { return cellName; } public void setCellName(String cellName) { this.cellName = cellName; } public String getNeType() { return neType; } public void setNeType(String neType) { this.neType = neType; } public int getPsc() { return psc; } public void setPsc(int psc) { this.psc = psc; } public Integer getTilt() { return tilt; } public void setTilt(Integer tilt) { this.tilt = tilt; } public String getAntType() { return antType; } public void setAntType(String antType) { this.antType = antType; } public String getSharedAnt() { return sharedAnt; } public void setSharedAnt(String sharedAnt) { this.sharedAnt = sharedAnt; } public BigDecimal getAntElectAngle() { return antElectAngle; } public void setAntElectAngle(BigDecimal antElectAngle) { this.antElectAngle = antElectAngle; } public BigDecimal getAntMathAngle() { return antMathAngle; } public void setAntMathAngle(BigDecimal antMathAngle) { this.antMathAngle = antMathAngle; } public void setTilt(int tilt) { this.tilt = tilt; } public String getSharedPlatform() { return sharedPlatform; } public void setSharedPlatform(String sharedPlatform) { this.sharedPlatform = sharedPlatform; } public int getBsic() { return bsic; } public void setBsic(int bsic) { this.bsic = bsic; } public String getDevType() { return devType; } public void setDevType(String devType) { this.devType = devType; } public String getCoverRange() { return coverRange; } public void setCoverRange(String coverRange) { this.coverRange = coverRange; } public String getBscName() { return bscName; } public void setBscName(String bscName) { this.bscName = bscName; } public Integer getCellBand() { return cellBand; } public void setCellBand(Integer cellBand) { this.cellBand = cellBand; } } <file_sep>/src/main/java/com/complaint/model/GradekpiResults.java package com.complaint.model; public class GradekpiResults { private String flowid; private float inside; private double rxlev_Sub_1; private double rxlev_Sub_2; private double rxlev_Sub_3; private double rxlev_Sub_4; private double rxqual_Sub_1; private double rxqual_Sub_2; private double rxqual_Sub_3; private double rxqual_Sub_4; public String getFlowid() { return flowid; } public void setFlowid(String flowid) { this.flowid = flowid; } public float getInside() { return inside; } public void setInside(float inside) { this.inside = inside; } public double getRxlev_Sub_1() { return rxlev_Sub_1; } public void setRxlev_Sub_1(double rxlev_Sub_1) { this.rxlev_Sub_1 = rxlev_Sub_1; } public double getRxlev_Sub_2() { return rxlev_Sub_2; } public void setRxlev_Sub_2(double rxlev_Sub_2) { this.rxlev_Sub_2 = rxlev_Sub_2; } public double getRxlev_Sub_3() { return rxlev_Sub_3; } public void setRxlev_Sub_3(double rxlev_Sub_3) { this.rxlev_Sub_3 = rxlev_Sub_3; } public double getRxlev_Sub_4() { return rxlev_Sub_4; } public void setRxlev_Sub_4(double rxlev_Sub_4) { this.rxlev_Sub_4 = rxlev_Sub_4; } public double getRxqual_Sub_1() { return rxqual_Sub_1; } public void setRxqual_Sub_1(double rxqual_Sub_1) { this.rxqual_Sub_1 = rxqual_Sub_1; } public double getRxqual_Sub_2() { return rxqual_Sub_2; } public void setRxqual_Sub_2(double rxqual_Sub_2) { this.rxqual_Sub_2 = rxqual_Sub_2; } public double getRxqual_Sub_3() { return rxqual_Sub_3; } public void setRxqual_Sub_3(double rxqual_Sub_3) { this.rxqual_Sub_3 = rxqual_Sub_3; } public double getRxqual_Sub_4() { return rxqual_Sub_4; } public void setRxqual_Sub_4(double rxqual_Sub_4) { this.rxqual_Sub_4 = rxqual_Sub_4; } } <file_sep>/src/main/java/com/complaint/mina/MinaServer.java package com.complaint.mina; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.concurrent.Executors; import org.apache.mina.core.service.IoAcceptor; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.executor.ExecutorFilter; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; public class MinaServer { private static final int PORT = 9123; public static void main( String[] args ) throws IOException { IoAcceptor acceptor = new NioSocketAcceptor(); //acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory(Charset.forName( "UTF-8" )))); acceptor.getFilterChain().addFirst("codeFactory", new ProtocolCodecFilter(new ByteCodeFactory())); acceptor.getFilterChain().addLast("executorFilter", new ExecutorFilter(Executors.newCachedThreadPool())); acceptor.setHandler(new MinaServerHandler()); acceptor.getSessionConfig().setMinReadBufferSize(100); acceptor.getSessionConfig().setMaxReadBufferSize(8888); acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); acceptor.bind(new InetSocketAddress(PORT)); } } <file_sep>/src/main/java/com/complaint/action/FaqController.java package com.complaint.action; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URLDecoder; import java.net.URLEncoder; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.complaint.utils.Constant; @Controller @RequestMapping("/faq") public class FaqController { /** * 下载帮助文档 * @param Name * @param request * @param response * @return */ @RequestMapping(value="/faq", method = RequestMethod.GET) public ModelAndView faqdown(HttpServletRequest request ,HttpServletResponse response){ ModelAndView mv = null; String path = request.getSession().getServletContext().getRealPath("/").replace("\\", "/")+Constant.CAS_TEMPLATE_PATH+"FAQ.doc"; ServletOutputStream out = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { String fileName = "FAQ.doc";//路径加文件名 fileName = URLEncoder.encode(fileName, "GB2312"); fileName = URLDecoder.decode(fileName, "ISO8859_1"); File file = new File(path); byte[] buf = new byte[1024]; int len = 0; response.reset(); // 非常重要 response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); out = response.getOutputStream(); bis = new BufferedInputStream(new FileInputStream(file)); bos = new BufferedOutputStream(out); while (-1 != (len = bis.read(buf, 0, buf.length))) { bos.write(buf, 0, len); } } catch (Exception e) { }finally{ if (bis != null){ try { bis.close(); } catch (IOException e) { } } if (bos != null){ try { bos.close(); } catch (IOException e) { } } } return mv; } } <file_sep>/src/main/java/com/complaint/model/ComplainEvaluate.java package com.complaint.model; public class ComplainEvaluate { // 区域id private Integer[] area_id; // rscp优良中差对应abcd private Integer[] rscp_a; private Integer[] rscp_b; private Integer[] rscp_c; private Integer[] rscp_d; // ecno优良中差对应abcd private Integer[] ec_no_a; private Integer[] ec_no_b; private Integer[] ec_no_c; private Integer[] ec_no_d; // txpower优良中差对应abcd private Integer[] txpower_a; private Integer[] txpower_b; private Integer[] txpower_c; private Integer[] txpower_d; // ftp上行优良中差对应abcd private Integer[] ftp_up_a; private Integer[] ftp_up_b; private Integer[] ftp_up_c; private Integer[] ftp_up_d; // ftp下行优良中差对应abcd private Integer[] ftp_down_a; private Integer[] ftp_down_b; private Integer[] ftp_down_c; private Integer[] ftp_down_d; // rxlev优良中差对应abcd private Integer[] rxlev_a; private Integer[] rxlev_b; private Integer[] rxlev_c; private Integer[] rxlev_d; // qxqual优良中差对应abcd private Integer[] rxqual_a; private Integer[] rxqual_b; private Integer[] rxqual_c; private Integer[] rxqual_d; // C/I优良中差对应abcd private Integer[] ci_a; private Integer[] ci_b; private Integer[] ci_c; private Integer[] ci_d; // 综合评价优良中差对应abcd ,3g/2g private Integer[] comp_eval_3g_a; private Integer[] comp_eval_3g_b; private Integer[] comp_eval_3g_c; private Integer[] comp_eval_3g_d; private Integer[] comp_eval_2g_a; private Integer[] comp_eval_2g_b; private Integer[] comp_eval_2g_c; private Integer[] comp_eval_2g_d; // 综合改善优良中差对应abcd private Integer[] comp_impr_a; private Integer[] comp_impr_b; private Integer[] comp_impr_c; private Integer[] comp_impr_d; // 综合改善得分 3g/2g private Double[] comp_impr_value_3g; private Double[] comp_impr_value_2g; // 综合改善比例 3g/2g private String[] comp_impr_ratio_3g; private String[] comp_impr_ratio_2g; // 及时率 private String[] timely_rate; // 及时率排名 private Integer[] timely_rate_rank; public String[] getComp_impr_ratio_3g() { return comp_impr_ratio_3g; } public void setComp_impr_ratio_3g(String[] comp_impr_ratio_3g) { this.comp_impr_ratio_3g = comp_impr_ratio_3g; } public String[] getComp_impr_ratio_2g() { return comp_impr_ratio_2g; } public void setComp_impr_ratio_2g(String[] comp_impr_ratio_2g) { this.comp_impr_ratio_2g = comp_impr_ratio_2g; } public Integer[] getCi_a() { return ci_a; } public void setCi_a(Integer[] ci_a) { this.ci_a = ci_a; } public Integer[] getCi_b() { return ci_b; } public void setCi_b(Integer[] ci_b) { this.ci_b = ci_b; } public Integer[] getCi_c() { return ci_c; } public void setCi_c(Integer[] ci_c) { this.ci_c = ci_c; } public Integer[] getCi_d() { return ci_d; } public void setCi_d(Integer[] ci_d) { this.ci_d = ci_d; } public Integer[] getArea_id() { return area_id; } public void setArea_id(Integer[] area_id) { this.area_id = area_id; } public Integer[] getRscp_a() { return rscp_a; } public void setRscp_a(Integer[] rscp_a) { this.rscp_a = rscp_a; } public Integer[] getRscp_b() { return rscp_b; } public void setRscp_b(Integer[] rscp_b) { this.rscp_b = rscp_b; } public Integer[] getRscp_c() { return rscp_c; } public void setRscp_c(Integer[] rscp_c) { this.rscp_c = rscp_c; } public Integer[] getRscp_d() { return rscp_d; } public void setRscp_d(Integer[] rscp_d) { this.rscp_d = rscp_d; } public Integer[] getEc_no_a() { return ec_no_a; } public void setEc_no_a(Integer[] ec_no_a) { this.ec_no_a = ec_no_a; } public Integer[] getEc_no_b() { return ec_no_b; } public void setEc_no_b(Integer[] ec_no_b) { this.ec_no_b = ec_no_b; } public Integer[] getEc_no_c() { return ec_no_c; } public void setEc_no_c(Integer[] ec_no_c) { this.ec_no_c = ec_no_c; } public Integer[] getEc_no_d() { return ec_no_d; } public void setEc_no_d(Integer[] ec_no_d) { this.ec_no_d = ec_no_d; } public Integer[] getTxpower_a() { return txpower_a; } public void setTxpower_a(Integer[] txpower_a) { this.txpower_a = txpower_a; } public Integer[] getTxpower_b() { return txpower_b; } public void setTxpower_b(Integer[] txpower_b) { this.txpower_b = txpower_b; } public Integer[] getTxpower_c() { return txpower_c; } public void setTxpower_c(Integer[] txpower_c) { this.txpower_c = txpower_c; } public Integer[] getTxpower_d() { return txpower_d; } public void setTxpower_d(Integer[] txpower_d) { this.txpower_d = txpower_d; } public Integer[] getFtp_up_a() { return ftp_up_a; } public void setFtp_up_a(Integer[] ftp_up_a) { this.ftp_up_a = ftp_up_a; } public Integer[] getFtp_up_b() { return ftp_up_b; } public void setFtp_up_b(Integer[] ftp_up_b) { this.ftp_up_b = ftp_up_b; } public Integer[] getFtp_up_c() { return ftp_up_c; } public void setFtp_up_c(Integer[] ftp_up_c) { this.ftp_up_c = ftp_up_c; } public Integer[] getFtp_up_d() { return ftp_up_d; } public void setFtp_up_d(Integer[] ftp_up_d) { this.ftp_up_d = ftp_up_d; } public Integer[] getFtp_down_a() { return ftp_down_a; } public void setFtp_down_a(Integer[] ftp_down_a) { this.ftp_down_a = ftp_down_a; } public Integer[] getFtp_down_b() { return ftp_down_b; } public void setFtp_down_b(Integer[] ftp_down_b) { this.ftp_down_b = ftp_down_b; } public Integer[] getFtp_down_c() { return ftp_down_c; } public void setFtp_down_c(Integer[] ftp_down_c) { this.ftp_down_c = ftp_down_c; } public Integer[] getFtp_down_d() { return ftp_down_d; } public void setFtp_down_d(Integer[] ftp_down_d) { this.ftp_down_d = ftp_down_d; } public Integer[] getRxlev_a() { return rxlev_a; } public void setRxlev_a(Integer[] rxlev_a) { this.rxlev_a = rxlev_a; } public Integer[] getRxlev_b() { return rxlev_b; } public void setRxlev_b(Integer[] rxlev_b) { this.rxlev_b = rxlev_b; } public Integer[] getRxlev_c() { return rxlev_c; } public void setRxlev_c(Integer[] rxlev_c) { this.rxlev_c = rxlev_c; } public Integer[] getRxlev_d() { return rxlev_d; } public void setRxlev_d(Integer[] rxlev_d) { this.rxlev_d = rxlev_d; } public Integer[] getRxqual_a() { return rxqual_a; } public void setRxqual_a(Integer[] rxqual_a) { this.rxqual_a = rxqual_a; } public Integer[] getRxqual_b() { return rxqual_b; } public void setRxqual_b(Integer[] rxqual_b) { this.rxqual_b = rxqual_b; } public Integer[] getRxqual_c() { return rxqual_c; } public void setRxqual_c(Integer[] rxqual_c) { this.rxqual_c = rxqual_c; } public Integer[] getRxqual_d() { return rxqual_d; } public void setRxqual_d(Integer[] rxqual_d) { this.rxqual_d = rxqual_d; } public Integer[] getComp_eval_3g_a() { return comp_eval_3g_a; } public void setComp_eval_3g_a(Integer[] comp_eval_3g_a) { this.comp_eval_3g_a = comp_eval_3g_a; } public Integer[] getComp_eval_3g_b() { return comp_eval_3g_b; } public void setComp_eval_3g_b(Integer[] comp_eval_3g_b) { this.comp_eval_3g_b = comp_eval_3g_b; } public Integer[] getComp_eval_3g_c() { return comp_eval_3g_c; } public void setComp_eval_3g_c(Integer[] comp_eval_3g_c) { this.comp_eval_3g_c = comp_eval_3g_c; } public Integer[] getComp_eval_3g_d() { return comp_eval_3g_d; } public void setComp_eval_3g_d(Integer[] comp_eval_3g_d) { this.comp_eval_3g_d = comp_eval_3g_d; } public Integer[] getComp_eval_2g_a() { return comp_eval_2g_a; } public void setComp_eval_2g_a(Integer[] comp_eval_2g_a) { this.comp_eval_2g_a = comp_eval_2g_a; } public Integer[] getComp_eval_2g_b() { return comp_eval_2g_b; } public void setComp_eval_2g_b(Integer[] comp_eval_2g_b) { this.comp_eval_2g_b = comp_eval_2g_b; } public Integer[] getComp_eval_2g_c() { return comp_eval_2g_c; } public void setComp_eval_2g_c(Integer[] comp_eval_2g_c) { this.comp_eval_2g_c = comp_eval_2g_c; } public Integer[] getComp_eval_2g_d() { return comp_eval_2g_d; } public void setComp_eval_2g_d(Integer[] comp_eval_2g_d) { this.comp_eval_2g_d = comp_eval_2g_d; } public Integer[] getComp_impr_a() { return comp_impr_a; } public void setComp_impr_a(Integer[] comp_impr_a) { this.comp_impr_a = comp_impr_a; } public Integer[] getComp_impr_b() { return comp_impr_b; } public void setComp_impr_b(Integer[] comp_impr_b) { this.comp_impr_b = comp_impr_b; } public Integer[] getComp_impr_c() { return comp_impr_c; } public void setComp_impr_c(Integer[] comp_impr_c) { this.comp_impr_c = comp_impr_c; } public Integer[] getComp_impr_d() { return comp_impr_d; } public void setComp_impr_d(Integer[] comp_impr_d) { this.comp_impr_d = comp_impr_d; } public Double[] getComp_impr_value_3g() { return comp_impr_value_3g; } public void setComp_impr_value_3g(Double[] comp_impr_value_3g) { this.comp_impr_value_3g = comp_impr_value_3g; } public Double[] getComp_impr_value_2g() { return comp_impr_value_2g; } public void setComp_impr_value_2g(Double[] comp_impr_value_2g) { this.comp_impr_value_2g = comp_impr_value_2g; } public String[] getTimely_rate() { return timely_rate; } public void setTimely_rate(String[] timely_rate) { this.timely_rate = timely_rate; } public Integer[] getTimely_rate_rank() { return timely_rate_rank; } public void setTimely_rate_rank(Integer[] timely_rate_rank) { this.timely_rate_rank = timely_rate_rank; } }<file_sep>/src/main/java/com/complaint/webservice/HelloWorld.java package com.complaint.webservice; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import com.complaint.service.UserService; public class HelloWorld{ @Autowired private UserService userSerivce; @Transactional public void greeting(String name){ //return "你好 "+name; } public String print() { return "我叫林计钦"; } }<file_sep>/src/main/java/com/complaint/model/KpiBean.java package com.complaint.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class KpiBean implements Serializable{ /** * */ private static final long serialVersionUID = 795247819143183103L; private short kpi; private short type; //1-2g 2-3g private short scene_type; private List<KpiIntervalValue> kpiValues = new ArrayList<KpiIntervalValue>(); public short getScene_type() { return scene_type; } public void setScene_type(short scene_type) { this.scene_type = scene_type; } public short getKpi() { return kpi; } public void setKpi(short kpi) { this.kpi = kpi; } public short getType() { return type; } public void setType(short type) { this.type = type; } public List<KpiIntervalValue> getKpiValues() { return kpiValues; } public void setKpiValues(List<KpiIntervalValue> kpiValues) { this.kpiValues = kpiValues; } } <file_sep>/src/main/webapp/js/reportTask/trck.js /******************************************************************************* * 单次测试室内外地图 * * @author czj */ var map; var colorlist; var gsmlist, wcdmalist; var first_id, first_type;// 第一个点ID var last_id, last_type;// 最后一个点ID var exlatAndlngMap_3g = new Map();// 封装Markerr 的偏移前经纬度KEY:marker;value:偏移前经纬度 var latAndlngMap_3g = new Map();// 封装Markerr 的偏移后经纬度KEY:marker;value:偏移后经纬度 var exlatAndlngMap_2g = new Map();// 封装Markerr 的偏移前经纬度KEY:marker;value:偏移前经纬度 var latAndlngMap_2g = new Map();// 封装Markerr 的偏移后经纬度KEY:marker;value:偏移后经纬度 var cenetr_lat_lng;// 中心位置 var zNodes = []; var zTree; /** * 对轨迹点数据进行处理判断室内外类型分别加载地图、图例 * 并根据数据对各指标是否进行测试判断生成指标的下拉菜单选择器(默认2G-Rxlev、3G-RSCP)并进行事件绑定、 * 生成叠加数据功能里的树形指标菜单与事件绑定 * 判断轨迹的第一个点(以时间判断)并默认展示轨迹点详细数据 * * * @param flowid * @param type * @param inside * @param flist */ function queryPoint(flowid, type, inside, flist) { var idooorTag=[]; var psc_xlist, bcch_xlist; for ( var t = 0; t < flist.length; t++) { if (flist[t].kpiId == 20) { psc_xlist = flist[t].x; } if (flist[t].kpiId == 21) { bcch_xlist = flist[t].x; } } $("#demo_div").html(""); flay = true; $(".case_tu p").css({ 'background-image' : 'url(../images/case_tu_s.png)' }); $(".case_zhi").hide(); $("#d_s_id").show(); flag = true; $ .ajax({ type : "post", url : contextPath + "/reportTask/showPoint", data : ({ flowid : flowid, areaid:$("#areaid").val(), type : type }), success : function(data) { if (data) { gsmlist = data.gsmlist; wcdmalist = data.wcdmalist; var sum = 0;//全部点 // 无服务点统计 var gmsnssum = 0;//2g无服务点 var wcdmanssum = 0;//3g无服务点 var gmssum = 0;//2g点 var wcdmasum = 0;//3G点 // 2g,3g,无服务 var noService = 0; var gsmProp =0; var wcdmaProp = 0; if (gsmlist) { sum += gsmlist.length; gmssum = gsmlist.length; // 统计自由模式2G无服务点 for(var i = 0;i < gsmlist.length;i++){ if(gsmlist[i].realnet_type == -1){ gmsnssum += 1; } } } if (wcdmalist) { sum += wcdmalist.length; wcdmasum = wcdmalist.length; // 统计自由模式3G无服务点 for(var i = 0;i < wcdmalist.length;i++){ if(wcdmalist[i].realnet_type == -1){ wcdmanssum += 1; } } } // 用来去分是否为WCDMA自由模式 var netType = $(".combo-text").val().split("_"); // 统计自由模式无服务占比 // 统计3g 2g 以及无服务占比,如果采点总数为0让他各项为初始值0 if(sum!=0){ // noService noService = ((wcdmanssum+gmsnssum)/sum)*100; // 2G占比 gsmProp = ((gmssum-gmsnssum)/sum)*100; // 3G占比 wcdmaProp = ((wcdmasum-wcdmanssum)/sum)*100; } // 判断noService是否为0有没有必要添加 var noServiceLast = ""; var gsm_net =""; var wcdma_net =""; if(noService!=0){ noServiceLast = NumOptimize(noService.toFixed(2))+"%"; }else{ noServiceLast = "0%"; } if(gsmProp.toFixed(2)!=0){ gsm_net = NumOptimize(gsmProp.toFixed(2))+"%"; }else{ gsm_net = "0%"; } if(wcdmaProp.toFixed(2)!=0){ wcdma_net = NumOptimize(wcdmaProp.toFixed(2))+"%"; }else{ wcdma_net = "0%"; } // 页面添加无服务行 $("#wcdmaScale").html(wcdma_net); $("#gsmScale").html(gsm_net); $("#noServiceScale").html(noServiceLast); $("#sum_count").html("采样点:" + sum); colorlist = data.colorlist; center = data.center; // 根据数据显示下拉 // 3G下拉 zNodes指标下拉列表里去掉id为1、2的,其他ID-2 zNodes = []; var child = []; $("#s_sel1").hide(); $("#s_sel2").hide(); var dd = [], dd_id = []; for (i in wcdmalist) { if ($.inArray(1, dd_id) < 0 && wcdmalist[i].rscp > 0) { dd_id.push(1); dd.push({ "text" : 'RSCP', "id" : '1', "selected" : true }); child.push({ id : 3, text : "RSCP" }); } if ($.inArray(2, dd_id) < 0 && wcdmalist[i].ecno > 0) { dd_id.push(2); dd.push({ "text" : 'EcNo', "id" : '2' }); child.push({ id : 4, text : "EcNo" }); } if ($.inArray(3, dd_id) < 0 && wcdmalist[i].txpower > 0) { dd_id.push(3); dd.push({ "text" : 'TXPOWER', "id" : '3' }); child.push({ id : 5, text : "TXPOWER" }); } if ($.inArray(4, dd_id) < 0 && wcdmalist[i].ftpSpeed > 0) { dd_id.push(4); dd.push({ "text" : 'FTP', "id" : '4' }); child.push({ id : 6, text : "FTP" }); } if ($.inArray(20, dd_id) < 0 && wcdmalist[i].psc > 0) { dd_id.push(20); dd.push({ "text" : 'PSC', "id" : '20' }); child.push({ id : 22, text : "PSC" }); } } if ($("#s_sel2").css("display") == 'none' && dd_id.length > 0) { $("#s_sel2").show(); zNodes.push({ 'id' : 2, 'text' : "3G", 'children' : child }); $("#SelectBox2").combobox({ data : dd, valueField : 'id', textField : 'text' }); } else { $("#SelectBox2").combobox("clear"); } var dd = [], dd_id_1 = [], child = []; // 2g下拉 for (i in gsmlist) { if ($.inArray(6, dd_id_1) < 0 && gsmlist[i].rxlev > 0) { dd_id_1.push(6); dd.push({ "text" : 'RXLEV', "id" : '6', "selected" : true }); child.push({ 'id' : 8, 'text' : "RXLEV" }); } if ($.inArray(7, dd_id_1) < 0 && gsmlist[i].rxqual > 0) { dd_id_1.push(7); dd.push({ "text" : 'RXQUAL', "id" : '7' }); child.push({ 'id' : 9, pId : 1, 'text' : "RXQUAL" }); } if ($.inArray(8, dd_id_1) < 0 && gsmlist[i].rxqual > 0) { dd_id_1.push(8); dd.push({ "text" : 'C/I', "id" : '8' }); child.push({ 'id' : 10, 'text' : "C/I" }); } // if(($("#CI").val()== undefined||$("#CI").val()== // 'undefined')&&gsmlist[i].ci>0){ // var dd='<option value="8" id="CI">CI</option>'; // $("#SelectBox1").append(dd); // zNodes.push({id:10, pId:1, name:"CI"}); // } // if(($("#MOS").val()== // undefined||$("#MOS").val()== // 'undefined')&&gsmlist[i].mos>0){ // var dd='<option value="9" id="MOS">MOS</option>'; // $("#SelectBox1").append(dd); // zNodes.push({id:11, pId:1, name:"MOS"}); // } if ($.inArray(21, dd_id_1) < 0 && gsmlist[i].bcch > 0) { dd_id_1.push(21); dd.push({ "text" : 'BCCH', "id" : '21' }); child.push({ 'id' : 23, pId : 1, 'text' : "BCCH" }); } } if ($("#s_sel1").css("display") == 'none' && dd_id_1.length > 0) { $("#s_sel1").show(); zNodes.push({ 'id' : 1, 'text' : "2G", 'children' : child }); $("#SelectBox1").combobox({ data : dd, valueField : 'id', textField : 'text' }); } else { $("#SelectBox2").combobox("clear"); } $("#forms_data_id").show(); if (inside == 1) { // 室内 $("#expand").show(); $("#narrow").show(); if (map) { $("#div_point").html(div_html); } var aaf= showIndoorPoint(gsmlist, wcdmalist, colorlist, psc_xlist, bcch_xlist,idooorTag); if (dd_id_1.length > 0) { $("#SelectBox1") .combobox( { onSelect : function(n, o) { var sel1, sel2; if (dd_id_1.length > 0) { sel1 = $( "#SelectBox1") .combobox( "getValue"); } if (dd_id.length > 0) { sel2 = $( "#SelectBox2") .combobox( "getValue"); } var temp = ""; var str=""; if (sel1) { if (dd_id_1.length > 0) { str = $( "#SelectBox1") .combobox( "getText"); temp = str + "," + temp; } } if (sel2) { if (dd_id.length > 0) { str = $( "#SelectBox2") .combobox( "getText"); temp = str + "," + temp; } } if ($("#demo_div") .html()) { choose_demo( flowid, flist, $( "#SelectBox1") .combobox( "getValue"), $( "#SelectBox2") .combobox( "getValue"), $( "#SelectBox1") .combobox( "getText"), $( "#SelectBox2") .combobox( "getText"), "#demo_div", wcdmalist, gsmlist); } var vs = new Array(); var vs1 = new Array(); vs = temp.split(","); for (var x=0;x<vs.length;x++){ if(vs[x].length>0&&$.inArray(vs[x], idooorTag)<0){ idooorTag.push(vs[x]); vs1.push(vs[x]); } } if(vs1.length>0){ var obj=getindoorName(aaf.dfobj,vs1); initData(obj,vs1,aaf.firstId,aaf.firstType,aaf.lastId,aaf.lastType,aaf.wl.wid,aaf.wl.hie,idooorTag); } display(vs); } }); } // 下拉列表3G点击事件 if (dd_id.length > 0) { $("#SelectBox2") .combobox( { onSelect : function(n, o) { var sel1, sel2; if (dd_id_1.length > 0) { sel1 = $( "#SelectBox1") .combobox( "getValue"); } if (dd_id.length > 0) { sel2 = $( "#SelectBox2") .combobox( "getValue"); } var temp = ""; var str = ""; if (sel1) { if (dd_id_1.length > 0) { str = $( "#SelectBox1") .combobox( "getText"); temp = str + "," + temp; } } if (sel2) { if (dd_id.length > 0) { str = $( "#SelectBox2") .combobox( "getText"); temp = str + "," + temp; } } if ($("#demo_div") .html()) { choose_demo( flowid, flist, $( "#SelectBox1") .combobox( "getValue"), $( "#SelectBox2") .combobox( "getValue"), $( "#SelectBox1") .combobox( "getText"), $( "#SelectBox2") .combobox( "getText"), "#demo_div", wcdmalist, gsmlist); } var vs = new Array(); var vs1 = new Array(); vs = temp.split(","); for (var x=0;x<vs.length;x++){ if($.inArray(vs[x], idooorTag)<0){ idooorTag.push(vs[x]); vs1.push(vs[x]); } } if(vs1.length>0){ var obj=getindoorName(aaf.dfobj,vs1); initData(obj,vs1,aaf.firstId,aaf.firstType,aaf.lastId,aaf.lastType,aaf.wl.wid,aaf.wl.hie,idooorTag); } display(vs); } }); } } else if (inside == 0) { // 室外 $("#expand").hide(); $("#narrow").hide(); initMap(wcdmalist, gsmlist, center, psc_xlist, bcch_xlist); // 下拉列表2G点击事件 if (dd_id_1.length > 0) { $("#SelectBox1") .combobox( { onSelect : function(n, o) { chooseKpi( wcdmalist, gsmlist, $("#SelectBox1") .combobox( "getValue"), 1, psc_xlist, bcch_xlist); if ($("#demo_div") .html()) { choose_demo( flowid, flist, $( "#SelectBox1") .combobox( "getValue"), $( "#SelectBox2") .combobox( "getValue"), $( "#SelectBox1") .combobox( "getText"), $( "#SelectBox2") .combobox( "getText"), "#demo_div", wcdmalist, gsmlist); } } }); } // 下拉列表3G点击事件 if (dd_id.length > 0) { $("#SelectBox2") .combobox( { onSelect : function(n, o) { chooseKpi( wcdmalist, gsmlist, $("#SelectBox2") .combobox( "getValue"), 2, psc_xlist, bcch_xlist); if ($("#demo_div") .html()) { choose_demo( flowid, flist, $( "#SelectBox1") .combobox( "getValue"), $( "#SelectBox2") .combobox( "getValue"), $( "#SelectBox1") .combobox( "getText"), $( "#SelectBox2") .combobox( "getText"), "#demo_div", wcdmalist, gsmlist); } } }); } } // 图例比例显示点击事件 $('#img_demo') .die() .live( "click", function(e) { $(".case_tu") .css("background", "none repeat scroll 0 0 #fff"); $(".case_tu").css("border-bottom", "1px solid #979797"); $(".case_tu").css("border-right", "1px solid #979797"); var sel1 = 0, sel2 = 0; var sel1_n = "", sel2_n = ""; if (dd_id_1.length > 0) { sel1 = $("#SelectBox1") .combobox("getValue"); sel1_n = $("#SelectBox1") .combobox("getText"); } if (dd_id.length > 0) { sel2 = $("#SelectBox2") .combobox("getValue"); sel2_n = $("#SelectBox2") .combobox("getText"); } if (flay == true) { choose_demo(flowid, flist, sel1, sel2, sel1_n, sel2_n, "#demo_div", wcdmalist, gsmlist); $(".case_tu p") .css( { 'background-image' : 'url(../images/case_tu.png)' }); flay = false; } else { $(".case_tu").css("background", ""); $(".case_tu").css( "border-bottom", ""); $(".case_tu").css( "border-right", ""); $("#demo_div").html(""); flay = true; $(".case_tu p") .css( { 'background-image' : 'url(../images/case_tu_s.png)' }); } }); // 轨迹叠加选择 $('.twoG') .click( function(e) { $(".easyui-linkbutton").show(); var sel1 = 0, sel2 = 0; $("#zhibiao").dialog({ height : 200, width : 380, title : "测试指标选择", modal : true, closed : false }); $("#tul").tree({ data : zNodes, animate : true, checkbox : true, onlyLeafCheck : true }); if (dd_id_1.length > 0) { sel1 = $("#SelectBox1") .combobox("getValue"); } if (dd_id.length > 0) { sel2 = $("#SelectBox2") .combobox("getValue"); } for (i in zNodes) { child = zNodes[i].children; for (j in child) { if (child[j].id == (parseInt(sel1) + 2)) { var no = $("#tul") .tree( "find", child[j].id); $("#tul").tree( "remove", no.target); } if (child[j].id == (parseInt(sel2) + 2)) { var no = $("#tul") .tree( "find", child[j].id); $("#tul").tree( "remove", no.target); } } } $('#zhibiao').dialog('open'); $.parser.parse('#zhibiao'); }); // 树形确定事件 $('.treeb').unbind("click").click( function(e) { var sel1 = 0, sel2 = 0; if (dd_id_1.length > 0) { sel1 = $("#SelectBox1").combobox( "getValue"); } if (dd_id.length > 0) { sel2 = $("#SelectBox2").combobox( "getValue"); } var nodes = $('#zhibiao') .tree('getChecked'); var v = "", id_v = "",str = ""; for ( var i = 0; i < nodes.length; i++) { if (v != '') { v += ','; id_v += ','; } str = nodes[i].text; if (i != nodes.length - 1) { v += str + ","; id_v += nodes[i].id + ","; } else { v += str; id_v += nodes[i].id; } } if (nodes.length == 0) { $.messager.alert("warning", "至少选择一个指标!", "warning"); return; } var idd = ""; if (sel2) { idd += (parseInt(sel2) + 2) + ","; } if (sel1) { idd += (parseInt(sel1) + 2) + ","; } idd += id_v; $("#undata").val(v); $("#undata_id").val(idd); if (inside == 1) { if (sel1) { if (dd_id_1.length > 0) { str = $("#SelectBox1").combobox( "getText"); v = str + "," + v; } } if (sel2) { if (dd_id.length > 0) { str = $("#SelectBox2").combobox( "getText"); v = str + "," + v; } } var vs = new Array(); var vs1 = new Array(); vs = v.split(","); for (var x=0;x<vs.length;x++){ if($.inArray(vs[x], idooorTag)<0){ idooorTag.push(vs[x]); vs1.push(vs[x]); } } if(vs1.length>0){ var obj=getindoorName(aaf.dfobj,vs1); initData(obj,vs1,aaf.firstId,aaf.firstType,aaf.lastId,aaf.lastType,aaf.wl.wid,aaf.wl.hie,idooorTag); } display(vs); } else if (inside == 0) { outclick(psc_xlist, bcch_xlist); } $('#zhibiao').dialog('close'); }); $("#div_point").show(); $("#background").hide(); $("#bar_id").hide(); $(document).css({ "overflow" : "auto" }); } } }); } // 树型菜单 var setting = { check : { enable : true }, data : { simpleData : { enable : true } }, callback : { onCheck : onCheck } }; function onCheck(e, treeId, treeNode) { } /** * 生成室内地图并对数据进行处理并调用Raphael相关画图JS方法 * 对2G、3G数据分别传入 * 判断第一个点并默认展示RSCP、RXLEV的轨迹 * @param gsmlist * @param wcdmalist * @param colorlist * @param psc_xlist * @param bcch_xlist */ function showIndoorPoint(gsmlist, wcdmalist, colorlist, psc_xlist, bcch_xlist,idooorTag) { var pscmap = new Map();// 键:PSC值,值:颜色集id var bcchmap = new Map();// 键:PSC值,值:颜色集id var time_3g = "", time_2g = "", id_3g, id_2g; var real_t_3g, real_t_2g; var time_3g_last = "", time_2g_last = "", id_3g_last, id_2g_last; var colorall = []; var arr_color = []; for ( var t = 0; t < colorlist.length; t++) { var color = colorlist[t]; arr_color.push(color.colourcode); } var psc_arr_color = []; for ( var j = arr_color.length - 1; j >= 0; j--) { psc_arr_color.push(arr_color[j]); } var dc = colorall.concat(psc_arr_color, colorRoom);// 两个颜色合并作为PSC颜色用 // 指标数据 var rscp = [], ecno = [], TxPower = [], psc = [], ftpSpeed = []; // 3G for ( var i = 0; i < wcdmalist.length; i++) { var wcdma = wcdmalist[i]; // RSCP if (wcdma.rscp != 0) { var colorid = wcdma.rscp - 1; var obj = { x : wcdma.x, y : wcdma.y, color : arr_color[colorid], id : wcdma.id, type : '2', va : wcdma.rscp_, reltype : wcdma.realnet_type }; rscp.push(obj); } // ECNO if (wcdma.ecno != 0) { var colorid = wcdma.ecno - 1; var obj = { x : wcdma.x, y : wcdma.y, color : arr_color[colorid], id : wcdma.id, type : '2', va : wcdma.ecno_, reltype : wcdma.realnet_type }; ecno.push(obj); } // TxPower if (wcdma.txpower != 0) { var colorid = wcdma.txpower - 1; var obj = { x : wcdma.x, y : wcdma.y, color : arr_color[colorid], id : wcdma.id, type : '2', va : wcdma.txpower_, reltype : wcdma.realnet_type }; TxPower.push(obj); } // FTP if (wcdma.ftpSpeed != 0) { var colorid = wcdma.ftpSpeed - 1; var obj = { x : wcdma.x, y : wcdma.y, color : arr_color[colorid], id : wcdma.id, type : '2', va : wcdma.ftpSpeed_, reltype : wcdma.realnet_type }; ftpSpeed.push(obj); } // PSC if (wcdma.psc) { var ij = $.inArray(wcdma.psc.toString(), psc_xlist); if (ij < 20) { var obj = { x : wcdma.x, y : wcdma.y, color : dc[ij], id : wcdma.id, type : '2', va : wcdma.psc, reltype : wcdma.realnet_type }; psc.push(obj); } } // 取第一个点 if (i == 0) { time_3g = wcdma.eptime; id_3g = wcdma.id; real_t_3g = wcdma.realnet_type; } if (i == wcdmalist.length-1) { time_3g_last = wcdma.eptime; id_3g_last = wcdma.id; } } // 2G var rxlev = [], txpower_2g = [], rxqual = [], bcch = [], ci = [], mos = []; for ( var i = 0; i < gsmlist.length; i++) { var gsm = gsmlist[i]; // RxLev if (gsm.rxlev > 0) { var colorid = gsm.rxlev - 1; var obj = { x : gsm.x, y : gsm.y, color : arr_color[colorid], id : gsm.id, type : '1', va : gsm.rxlev_, reltype : gsm.realnet_type }; rxlev.push(obj); } // TxPower if (gsm.txpower > 0) { var colorid = gsm.txpower - 1; var obj = { x : gsm.x, y : gsm.y, color : arr_color[colorid], id : gsm.id, type : '1', va : gsm.txpower_, reltype : gsm.realnet_type }; txpower_2g.push(obj); } // rxqual if (gsm.rxqual > 0) { var colorid = gsm.rxqual - 1; var obj = { x : gsm.x, y : gsm.y, color : arr_color[colorid], id : gsm.id, type : '1', va : gsm.rxqual_, reltype : gsm.realnet_type }; rxqual.push(obj); } // ci if (gsm.ci > 0) { var colorid = gsm.ci - 1; var obj = { x : gsm.x, y : gsm.y, color : arr_color[colorid], id : gsm.id, type : '1', va : gsm.ci_, reltype : gsm.realnet_type }; ci.push(obj); } // mos if (gsm.mos > 0) { var colorid = gsm.mos - 1; var obj = { x : gsm.x, y : gsm.y, color : arr_color[colorid], id : gsm.id, type : '1', va : gsm.mos_, reltype : gsm.realnet_type }; mos.push(obj); } // bcch if (gsm.bcch) { var ij = $.inArray(gsm.bcch.toString(), bcch_xlist); if (ij < 20) { var obj = { x : gsm.x, y : gsm.y, color : dc[ij], id : gsm.id, type : '1', va : gsm.bcch, reltype : gsm.realnet_type }; bcch.push(obj); } } // 取第一个点 if (i == 0) { time_2g = gsm.eptime; id_2g = gsm.id; real_t_2g = gsm.realnet_type; } // 去最后一个点 if (i == gsmlist.length-1) { time_2g_last = gsm.eptime; id_2g_last = gsm.id; } } // 第一个比较时间大小,默认显示点 if (time_3g && time_2g) { if (time_3g > time_2g) { // 2 clickPoint(1, id_2g, real_t_2g); first_id = id_2g; first_type = 1; } else { clickPoint(2, id_3g, real_t_3g); first_id = id_3g; first_type = 2; } } else { if (time_3g) { clickPoint(2, id_3g, real_t_3g); first_id = id_3g; first_type = 2; } if (time_2g) { clickPoint(1, id_2g, real_t_2g); first_id = id_2g; first_type = 1; } } // 最后一个点比较时间大小,默认显示点 if (time_3g_last && time_2g_last) { if (time_3g_last < time_2g_last) { // 2 last_id = id_2g_last; last_type = 1; } else { last_id = id_3g_last; last_type = 2; } } else { if (time_3g_last) { last_id = id_3g_last; last_type = 2; } if (time_2g_last) { last_id = id_2g_last; last_type = 1; } } var svgData = { // 入口的经纬度 origin : [ 106.54252000, 29.56392000 ], station : {} }; // 室内轨迹点数据 var dd = new Object(); var dfobj=new Object(); if (rscp.length > 0) { dfobj.RSCP = rscp; } if (ecno.length > 0) { dfobj.EcNo = ecno; } if (TxPower.length > 0) { dfobj.TXPOWER = TxPower; } if (psc.length > 0) { dfobj.PSC = psc; } if (ftpSpeed.length > 0) { dfobj.FTP = ftpSpeed; } var db = new Object(); if (rxlev.length > 0) { dfobj.RXLEV = rxlev; } if (rxqual.length > 0) { dfobj.RXQUAL = rxqual; } if (ci.length > 0) { dfobj['C/I'] = ci; } // if(ci.length>0){db.CI=ci;} // if(mos.length>0){db.MOS=mos;} // if(txpower_2g.length>0){db.TXPOWER=txpower_2g;} if (bcch.length > 0) { dfobj.BCCH = bcch; } // var obj = new Object(); // obj["3G"] = dd; // obj["2G"] = db; var s = new Array(); s.push("RSCP"); s.push("RXLEV"); idooorTag.push("RSCP"); idooorTag.push("RXLEV"); var aaf=new Object(); aaf.firstId=first_id; aaf.firstType=first_type; aaf.lastId=last_id; aaf.lastType=last_type; var obj=getindoorName(dfobj,s); svgData.datas = obj; var wl=initPaper(svgData.datas, s, first_id, first_type,last_id,last_type); aaf.wl=wl; aaf.dfobj=dfobj; return aaf; } function getindoorName(datas,vs){ var newObj=new Object(); var newObj2=new Object(); if(vs.length>0){ for(var i=0;i<vs.length;i++){ if(vs[i]=='RSCP'||vs[i]=='EcNo'||vs[i]=='TXPOWER'||vs[i]=='PSC'||vs[i]=='FTP'){ if(datas[vs[i]])newObj[vs[i]]=datas[vs[i]];} if(vs[i]=='RXLEV'||vs[i]=='RXQUAL'||vs[i]=='C/I'||vs[i]=='BCCH') {if(datas[vs[i]]) newObj2[vs[i]]=datas[vs[i]];} } } var obj = new Object(); obj["3G"] = newObj; obj["2G"] = newObj2; return obj; } /** * 点击地图中某一轨迹点时查询并展示详细数据 * * @param id * 点ID * @param type:2-WCDMA或是1-GSM * @realnet_type -1无服务 */ function clickPoint(type, id, realnet_type) { // 点图缩小时列表 if (realnet_type != -1) { $.ajax({ type : "post", url : contextPath + "/reportTask/wcdmaOrGsm", data : ({ id : id, areaid:$("#areaid").val(), type : type }), success : function(data) { $('#div_page').html(data.content); // $('#div_page_max').html(data.contentMax); } }); } else { $('#div_page').html('<div class="noservice">No Service</div>'); } // 点图放大时列表 } /** * 室外多选对指标ID进行字符组装并调用chooseKpi方法 * @param doc */ function outclick(psc_xlist, bcch_xlist) { $('.wrapper,#dialData').hide(); var obj_id = $("#undata_id").attr("value"); var sid = obj_id.split(","); var g3 = ""; g2 = ""; for ( var i = 0; i < sid.length; i++) { switch (parseInt(sid[i])) { case 3: g3 += ",1"; break; case 4: g3 += ",2"; break; case 5: g3 += ",3"; break; case 6: g3 += ",4"; break; case 22: g3 += ",20"; break; case 8: g2 += ",6"; break; case 9: g2 += ",7"; break; case 10: g2 += ",8"; break; case 11: g2 += ",9"; break; case 23: g2 += ",21"; break; default: break; } } g2 = g2.length > 0 ? g2.substring(1, g2.length) : ""; g3 = g3.length > 0 ? g3.substring(1, g3.length) : ""; if (g2 != "") { chooseKpi(wcdmalist, gsmlist, g2, 1, psc_xlist, bcch_xlist); } else { for (i in markerArr_2g) { var m = markerArr_2g[i]; m.setMap(null); } markerArr_2g = []; exlatAndlngMap_2g.clear(); latAndlngMap_2g.clear(); } if (g3 != "") { chooseKpi(wcdmalist, gsmlist, g3, 2, psc_xlist, bcch_xlist); } else { for (i in markerArr_3g) { var m = markerArr_3g[i]; m.setMap(null); } markerArr_3g = []; exlatAndlngMap_3g.clear(); latAndlngMap_3g.clear(); } } /** * 计算页面宽度并改变页面里的地图与比例图组件宽度与高度 */ function changeWionw() { //计算宽度高度 var wid_len = (document.body.scrollWidth); var hie_len = wid_len * (9 / 16); $("#div_left").css("width", wid_len * 0.98); $("#div_left").css("height", hie_len); $("#div_point").css("width", (wid_len) * 0.98); $("#div_point").css("height", hie_len); $(".svg-div").css("width", wid_len); $(".svg-div").css("height", hie_len); $(".svg-div-main").css("width", wid_len); $(".svg-div-main").css("height", hie_len); $(".svg-main").css("width", wid_len * 3); $(".svg-main").css("height", hie_len * 3); $(".case_zhi").css("height", hie_len); $("#div_czj").css("height", hie_len); var wid = (document.body.scrollWidth - document.body.scrollWidth * 0.05) / 2; $(".histogram_flash").css("width", wid); } /** * 小数优化,把位数占位的0去掉,返回类型为string **/ function NumOptimize(num){ // 判断是否位小数 var param =/^\d+[.]\d+$/; if(param.test(num)){ var str = num.split("."); var lastNum; if(str.length=2){ var strSecond =str[1]; // 排除1.后面没有数的情况 for(var i=0;i<strSecond.length;i++){ var tempNum = strSecond.substring(strSecond.length-i-1,strSecond.length-i); if(parseInt(tempNum)!=0){ var index = strSecond.length-i; lastNum = str[0]+"."+strSecond.substring(0,index); return lastNum; } if(i==strSecond.length-1){ lastNum = str[0]; return lastNum; } } } }else{ return num; } } <file_sep>/src/main/java/com/complaint/schedual/context/BeanNames.java package com.complaint.schedual.context; public interface BeanNames { public static final String SCHEDUALCONTAINER = "schedualContainer"; } <file_sep>/src/main/webapp/js/index.js $(document).ready(function(){ var elem = { box: $('.box'), lMenu: $('#leftMenu'), ifraCont: $('#iframeContent'), hDiv: $('#hideDiv'), cDiv: $("#conDiv"), wHeight: $(window).height(), wWidth: $(window).width() }; var resize = function(){ elem.box.css({'height':(elem.wHeight)+'px','overflow':'hidden'}); elem.lMenu.attr('height',(elem.wHeight-99)+'px'); elem.ifraCont.css({'height':(elem.wHeight)+'px','width':(elem.wWidth - 203)+'px'}); elem.hDiv.css('height',(elem.wHeight-99)+'px'); elem.cDiv.css('width', (elem.wWidth - 221)+'px'); }; resize(); $(window).resize(function(){ resize(); }); elem.hDiv.click(function(){ if(elem.lMenu.css('display') == 'none'){ elem.lMenu.show(); elem.ifraCont.css('width',elem.wWidth - 203); }else{ elem.lMenu.hide(); elem.ifraCont.css('width',elem.wWidth - 5); } }); }); <file_sep>/src/main/webapp/js/reportTask/indoorMap_google.js /** * 加载indoorMap的小区 * */ var span_map_psc = new Array(); var p_map_jizhan = new Array(); var sctype; var angle; function getCell(map,lat,lng,flowid){ $.ajax({ type : "post", url : contextPath + "/reportTask/getCell", data : ({flowid : flowid}), success : function(data) { angle = data.angle; var cells = data.cell; sctype = data.type; var distance=[]; for(var i=0;i<cells.length;i++){ //画线 //连线的点组合 var heatmapData = [ new google.maps.LatLng(cells[i].celllat,cells[i].celllng), new google.maps.LatLng(lat,lng) ]; var stanceValue = getFlatternDistance(parseFloat(lat),parseFloat(lng),parseFloat(cells[i].celllat),parseFloat(cells[i].celllng)).toFixed(2); var message = stanceValue+"m"; distance[i] = stanceValue; //线属性 var polyOptions = { path: heatmapData, strokeColor: '#00ccff',//颜色 strokeOpacity: 1.0,//透明度 strokeWeight: 2,//宽度 title: message }; //把线添加到google里 var poly = new google.maps.Polyline(polyOptions); //装载 poly.setMap(map); google.maps.event.addListener(poly,'click',function(event){ $("#currvalue").val(this.title); }); //画图 /*var marker = new google.maps.Marker({ position : new google.maps.LatLng(cells[i].celllat,cells[i].celllng), title:"LAC:"+cells[i].lac+",CID"+cells[i].cellId+"小区名称"+cells[i].cellName+"", map : map });*/ } stationInitData = data.list; for (var j = 0; j < stationInitData.length; j++) { drawStation(stationInitData[j].bsList, map); } //drawStation(cells, map); //计算最远和最近距离 if(distance.length>0){ getDistance(distance); } } }); } var EARTH_RADIUS = 6378137.0; //单位M var PI = Math.PI; function getRad(d){ return d*PI/180.0; } /** * 计算两点距离 */ function getFlatternDistance(lat1,lng1,lat2,lng2){ var radLat1 = getRad(lat1); var radLat2 = getRad(lat2); var a = radLat1 - radLat2; var b = getRad(lng1) - getRad(lng2); var s = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2))); s = s*EARTH_RADIUS; s = Math.round(s*10000)/10000.0; return s; } /** * 计算最远和最近的一个距离 */ function getDistance(distance){ var max; var min; for(var i=0;i<distance.length;i++){ if(i==0){ max = distance[i]; min = distance[i]; }else{ if(distance[i]>max){ max = distance[i]; } if(distance[i]<min){ min = distance[i]; } } } $("#titleName").html("<span>当前距离:<input type=\"text\" id=\"currvalue\" disabled=\"disabled\" style=\"height:20px;border-color:#C8C8C8;width:70px;text-align:center;color:#ff00ff;\"></span>"+ "<span>最远距离:<input type=\"text\" id=\"maxvalue\" disabled=\"disabled\" style=\"height:20px;border-color:#C8C8C8;width:70px;text-align:center;color:#ff00ff;\"></span>"+ "<span>最近距离:<input type=\"text\" id=\"minvalue\" disabled=\"disabled\" style=\"height:20px;border-color:#C8C8C8;width:70px;text-align:center;color:#ff00ff;\"></span>"); $("#maxvalue").val(max+"m"); $("#minvalue").val(min+"m"); }<file_sep>/src/main/webapp/js/user/SVGCircle.js var SVGCircle = function(args){ var private, public, fn, handle, result; private = { //地球半径(单位:米) radius: 6371229, //比例大小(这里是通过计算出来的) ratio: 0, //比例倍数 multiple: 3, //基站原点(坐标) origin: {x:0, y:0}, //基站与原点距离 staRange: [], //第一组点的数据 point: [], //基站与原点的最小距离 minRange: 0, //点的间距 space: 10, //基站与原点最小坐标 minCoor: null, //当前样式 style: {top:0, left:0, width:433, height:400}, //零时样式 tempStyle: {top:0, left:0, width:433, height:400}, //当前显示点的组数据 datas: {}, flag: false, //基站是否已创建 isStation: false }; public = { // //原点的经纬度 // origin: [80, 50], // //基站的经纬度{基站名称:[经度,纬度]} // station: { // sta1: { // //基站类型 // type: 1, // //基站的经纬度 // landl: [111, 51], // //基站上的角度 // Angle: [[10,70,'sta1_key1','#FF5500'],[130,190,'sta1_key2','#FF0000'],[250,310,'sta1_key3','#03429F']] // }, // sta2: { // //基站类型 // type: null, // landl: [11, 51], // Angle: [[10,70,'sta2_key1','#B848FF'],[130,190,'sta2_key2','#3496D3'],[250,310,'sta3_key3','#3A7C1A']] // } // }, // //点的数据 // datas: { // RSCP: [ // {x:12,y:19,color:'#FFBD1E', id: 'RSCP_Id_01', type: 'RSCP_Type_01'}, // {x:20,y:90,color:'#0480FF'}, // {x:52,y:21,color:'#0DA60D'}, // {x:82,y:80,color:'#0480FF'}, // {x:42,y:77,color:'#FFBD1E'} // ], // EcNo: [ // {x:15,y:22,color:'#FFBD1E'}, // {x:22,y:92,color:'#0480FF'}, // {x:55,y:25,color:'#0DA60D'}, // {x:85,y:83,color:'#0480FF'}, // {x:45,y:80,color:'#FFBD1E'} // ], // TxPower: [ // {x:12,y:19,color:'#FFBD1E'}, // {x:20,y:90,color:'#0480FF'}, // {x:52,y:21,color:'#0DA60D'}, // {x:82,y:80,color:'#0480FF'}, // {x:42,y:77,color:'#FFBD1E'} // ], // PSC:[ // {x:12,y:19,color:'#FFBD1E'}, // {x:20,y:90,color:'#0480FF'}, // {x:52,y:21,color:'#0DA60D'}, // {x:82,y:80,color:'#0480FF'}, // {x:42,y:77,color:'#FFBD1E'} // ] // } }; fn = { /** * 计算初始值 */ init: function(){ var svg = $('#SVG'); private.R = Raphael('SVG'); //获取宽、高、left、top var style = private.style; style.width = svg.width(), style.height = svg.height(); style.left = parseInt(svg.css('left')), style.top = parseInt(svg.css('top')); style.left = isNaN(style.left)?0:style.left, style.top = isNaN(style.top)?0:style.top; //获取基站的原点 var origin = private.origin; origin.x = style.width/2, origin.y = style.height/2; //计算当前比例 private.ratio = (private.multiple*(((style.height/2)+(style.width/2))/2))/private.radius; }, //创建点 circle: function(ID, data){ private.point = []; //[0,0]点 var o = [100, 100]; //点的半径 var r = 6; var R = private.R var cir = R.set(); var i, len = data.length, items; var w = private.style.width, h = private.style.height; var ws = (w-(2*o[0]))/100, hs = (h-(2*o[1]))/100; var x, y; for(i=0;i<len;i++){ items = data[i]; x = (ws*(items.x))-(r/2)+o[0], y = (hs*(items.y))-(r/2)+o[1]; private.point.push([x, y]); cir.push(R.circle(x, y, r)); cir[i].attr({fill: items.color, 'stroke-width': 0, 'fill-opacity': 100}); } cir.mouseover(function(){ this.attr('stroke-width', 3); }).mouseout(function(){ this.attr('stroke-width', 0); }).click(function(event){ var x = parseInt(this.attr('cx'))-r-1, y = parseInt(this.attr('cy'))-r-1; event = event || window.event; var target = $(event.target || event.srcElement); //获取当前点击的点的数据 var ID = target.attr('data'), TYPE = target.attr('type'); //alert('ID:'+ID+'-----TYPE:'+TYPE); clickPoint(TYPE,ID); }); var top = (hs*data[0].y)+(o[1]+2), left = (ws*data[0].x)+(o[0]-12); left = left < 0 ? 0 : left; var html = []; var mTop = window.attachEvent ? -17 : -13; html.push('<label id="SVG_'+ID+'" '); html.push('style="float:left;font-size:12px;width:auto;height:auto;position:absolute;overflow:hidden;'); html.push('top:'+top+'px;left:'+left+'px;">'); html.push('<label style="float:left;">'+ID.replace('EcNo', 'Ec/No')+'</label>'); html.push('<label style="float:left;height:12px;margin-top:'+mTop+'px;font-size:40px;color:#888888;">&rarr;</label>'); html.push('</label>'); svg = $('#SVG'); svg.append(html.join('\r\n')); svg = svg.children().children(); var id, datas_id, datas_type; svg.each(function(index, element){ element = $(element); id = element.attr('id'); //datas_id = data[index].id; if(!id){ element.attr('id', 'SVG_'+ID); } }); //IE和firefox的标签不一样,通过取不同标签,获取要设置数据的元素 var circle = $('#SVG').find('circle'); var shape = $('#SVG').find('shape'); var eachElem = circle.length > 0 ? circle : shape; //遍历元素,给每一个元素邦数据 eachElem.each(function(index, element){ element = $(element); //获取数据的ID datas_id = data[index].id; datas_id = datas_id ? datas_id : ''; //获取数据的Type datas_type = data[index].type; datas_type = datas_type ? datas_type : ''; //绑定数据 element.attr('data', datas_id).attr('type', datas_type); }); if(!private.isStation){ fn.maxLen();fn.station(); } }, //遍历数据 formatData: function(ID){ var datas = public.datas; private.datas[ID] = datas[ID]; fn.circle(ID, datas[ID]); }, /** * 计算点距原点的最大值 */ maxLen: function(){ var points = private.point; var origin = private.origin; var i, len = points.length, point, px, py, x = [], y = []; for(i=0;i<len;i++){ point = points[i]; px = point[0], py = point[1]; x.push(Math.abs(parseInt(origin.x)-parseInt(px))); y.push(Math.abs(parseInt(origin.y)-parseInt(py))); } var maxX = SJ.maxValue(x); var maxY = SJ.maxValue(y); private.pointLen = Math.sqrt((maxX*maxX)+(maxY*maxY)); }, /** * 通过角度,计算点的坐标,首先定位第一个点的坐标 * @params datas <JSON> 当前的所有点的数据 */ formatAngle: function(ID, datas){ var key, data, i, len, items, angle, x, y; len = datas.length; private.datas[ID] = datas; for(i=0;i<len;i++){ items = datas[i]; angle = items.angle; if(i == 0){ x = private.origin.x + Math.sin(angle*Math.PI/180)*private.space; y = private.origin.y + Math.cos(angle*Math.PI/180)*private.space; } else{ x = x + Math.sin(angle*Math.PI/180)*private.space; y = y + Math.cos(angle*Math.PI/180)*private.space; } y = y - (2*(y - private.origin.y))-14; items.x = x, items.y = y; } fn.circle(ID, datas); }, /** * 放大 */ magnify: function(args){ var svg = $('#SVG'); var style = private.style; var tempStyle = private.tempStyle; var w = style.width, h = style.height, top = tempStyle.top, left = tempStyle.left; w = style.width = w+200, h = style.height = h+200; top = style.top = tempStyle.top = top - 100, left = style.left = tempStyle.left = left - 100; private.space += 10; svg.css('width', (w)+'px').css('height', (h)+'px').css('left', (left)+'px').css('top', (top)+'px'); var origin = private.origin; origin.x = w/2, origin.y = h/2; //fn.station(); private.flag = false; if(!args){ var child = svg.children().eq(0); if(child[0].nodeName == 'DIV'){ child.css('width', (w)+'px').css('height', (h)+'px'); } else{ child.attr('width', w).attr('height', h); } //从新排列点坐标 var key, data, datas = private.datas; for(key in datas){ if(datas[key]){ //1.移出所有点 $(".svg-div").find('#SVG_'+key).remove(); //2.从新绑定 private.isStation = false; fn.circle(key, datas[key]); //fn.formatAngle(key, datas[key]); } } } }, /** * 缩小 */ reduce: function(args){ var svg = $('#SVG'); var style = private.style; var tempStyle = private.tempStyle; var w = style.width, h = style.height, top = tempStyle.top, left = tempStyle.left; var svgW = $('.svg-div').width(), svgH = $('.svg-div').height()-40; if(w > svgW){ w = style.width = w-200, h = style.height = h-200; private.flag = true; if(w == svgW){ top = style.top, left = style.left;private.flag = false; } top = style.top = tempStyle.top = top + 100, left = style.left = tempStyle.left = left + 100; private.space -= 10; if(w-svgW >= 0 && !args){ left = style.left = tempStyle.left = left - (left + (w-svgW)); top = style.top = tempStyle.top = top - (top + (h-svgH)); left = left/2, top = top/2; private.flag = true; } svg.css('width', (w)+'px').css('height', (h)+'px').css('left', (left)+'px').css('top', (top)+'px'); var origin = private.origin; origin.x = w/2, origin.y = h/2; //fn.station(); if(!args){ svg.find('svg').attr('width', w).attr('height', h); //从新排列点坐标 var key, data, datas = private.datas; for(key in datas){ if(datas[key]){ //1.移出所有点 $(".svg-div").find('#SVG_'+key).remove(); //2.从新绑定 private.isStation = false; fn.circle(key, datas[key]); //fn.formatAngle(key, datas[key]); } } } } }, /** * 拖动 */ darg: function(){ var svg = $('#SVG'); var label = $('#label'), tempx, tempy, flag = 2; var svgW = $('.svg-div').width(), svgH = $('.svg-div').height()-40; svg.unbind('mousedown').mousedown(function(event){ event = event || window.event; var tl = SJ.getElementTL(svg[0]); var top = private.style.top, left = private.style.left; var width = private.style.width, height = private.style.height; ts = private.flag ? tempy : top, ls = private.flag ? tempx : left; var x = event.clientX - tl.left; var y = event.clientY - tl.top; if(svgW - private.style.width == left){ flag = 1; }else{ flag = 2; } label.html('down:'+ls+'*'+ts); var tsm, lsm; $(document).unbind('mousemove').mousemove(function(event){ event = event || window.event; var mx = event.clientX - tl.left; var my = event.clientY - tl.top; var jlx = mx-x, jly = my-y; tsm = ts + jly, lsm = ls + jlx; lsm = lsm > 0 ? 0 : lsm; tsm = tsm > 0 ? 0 : tsm; lsm = lsm < svgW-width ? svgW-width: lsm; tsm = tsm < svgH-height ? svgH-height : tsm; label.html('move:'+lsm+'*'+tsm); svg.css('left', (lsm)+'px').css('top', (tsm)+'px'); }); $(document).unbind('mouseup').mouseup(function(event){ private.tempStyle.top = tempy = tsm ? tsm : parseInt(svg.css('top')); private.tempStyle.left = tempx = lsm ? lsm : parseInt(svg.css('left')); $(document).unbind(); private.flag = true; }); }); }, /** * 复选框点击事件 * @param $this <Element> 当前事件触发元素 */ checkClick: function($this){ setTimeout(function(){ $this = $($this); var checked = $this.attr('checked'); var ID = $this.attr('id'); if(checked){ fn.formatData(ID);/*fn.magnify(true);fn.reduce(true);*/ } else{ $(".svg-div").find('#SVG_'+ID).remove();private.datas[ID] = null; } }, 10); }, /** * 度数转弧度 */ angToRad: function(angle_d){ var Pi = 3.1415926535898; return angle_d * Pi / 180; }, /** * 计算角度 * @param station <Json> 基站数据(经纬度) */ getAngle: function(station){ var origin = public.origin; var lng1 = origin[0], lat1 = origin[1]; var lng2 = station[0], lat2 = station[1]; var azimuth = 0, averageLat=(lat1+lat2)/2; if(lat1-lat2==0){ azimuth=90;} else{ azimuth = Math.atan((lng1-lng2)*Math.cos(fn.angToRad(averageLat))/(lat1-lat2))*180/Math.PI; } if (lat1 > lat2){ azimuth = azimuth + 180; } if (azimuth < 0){ azimuth = 360 + azimuth; } return azimuth; }, /** * 计算距离 * @param station <Json> 基站数据(经纬度) */ getrRange: function(station){ var origin = public.origin; var lng1 = origin[0], lat1 = origin[1]; var lng2 = station[0], lat2 = station[1]; //地球半径(单位:米) var r = private.radius; var dis = Math.sqrt(Math.pow((lng1-lng2)*Math.PI*r*Math.cos((lat1+lat2)/2*Math.PI/180)/180,2)+Math.pow((lat1-lat2)*Math.PI*r/180,2)); return dis; }, /** * chart */ chart: function(container, datas){ var args = { chart: { width:60,height:60, renderTo: container, plotBackgroundColor: '#000000', plotBorderWidth: null, plotShadow: false }, legend: { enabled: false }, credits: { enabled: false }, tooltip: { enabled: false }, exporting: { enabled: false }, title: { text: '' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: false }, showInLegend: true } }, series: [{ type: 'pie', name: 'Browser share', data: [ { name: 'Chrome', y: 50, sliced: true, color: 'red', selected: true } ] }] }; var len1 = datas.length, len2, i, d1, d2, d, array = [], arys = [], items; for(i=0;i<len1;i++){ items = datas[i]; d1 = items[0], d2 = items[1], key = items[2], color = items[3]; d = d2-d1; if(i == 0){ len2 = array.length; array.push({name:'KEY'+(len2),y:d1}); arys.push(len2); len2 = array.length; array.push({name:key,y:d,color:color}); } else{ len2 = array.length; array.push({name:'KEY'+(len2),y:d1-datas[i-1][1]}); arys.push(len2); len2 = array.length; array.push({name:key,y:d,color:color}); if(i == len1 - 1){ len2 = array.length; array.push({name:'KEY'+(len2),y:(360-d2)}); arys.push(len2); } } } args.series[0].data = array; var chart = new Highcharts.Chart(args); for(i=0,len1=arys.length;i<len1;i++){ chart.series[0].data[arys[i]].setVisible(false); } }, /** * 创建基站 * @param station <Json> 基站数据(经纬度) * @param origin <Array> 原点经纬度 */ station: function(station, origin){ //计算当前比例 private.ratio = (private.multiple*(private.style.height/2))/private.radius; station = station ? station : public.station; origin = origin ? origin : public.origin; var svg = $('#SVG'); var o = svg.find('#origin'); if(o.length == 0){ var o = $('<div id="origin" style="font-size:0px;width:5px;height:5px;position:absolute;"></div>'); svg.append(o); } private.origin.y -= 2.5, private.origin.x -= 2.5; o.css('top', (private.origin.y)+'px').css('left', (private.origin.x)+'px'); //if(!private.isStation){ //var svg = $('#SVG'); var sta, sHtml, angle, range, sta_xy, tempElem; private.staRange = []; var pointLen = private.pointLen; var x, y, w = private.style.width, h = private.style.height, count = 0; for(var key in station){ sHtml = [], sta_xy = []; sta = station[key]; //移出原来的 //tempElem = svg.find('#'+key); //if(tempElem.length == 0){ svg.find('#'+key).remove(); sHtml.push('<div id="'+key+'" style="width:60px;height:60px;position:absolute;font-size:0px;"></div>'); sHtml = $(sHtml.join('\r\n')); svg.append(sHtml); //} //else{sHtml = tempElem;} //计算角度 angle = fn.getAngle(sta.landl); //计算距离 range = fn.getrRange(sta.landl); range = range*private.ratio; range = range*(pointLen/range); //alert(range*private.ratio) //转换为xy坐标(需要相对于原点定位) sta_xy.push(private.origin.y + Math.sin(angle*Math.PI/180)*range); sta_xy.push(private.origin.x + Math.cos(angle*Math.PI/180)*range); private.staRange.push(SJ.Round(range)); x = sta_xy[0], y = sta_xy[1]; x = x > w ? w : x, y = y > h ? h : y; //根据基站不同类型,定位不同位置 if(sta.type == 1){ x = count*60, y = private.style.height - 60; count += 1; } sHtml.css('top', (y)+"px").css('left', (x)+"px") .attr('coor', '{y:'+y+',x:'+x+'}') .attr('Range', SJ.Round(range)) .addClass('station'); fn.chart(key, sta.Angle); sHtml.find('svg>rect').eq(0).remove(); sHtml.find('.highcharts-container shape').eq(0).remove(); } //基站与原点的最小距离 private.minRange = SJ.minValue(private.staRange); //最小距离基站的坐标 var _range, coor; var div_sta = svg.find('>div.station').each(function(){ _range = $(this).attr('Range'); if(_range == private.minRange){ private.minCoor = eval('('+$(this).attr('coor')+')'); } }); private.isStation = true; //} } }; handle = { /** * 初始化函数 */ initArgs: function(args){ if(args){ SJ.extend(public, args); } fn.init(); //fn.cOrigin(); handle.bindEvent(); SJ.Component["JCheckBoxs"](); }, /** * 绑定事件 */ bindEvent: function(){ //放大 $('#magnify').unbind('click').click(function(){ fn.magnify(); }); //缩小 $('#reduce').unbind('click').click(function(){ fn.reduce(); }); //复选框点击事件 $('.svg-div-title').find('input[type=checkbox]').unbind('click').click(function(){ fn.checkClick(this); }); //拖动 fn.darg(); } }; handle.initArgs(args); result = {}; SJ.extend(this, result); };<file_sep>/src/main/java/com/complaint/model/RateColor.java package com.complaint.model; import java.io.Serializable; public class RateColor implements Serializable { // rank_code等级类型优良中差 private int rank_code; private String rank_color; private int scene; public int getRank_code() { return rank_code; } public void setRank_code(int rank_code) { this.rank_code = rank_code; } public String getRank_color() { return rank_color; } public void setRank_color(String rank_color) { this.rank_color = rank_color; } public int getScene() { return scene; } public void setScene(int scene) { this.scene = scene; } } <file_sep>/src/main/webapp/js/report/kpi_selectBox.js function kpi_choose(wcdmalist,gsmlist,ltelist,dd, dd_id ,dd_id_1,dd_id_2, child){ if(dd_id.length<5){ for (i in wcdmalist) { if ($.inArray(1, dd_id) < 0 && wcdmalist[i].rscp > 0) { dd_id.push(1); dd.push({ "text" : 'RSCP', "id" : '1', "selected" : true }); child.push({ id : 4, text : "RSCP" }); } if ($.inArray(2, dd_id) < 0 && wcdmalist[i].ecno > 0) { dd_id.push(2); dd.push({ "text" : 'EcNo', "id" : '2' }); child.push({ id : 5, text : "EcNo" }); } if ($.inArray(3, dd_id) < 0 && wcdmalist[i].txpower > 0) { dd_id.push(3); dd.push({ "text" : 'TXPOWER', "id" : '3' }); child.push({ id : 6, text : "TXPOWER" }); } if ($.inArray(4, dd_id) < 0 && wcdmalist[i].ftpSpeed > 0) { dd_id.push(4); dd.push({ "text" : 'FTP3G', "id" : '4' }); child.push({ id : 7, text : "FTP3G" }); } if ($.inArray(20, dd_id) < 0 && wcdmalist[i].psc > 0) { dd_id.push(20); dd.push({ "text" : 'PSC', "id" : '20' }); child.push({ id : 23, text : "PSC" }); } } } if ($("#s_sel2").css("display") == 'none' && dd_id.length > 0) { $("#s_sel2").show(); zNodes.push({ 'id' : 2, 'text' : "3G", 'children' : child }); $("#SelectBox2").combobox({ data : dd, valueField : 'id', textField : 'text' }); } else { $("#SelectBox2").combobox("clear"); } dd = [], child = []; // 2g下拉 if(dd_id_1.length<4){ for (i in gsmlist) { if ($.inArray(6, dd_id_1) < 0 && gsmlist[i].rxlev > 0) { dd_id_1.push(6); dd.push({ "text" : 'RXLEV', "id" : '6', "selected" : true }); child.push({ 'id' : 9, 'text' : "RXLEV" }); } if ($.inArray(7, dd_id_1) < 0 && gsmlist[i].rxqual > 0) { dd_id_1.push(7); dd.push({ "text" : 'RXQUAL', "id" : '7' }); child.push({ 'id' : 10, pId : 1, 'text' : "RXQUAL" }); } if ($.inArray(8, dd_id_1) < 0 && gsmlist[i].rxqual > 0) { dd_id_1.push(8); dd.push({ "text" : 'C/I', "id" : '8' }); child.push({ 'id' : 11, 'text' : "C/I" }); } if ($.inArray(21, dd_id_1) < 0 && gsmlist[i].bcch > 0) { dd_id_1.push(21); dd.push({ "text" : 'BCCH', "id" : '21' }); child.push({ 'id' : 24, pId : 1, 'text' : "BCCH" }); } } } if ($("#s_sel1").css("display") == 'none' && dd_id_1.length > 0) { $("#s_sel1").show(); zNodes.push({ 'id' : 1, 'text' : "2G", 'children' : child }); $("#SelectBox1").combobox({ data : dd, valueField : 'id', textField : 'text' }); } else { $("#SelectBox1").combobox("clear"); } dd = [], child = []; // 4g下拉 if(dd_id_2.length<5){ for (i in ltelist) { if ($.inArray(23, dd_id_2) < 0 && ltelist[i].rsrp > 0) { dd_id_2.push(23); dd.push({ "text" : 'RSRP', "id" : '23', "selected" : true }); child.push({ 'id' : 26, 'text' : "RSRP" }); } if ($.inArray(24, dd_id_2) < 0 && ltelist[i].rsrq > 0) { dd_id_2.push(24); dd.push({ "text" : 'RSRQ', "id" : '24' }); child.push({ 'id' : 27, pId : 3, 'text' : "RSRQ" }); } if ($.inArray(25, dd_id_2) < 0 && ltelist[i].snr > 0) { dd_id_2.push(25); dd.push({ "text" : 'SINR', "id" : '25' }); child.push({ 'id' : 28, 'text' : "SINR" }); } if ($.inArray(71, dd_id_2) < 0 && ltelist[i].ftpSpeed > 0) { dd_id_2.push(71); dd.push({ "text" : 'FTP4G', "id" : '71' }); child.push({ id : 74, text : "FTP4G" }); } if ($.inArray(26, dd_id_2) < 0 && ltelist[i].pci > 0) { dd_id_2.push(26); dd.push({ "text" : 'PCI', "id" : '26' }); child.push({ 'id' : 29, pId : 3, 'text' : "PCI" }); } } } if ($("#s_sel3").css("display") == 'none' && dd_id_2.length > 0) { $("#s_sel3").show(); zNodes.push({ 'id' : 3, 'text' : "4G", 'children' : child }); $("#SelectBox3").combobox({ data : dd, valueField : 'id', textField : 'text' }); } else { $("#SelectBox3").combobox("clear"); } } /** * select的change事件 */ function select_change(dd_id,dd_id_1,dd_id_2,flowid,flist,wcdmalist, gsmlist,ltelist,idooorTag,aaf){ var sel1, sel2,sel3; if (dd_id_1.length > 0) sel1 = $("#SelectBox1").combobox("getValue"); if (dd_id.length > 0) sel2 = $("#SelectBox2").combobox("getValue"); if (dd_id_2.length > 0) sel3 = $("#SelectBox3").combobox("getValue"); var temp = ""; var str=""; if (sel1&&dd_id_1.length > 0) { str = $("#SelectBox1").combobox("getText"); temp = str+ ","+ temp; } if (sel2&&dd_id.length > 0) { str = $("#SelectBox2").combobox("getText"); temp = str+ ","+ temp; } if (sel3&&dd_id_2.length > 0) { str = $("#SelectBox3").combobox("getText"); temp = str+ ","+ temp; } if ($("#demo_div").html()) { choose_demo( flowid, flist,$( "#SelectBox1") .combobox( "getValue"), $( "#SelectBox2") .combobox( "getValue"),$( "#SelectBox3") .combobox( "getValue"), $( "#SelectBox1") .combobox( "getText"), $( "#SelectBox2") .combobox( "getText"),$( "#SelectBox3") .combobox( "getText"), "#demo_div", wcdmalist, gsmlist,ltelist); } var vs = new Array(); var vs1 = new Array(); vs = temp.split(","); for (var x=0;x<vs.length;x++){ if(vs[x].length>0&&$.inArray(vs[x], idooorTag)<0){ idooorTag.push(vs[x]); vs1.push(vs[x]); } } if(vs1.length>0){ var obj=getindoorName(aaf.dfobj,vs1); initData(obj,vs1,aaf.firstId,aaf.firstType,aaf.lastId,aaf.lastType,aaf.wl.wid,aaf.wl.hie,idooorTag); } display(vs); }<file_sep>/src/main/webapp/js/epinfo/epinfolistValidate.js $(function() { $.extend($.fn.validatebox.defaults.rules, { /** * uuid */ uuid:{ validator : function(value){ return /^[0-9]{15}$/i.test(value); }, message : '只能为15位数字' }, /** * 电话验证 */ teltphone : { //只能为1开头11为手机号码,3位区号-8号码,4位区号-7位号码,8位号码 validator : function(value){ return /^(([1]{1}\d{10})|(\d{3}\-{1}\d{8})|(\d{8})|(\d{4}\-{1}\d{7})|(\d{7})){1}$/.test(value); }, message : '请输入:手机号,电话号码 或 区号-电话号码' }, /** * 责任人 */ functionary : { //责任人只能为汉字 validator : function(value){ return /^[\u4e00-\u9fa5]+$/.test(value); }, message : '请输入汉字' } }); });<file_sep>/src/main/java/com/complaint/utils/MapUtil.java package com.complaint.utils; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import com.complaint.model.LLOffset; import com.complaint.model.MyLLOffset; import com.complaint.test.MarsCoordinate; import com.complaint.test.MarsCoordinate.Coordinate; public class MapUtil { private static Map<String, LLOffset> offsetMap = new HashMap<String, LLOffset>(); public static Map<String, LLOffset> getOffsetMap() { return offsetMap; } public static void setOffsetMap(Map<String, LLOffset> offsetMap) { MapUtil.offsetMap = offsetMap; } /** * 数据库纠偏 * @param lng * @param lat * @return */ public static LLOffset getLLOffset(BigDecimal lng, BigDecimal lat) { String lngstr = String.valueOf(lng.doubleValue()); String latstr = String.valueOf(lat.doubleValue()); String ll = lngstr.substring(0,lngstr.indexOf(".")+2)+"X"+latstr.substring(0, latstr.indexOf(".")+2); return offsetMap.get(ll); } /** * 算法纠偏 * @param lng * @param lat * @return */ public static LLOffset Convert2Mars(BigDecimal lng,BigDecimal lat) { MarsCoordinate mci = new MarsCoordinate(); MarsCoordinate.Coordinate earth = mci.new Coordinate(); earth.lat = lat.doubleValue(); earth.lng = lng.doubleValue(); MarsCoordinate.Coordinate mars = mci.convert2Mars(earth); LLOffset llOffset = new LLOffset(); llOffset.setLat(new BigDecimal(mars.lat)); llOffset.setLng(new BigDecimal(mars.lng)); return llOffset; } /** * 利用算法纠偏得到偏移后的经纬度 * @param mapType 经纬度类型 1 百度 0 google google需要纠偏 * @param lng * @param lat * @return */ public static MyLLOffset getMyLLOffset1(int mapType, BigDecimal lng, BigDecimal lat) { MyLLOffset myLLOffset = new MyLLOffset(); if (mapType == 0) { LLOffset llOffset = Convert2Mars(lng, lat); myLLOffset.setOldLng(lng); myLLOffset.setOldLat(lat); myLLOffset.setNewLng(llOffset.getLng()); myLLOffset.setNewLat(llOffset.getLat()); myLLOffset.setType(mapType); } else { myLLOffset.setOldLng(lng); myLLOffset.setOldLat(lat); myLLOffset.setNewLng(lng); myLLOffset.setNewLat(lat); myLLOffset.setType(mapType); } return myLLOffset; } /** * 用数据库纠偏取得的值 * 如果要使用该方法 需要放开SecurityMetadataSource类中的loadResourceDefine()方法里面的initLLMap(); * @param mapType * @param lng * @param lat * @return */ public static MyLLOffset getMyLLOffset(int mapType, BigDecimal lng, BigDecimal lat) { MyLLOffset myLLOffset = new MyLLOffset(); LLOffset llOffset = getLLOffset(lng, lat); if (llOffset != null) { if (mapType == 0) { myLLOffset.setOldLng(lng); myLLOffset.setOldLat(lat); myLLOffset.setNewLng(lng.add(llOffset.getOffsetLng())); myLLOffset.setNewLat(lat.add(llOffset.getOffsetLat())); myLLOffset.setType(mapType); } else { myLLOffset.setOldLng(lng.subtract(llOffset.getOffsetLng())); myLLOffset.setOldLat(lat.subtract(llOffset.getOffsetLat())); /*LLOffset temp = getLLOffset( lng.subtract(llOffset.getOffsetLng()), lat.subtract(llOffset.getOffsetLat())); myLLOffset.setNewLng(lng.add(temp.getOffsetLng())); myLLOffset.setNewLat(lat.add(temp.getOffsetLat()));*/ myLLOffset.setNewLng(lng); myLLOffset.setNewLat(lat); myLLOffset.setType(mapType); } }else{ myLLOffset.setOldLng(lng); myLLOffset.setOldLat(lat); myLLOffset.setNewLng(lng); myLLOffset.setNewLat(lat); myLLOffset.setType(mapType); } return myLLOffset; } } <file_sep>/src/main/webapp/js/Component/JTreeMenu.js /**---------------------------------------------------------------- // Copyright (C) 2012 思建科技-潘毅 // E-mail:<EMAIL> // // 文件名: JPopUp.js // 文件功能描述:JS弹出框 // 创建标识:2012年12月12日 14:38:57 // // 修改标识: // 修改描述: //----------------------------------------------------------------*/ SJ.NameSpace.register("SJ.Component"); SJ.Component["JTreeMenu"] = function(args){ //版本 this.Version = '1.0.0'; //组件创建日期 this.CreateData = '2013年01月29日 13:07:51'; //组件最后修改日期 this.FinallyData = '2013年01月29日 13:08:00'; //组件描述 this.Remark = 'SJ Component 折叠菜单'; //版权所有 this.CopyRight = '思建科技'; //遵循变量先定义,后使用原则,定义相关变量 var private, public, lang, element, eventLibFn, fn, handle, result; //私有变量对象,存放非外部传入的变量 private = { //弹出框对象的class mClass: "SJ-JTreeMenu-Main", //样式标签的ID StyleSheetIdentity: "SJ_JTreeMenu_StyleSheet", //线程 thread: null, //菜单Click事件参数配置 EventClick: [ {nodeName:"span",className:"JTreeMenu-PNode",fn:function(event, element){ fn.PNodeClick(event, element); }}, {nodeName:"samp",className:"JTreeMenu-CNode-Item",fn:function(event, element){ fn.CNodeClick(event, element); }} ] }; //公共变量对象,存放外部传入参数 public = { //要添加到的父级元素 pNode: null, //菜单项 menu: [ { node:'用户管理', ico: '', fn: null, childNode: [ {node:'用户管理',fn:null}, {node:'权限管理',fn:null} ] } ], //皮肤颜色 color: null }; //内部实现函数对象 fn = { /** * 菜单父级项Click事件 * @params event <Event> 事件对象 * @params node <Element> 当前事件触发元素 */ PNodeClick: function(event, node){ //找到该项的子集 var cNode = SJ.nextPrev([node])[0]; var cNodeItems = SJ.children([cNode]); var len = cNodeItems.length, h = 36, h1; var cNodeH = parseInt(cNode.style.height); var i = SJ.browser().firefox ? 4 : 8; if(private.thread){ private.thread.stop(); } if(isNaN(cNodeH) || cNodeH == 1){ cNodeH = 1, h1 = len*h; private.thread = new SJ.Thread(function(){ cNodeH += i; if(cNodeH >= h1){ private.thread.stop(); cNodeH = h1 == 0 ? 1 : h1; } cNode.style.height = (cNodeH)+'px'; }, 1); private.thread.run(); } else{ h1 = 1; private.thread = new SJ.Thread(function(){ cNodeH -= i; if(cNodeH <= h1){ private.thread.stop(); cNodeH = h1; } cNode.style.height = (cNodeH)+'px'; }, 1); private.thread.run(); } if(len == 0){ node = $(node); var url = node.attr('url'); var equalto = node.attr('equalto'); if(url){ fn.jumpPage(url, equalto); } } }, jumpPage: function(url, equalto){ equalto = equalto ? equalto : '#iframeContent'; $($(top.document).find(equalto)).attr('src',url); }, /** * 菜单子级项Click事件 * @params event <Event> 事件对象 * @params node <Element> 当前事件触发元素 */ CNodeClick: function(event, node){ var cNodes = SJ.findElement(SJ('.SJ-JTreeMenu-Main'), '.JTreeMenu-CNode-Item'); var len = cNodes.length, i; for(i=0;i<len;i++){ SJ.removeClass([cNodes[i].parentNode], 'menu_left_now'); } SJ.addClass([node.parentNode], 'menu_left_now'); node = $(node).parent(); var url = node.attr('url'); var equalto = node.attr('equalto'); if(url){ fn.jumpPage(url, equalto); } } }; //内部函数操作对象 handle = { /** * 初始化 */ init: function(args){ if(args){ SJ.extend(public, args, true); } //绑定事件 handle.bindEvent(); }, /** * 绑定事件 */ bindEvent: function(){ var TreeMenu = SJ('.SJ-JTreeMenu-Main')[0]; //禁止内容选择 SJ.disableSelection(TreeMenu); //禁止右键 SJ.shieldRightMenu(TreeMenu); SJ.eventBubbling(private.EventClick, "click", TreeMenu); } }; //初始化实例 handle.init(args); //返回对象,提供外部调用的函数 result = { }; SJ.extend(this, result); };<file_sep>/src/main/webapp/js/export/qualityReport.js $(function() { window.onresize(); //隐藏加载效果 $("#background").hide(); $("#bar_id").hide(); $.parser.parse('#cc'); //绑定下拉框选择时间 $("#cc").combobox({ onSelect : function() { //$("#weekend").show(); var type = parseInt($(this).combobox("getValue")); showHide(type); changeDefDate(type); } }); var msg = $("#msg").val(); if (msg == "1") { $.messager.alert("提示", "查询失败!", "error"); } showHide(parseInt($("#cc").combobox("getValue"))); $.parser.parse('#cc'); //进入页面显示默认时间 if (show == 0) { getLastDay(new Date()); } // 初始化区域dialog initAreaDialog(); //需要填充kpi名称 var names = ["comp_score_rank","total_test_rate","total_solve_rate","total_delay_rate","total_over_rate","total_send_rate","total_complaint_rate","total_upgrade_rate","total_reject_rate"]; //颜色标识 fillBgColor(names,'.yybb_right_top',groupnum); var count = 0; $("#setBtn").click(function(){ if(count == 0){ var timelyrate = $("#timelyrate").val(); var qualdate = $("#qualdate").val(); if(qualdate != null && qualdate != ""){ if(timelyrate != null && timelyrate != "" && /^[1-9]\d{0,2}$/.exec(timelyrate)){ count ++; $("#setValueForm").ajaxForm({ type: "POST", url: contextPath + "/export/updateQual", success: function(data) { count = 0; if(data.msg == 1){ $.messager.alert("提示","设置成功!","success"); //修改隐藏域的累计起始时间(现在不修改是为了导出时和页面上的数量保持一致) //$("#systime").val(qualdate); }else{ $.messager.alert("提示","设置失败!","error"); } } }); $("#setValueForm").submit(); }else{ $.messager.alert("提示","及时率默认时间只能是在1~999之间的整数!","warning"); } }else{ $.messager.alert("提示","请选择累计起始时间!","warning"); } } }); }); // 查询 function search() { if(checkDate()){ $("#background").show(); $("#bar_id").show(); $("#searchForm").submit(); } } //导出excel function exportReport() { if(checkDate()){ var starttime = $("#starttime").val(); var endtime = $("#endtime").val(); var areaids = $("#areaids").val(); var queryids = $("#queryids").val(); var type = $("#cc").combobox("getValue"); var url = contextPath + "/export/downloadqual?type=" + type + "&starttime=" + starttime + "&endtime=" + endtime + "&areaids=" + areaids+"&queryids=" +queryids; // $("#download").attr("href",url).click(); var obja = document.getElementById("download"); obja.src = url; } } <file_sep>/src/main/webapp/js/reportconfig/groupconfig.js $(function() { var optInit = {callback: function(page_index,jq){ $.ajax({ type:"post", url: contextPath + "/reportconfig/grouplist/template", data:({pageIndex: page_index+1}), success:function(data){ $('#content').html(data); } }); return false; } }; $("#pager").pagination(pageTotal, optInit); $("#edit").click(function() { $("#managerdlg").dialog({ href : contextPath + "/reportconfig/groupmanager?type=0", height : 478, width : 668, title : "编辑", modal : true, closed : false, onClose:function(){ window.location.href = window.location.href; } }); $('#managerdlg').dialog('open'); $.parser.parse('#managerdlg'); }); var saveCount = 0; // 分公司归属点击事件 $('.btn_save').die().click(function(){ if(saveCount == 0){ saveCount ++; var _id = $('.con-tk-left-now').attr('id'); if(_id == 'groupgs'){ var groups = new Array(); $('.areas').each(function(){ var obj = {}; obj['groupid'] = $(this).attr('val'); obj['areas'] = []; $(this).find('li').each(function(){ obj['areas'].push($(this).attr('val')); }); groups.push(obj); }); $.ajax({ type:'post', url:contextPath + '/reportconfig/guishugroup', data:({groups : JSON.stringify(groups)}), dataType:"json", success:function(data){ if(data.msg == 1){ $.messager.alert('提示','操作成功','success',function(){ $('#managerdlg').dialog('refresh',contextPath + '/reportconfig/groupmanager?type=0'); }); }else{ $.messager.alert('提示','操作失败!','error'); } saveCount = 0; } }); }else{ $('#managerdlg').dialog('close'); window.location.href = window.location.href; } } }); // 名称点击事件 $('#grouplb').die().live('click', function() { $('#groupgs').removeClass('con-tk-left-now'); $(this).addClass('con-tk-left-now'); $('.gs').hide(); $('.lb').show(); }); $('#groupgs').die().live('click', function() { $('#grouplb').removeClass('con-tk-left-now'); $(this).addClass('con-tk-left-now'); $('.lb').hide(); $('.gs').show(); }); // 类别点击事件 $('.configure-family').find('li').die().live('click', function() { if (!$(this).hasClass('now')) { $("#right").find('img').attr('src', '../images/configure-01b.png'); $("#right").attr('val', 0); $("#left").find('img').attr('src', '../images/configureb.png'); $("#left").attr('val', 0); $('.areas').find('li').removeClass('areanow'); $('.unareas').find('li').removeClass('areanow'); $('.configure-family').find('li').removeClass('now'); $(this).addClass('now'); // 隐藏已归属的区域 $('.areas').hide(); // // 隐藏未归属区域 // $('.unareas').hide(); var groupid = $(this).attr('val'); // 显示当前已归属的区域 $('#areas_' + groupid).show(); // // 显示当前未归属区域 // $('#unareas_' + groupid).show(); } }); var rightFn = null; var leftFn = null; // 已归属区域点击事件 $('.areas').find('li').die().live('click', function() { // 取消上次延时未执行的方法 clearTimeout(rightFn); var _this = $(this); rightFn = setTimeout(function() { $("#right").find('img').attr('src', '../images/configure-01.png'); $("#right").attr('val', 1); $('.areas').find('li').removeClass('areanow'); _this.addClass('areanow'); }, 300); }); // 已归属区域双击击事件 $('.areas').find('li').live('dblclick', function() { // 取消上次延时未执行的方法 clearTimeout(rightFn); // var groupid = $(this).parent().attr('val'); $('.areas').find('li').removeClass('areanow'); $('.unareas').append($(this)); }); // 未归属区域点击事件 $('.unareas').find('li').live('click', function() { // 取消上次延时未执行的方法 clearTimeout(leftFn); var _this = $(this); leftFn = setTimeout(function() { $("#left").find('img').attr('src', '../images/configure.png'); $("#left").attr('val', 1); $('.unareas').find('li').removeClass('areanow'); _this.addClass('areanow'); }, 300); }); // 未归属区域双击击事件 $('.unareas').find('li').live('dblclick', function() { // 取消上次延时未执行的方法 clearTimeout(leftFn); var groupid = $(".now").attr('val'); $('.unareas').find('li').removeClass('areanow'); $('#areas_' + groupid).append($(this)); }); // 点击右移 $('#right').die().live('click', function() { if ($(this).attr('val') == '1') { $(this).find('img').attr('src', '../images/configure-01b.png'); // 得到当前选中区域 var _areanow = $('.areas').find('.areanow'); _areanow.removeClass('areanow'); $('.unareas').append(_areanow); // _areanow.remove(); $(this).attr('val', 0); } }); // 点击左移 $('#left').die().live('click', function() { if ($(this).attr('val') == '1') { $(this).find('img').attr('src', '../images/configureb.png'); // 得到当前选中区域 var _unareanow = $('.unareas').find('.areanow'); _unareanow.removeClass('areanow'); var groupid = $(".now").attr('val'); $('#areas_' + groupid).append(_unareanow); $(this).attr('val', 0); } }); // 新增分公司 $("#addGroup").die().live('click', function() { $("#adddlg").dialog({ href : contextPath + "/reportconfig/addgroup", height : 130, width : 435, title : "添加分公司", modal : true, closed : false }); $('#adddlg').dialog('open'); $.parser.parse('#adddlg'); }); var addCount = 0; //添加分公司 $('.addGroup_btn').click(function() { if (addCount == 0) { addCount++; $('#addForm').ajaxForm({ url : contextPath + '/reportconfig/addgroup', beforeSubmit : function() { if (!$('#addForm').form('validate')) { addCount = 0; return false; } else { return true; } }, success : function(data) { if (data.msg == 1) { $.messager.alert("提示", "操作成功!", "success", function() { // 刷新 $('#managerdlg').dialog('refresh',contextPath + '/reportconfig/groupmanager?type=1'); $('#adddlg').dialog('close'); }); }else{ $.messager.alert("提示", "操作失败!", "error"); } addCount = 0; } }); $('#addForm').submit(); } }); //编辑分公司 $('#editGroup').die().live('click',function(){ var _chk = $("input[name='chk']:checked"); var len = _chk.length; if(len > 0){ var content = '<form method="post" id="updateForm"><ul class="form">'; for(var i=0;i<len;i++){ var groupname = $(_chk[i]).attr('groupname'); var groupid = $(_chk[i]).val(); content +='<li><span style="text-align:left;"><samp style="color:red">*</samp>分公司名称:</span><p>' + '<input name="groupname" type="text" groupid="'+groupid+'" value="' + groupname + '" class="flpi easyui-validatebox" ' + ' data-options="required:true,validType:[\'ench\',\'lengthb[4,20]\',\'remote[\\\''+contextPath+'/reportconfig/isExsit\\\',\\\'groupname\\\',\\\''+groupname+'\\\',\\\'分公司名称\\\']\']"/>' + '</p></li>'; } content += '</ul></from>'; if(len >= 6){ height = 300; }else{ height = len * 33 + 100; } $("#editdlg").dialog({ height : height, width : 435, content:content, title : "编辑", modal : true, closed : false }); $('#editdlg').dialog('open'); $.parser.parse('#editdlg'); }else{ $.messager.alert("提示","请选择你要编辑的分公司!","warning"); } }); var updateCount = 0; $(".editGroup_btn").die().live('click',function(){ if (updateCount == 0) { updateCount++; if (!$('#updateForm').form('validate')) { updateCount = 0; return false; } var _groups = $('#updateForm').find('input[name=groupname]'); var _len = _groups.length; for(var i = 0; i< _len; i++){ var val_i = $(_groups[i]).val(); var count = 0; for(var j = 0; j< _len; j++){ var val_j = $(_groups[j]).val(); if(val_i == val_j){ count ++; if(count >= 2){ $.messager.alert("提示","分公司名称不能相同!","warning"); updateCount = 0; return; } } } } var groups = new Array(); $('#updateForm').find('input[name=groupname]').each(function(){ var obj = {}; obj["groupid"] = $(this).attr('groupid'); obj["groupname"] = $(this).val(); groups.push(obj); }); $.ajax({ type:'post', url:contextPath + '/reportconfig/updategroup', data:({groups : JSON.stringify(groups)}), success:function(data){ if(data.msg == 1){ $.messager.alert('提示','操作成功!','success',function(){ $('#editdlg').dialog('close'); $('#managerdlg').dialog('refresh',contextPath + '/reportconfig/groupmanager?type=1'); }); }else{ $.messager.alert('提示','操作失败!','error'); } updateCount = 0; } }); } }); //删除分公司 $('#deleteGroup').die().live('click',function(){ var str=""; $("input[name='chk']:checked").each(function(){ str+=$(this).val()+","; }); if(str != "" && str.length > 1){ str = str.substring(0, str.length-1); deleteGroup(str); }else{ $.messager.alert("提示","请选择你要删除的分公司!","warning"); } }); }); function deleteGroup(ids){ $.messager.confirm('提示', '是否删除你选择的分公司?', function(r){ if (r){ $.ajax({ type:'post', url:contextPath + '/reportconfig/deletegroup', data:({ids : ids}), success:function(data){ if(data.msg == 1){ $.messager.alert('提示','删除成功!','success',function(){ $('#managerdlg').dialog('refresh',contextPath + '/reportconfig/groupmanager?type=1'); }); }else{ $.messager.alert('提示','删除失败!','error'); } } }); } }); } <file_sep>/src/main/java/com/complaint/action/RoleController.java package com.complaint.action; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.complaint.model.AssignAccess; import com.complaint.model.Resource; import com.complaint.model.Role; import com.complaint.page.PageBean; import com.complaint.service.ResourceService; import com.complaint.service.RoleService; import com.complaint.utils.Constant; import com.complaint.utils.RoleResourceLoader; import com.complaint.utils.TokenProcessor; @Controller @RequestMapping("/role") public class RoleController { private static final Logger logger = LoggerFactory.getLogger(RoleController.class); @Autowired private RoleService roleSerivce; @Autowired private RoleResourceLoader roleResourceLoader; @Autowired private ResourceService resourceService; @RequestMapping(value = "/rolelist") public ModelAndView rolelist(String rolename,HttpServletRequest request){ List<Resource> buttons = this.roleResourceLoader.getButtons(request); ModelAndView mv = new ModelAndView("/role/rolelist"); PageBean pb = this.roleSerivce.countRoles(rolename,1,Constant.PAGESIZE); mv.addObject("rolename", rolename); mv.addObject("pb", pb); mv.addObject("buttons", buttons); return mv; } @RequestMapping(value = "/rolelist/template") public String rolelistJson(Model model,String rolename,Integer pageIndex,HttpServletRequest request){ List<Resource> buttons = this.roleResourceLoader.getButtons(request); try { PageBean pb = this.roleSerivce.getRoleList(rolename,pageIndex,Constant.PAGESIZE); List<Role> list = (List<Role>) pb.getList(); model.addAttribute("contextPath", request.getContextPath()); model.addAttribute("list", list); model.addAttribute("buttons", buttons); } catch (Exception e) { e.printStackTrace(); logger.error("",e); } return "/role/childlist"; } @RequestMapping(value="/addRole", method = RequestMethod.GET) public ModelAndView addRole(HttpServletRequest request){ ModelAndView mv = new ModelAndView("/role/addRole"); TokenProcessor tokenProcessor=TokenProcessor.getInstance(); tokenProcessor.mvAddToken(mv, request); return mv; } @RequestMapping(value="/updateRole", method = RequestMethod.GET) public ModelAndView updateRole(HttpServletRequest request,Integer roleid){ ModelAndView mv = new ModelAndView("/role/updateRole"); Role role = this.roleSerivce.getRoleById(roleid); TokenProcessor tokenProcessor=TokenProcessor.getInstance(); tokenProcessor.mvAddToken(mv, request); mv.addObject("role", role); return mv; } @RequestMapping(value="/updateRole", method = RequestMethod.POST) public @ResponseBody Map<String, Integer> updateRole(@ModelAttribute Role role,HttpServletRequest request){ Map<String, Integer> map = new HashMap<String, Integer>(); TokenProcessor tokenProcessor=TokenProcessor.getInstance(); int msg = 0; if(!tokenProcessor.isTokenValid(request)){ msg = Constant.TOKEN_RESUBMIT; }else{ Role temp = this.roleSerivce.getRoleById(role.getRoleid()); if(temp.getRolename().equals(role.getRolename())){ msg = 1; }else{ boolean msgbol = this.roleSerivce.isExsit(role.getRolename()); if(msgbol){ msg = -1; }else{ msg = this.roleSerivce.updateRole(role); tokenProcessor.reset(request);//清楚session中的标识 roleResourceLoader.refreshRoleResource(); } } } map.put("msg", msg); return map; } @RequestMapping(value="/addRole", method = RequestMethod.POST) public @ResponseBody Map<String, Integer> addRole(@ModelAttribute Role role,HttpServletRequest request){ Map<String, Integer> map = new HashMap<String, Integer>(); TokenProcessor tokenProcessor=TokenProcessor.getInstance(); int msg = 0; if(!tokenProcessor.isTokenValid(request)){ msg = Constant.TOKEN_RESUBMIT; }else{ boolean msgbol = this.roleSerivce.isExsit(role.getRolename()); if(msgbol){ msg = -1; }else{ msg = this.roleSerivce.addRole(role); tokenProcessor.reset(request);//清楚session中的标识 roleResourceLoader.refreshRoleResource(); } } map.put("msg", msg); return map; } @RequestMapping(value="/deleteRole", method = RequestMethod.POST) public @ResponseBody Map<String, Integer> deleteRole(String ids){ Map<String, Integer> map = new HashMap<String, Integer>(); int msg =0; try { msg = this.roleSerivce.deleteRole(ids); } catch (Exception e) { logger.error("deleteRole",e); } map.put("msg", msg); return map; } @RequestMapping(value="/assign") public @ResponseBody List<AssignAccess> assign(HttpServletRequest request,Integer roleid){ List<Resource> resources = this.resourceService.getResourcesByroleId(roleid); List<Resource> allresources = this.resourceService.getAllResources(); List<AssignAccess> assignAccesses = getChildrens(allresources, resources, 0); return assignAccesses; } private List<AssignAccess> getChildrens( List<Resource> allresources, List<Resource> resources, Integer parentid){ List<AssignAccess> accesses = new ArrayList<AssignAccess>(); AssignAccess access = null; if(allresources != null && allresources.size() > 0){ for (int i = 0; i < allresources.size(); i++) { Resource resource = allresources.get(i); if(resource.getParentid().intValue() == parentid){ access = new AssignAccess(); access.setId(resource.getResourceid()); access.setText(resource.getResourcename()); access.setState("open"); if(resource.getNepotismid()!=null){ access.setAttributes(resource.getNepotismid()); } if(resources != null && resources.size() >0){ for (int j = 0; j < resources.size(); j++) { if(resource.getResourceid().intValue() == resources.get(j).getResourceid().intValue()){ if(resource.getParentid()>0){ access.setChecked(true); break; } } } } accesses.add(access); } } if(accesses.size() > 0){ for (AssignAccess assignAccess : accesses) { assignAccess.setChildren(getChildrens(allresources, resources, assignAccess.getId())); for(AssignAccess aa:assignAccess.getChildren()){ if(aa.isChecked()==false){ assignAccess.setChecked(false); } } } } } return accesses; } @RequestMapping(value="/updateAccess") public @ResponseBody Map<String, Integer> updateAccess(Integer roleid,String ids,HttpServletRequest request){ int msg =0; try { msg = roleResourceLoader.updateAccess(roleid, ids); } catch (Exception e) { logger.error("updateAccess",e); } Map<String, Integer> map = new HashMap<String, Integer>(); map.put("msg",msg); roleResourceLoader.refreshRoleResource(); return map; } @RequestMapping(value="/assignAccess/{roleid}",method = RequestMethod.GET) public ModelAndView assignAccess(@PathVariable("roleid") Integer roleid){ ModelAndView mv = new ModelAndView("/role/assignAccess"); mv.addObject("roleid",roleid); return mv; } @RequestMapping(value="/isExsit", method = RequestMethod.POST) public @ResponseBody boolean isExsit(String rolename){ boolean bool = this.roleSerivce.isExsit(rolename); return !bool; } } <file_sep>/src/main/java/com/complaint/utils/PatternUtil.java package com.complaint.utils; import java.text.DecimalFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author jyNine * */ public class PatternUtil { private static Pattern FLOATPATTERN = Pattern.compile("^(-?\\d+)(\\.\\d{1,2})?$"); /** * 验证是否是float类型 * @param input * @return */ public static boolean isFloat(String input){ Matcher matcher = FLOATPATTERN.matcher(input); return matcher.matches(); } public static String formate(String str){ if(str != null && !"".equals(str)){ str = str.replaceAll(">", "&gt;").replaceAll("<", "&lt;"); } return str; } /** * 两个double计算百分比 * @param solv * @param complain * @return */ public static double getSolvRate(double numerator ,double denominator ){ double re = 0; double a = Math.round(numerator); double b = Math.round(denominator); re = (a/b)*10000; re = Math.round(re); re = re/100; return re; } /** * 去掉两位小数末尾的0 * @param param * @return 带%的String */ public static String getDouble(double param){ DecimalFormat df = new DecimalFormat(); String style = "0.00"; df.applyPattern(style); String res = df.format(param); String test = res.substring(res.length()-1,res.length()); if(test.equals("0")){ style = "0.0"; df.applyPattern(style); res = df.format(param); test = res.substring(res.length()-1,res.length()); if(test.equals("0")){ style = "0"; df.applyPattern(style); res = df.format(param); } } return res+"%"; } } <file_sep>/src/main/java/com/complaint/service/ReportIdExcelService.java package com.complaint.service; import java.awt.Color; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFDataFormat; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.complaint.dao.GradMapper; import com.complaint.dao.ReportIndependentDao; import com.complaint.dao.ReportTaskDao; import com.complaint.model.RateColor; import com.complaint.model.TrackPoint; import com.complaint.utils.ExcelUtil; @Service("reportIdExcelService") public class ReportIdExcelService { private static final Logger logger = LoggerFactory .getLogger(ReportExcelService.class); @Autowired private ReportIndependentDao reportIndependentDao; @Autowired private GradMapper gradMapper; /** * 获取excel模板 * @param value * @param tempPath */ public void excelService(Map value ,String flowid,String tempPath ,String path , Map valueMapgraph ,List<String> keys ,List<String> evalKeys , Map eval ,Map pingMap){ FileInputStream file = null; XSSFWorkbook wb = null; try { file = new FileInputStream(tempPath); wb = new XSSFWorkbook(file); } catch (Exception e) { logger.error("",e); } // 2G轨迹点 List<TrackPoint> gsmlist = new ArrayList<TrackPoint>(); gsmlist = reportIndependentDao.getGsmByFlowid(flowid); // 3G轨迹点 List<TrackPoint> wcdmalist = new ArrayList<TrackPoint>(); wcdmalist = reportIndependentDao.getWcdmaByFlowid(flowid); //查出颜色 List<RateColor> colist=this.gradMapper.showGradColor(); //第一页 XSSFSheet sheet1 = wb.getSheet("工单详情"); firstSheetContent(sheet1,value,wb,colist ,pingMap); //第二页 XSSFSheet sheet2 = wb.getSheet("实测明细"); secondSheetContent(sheet2,gsmlist,wcdmalist,wb); //第三页 XSSFSheet sheet3 = wb.getSheet("测试评价"); threeSheetContent(sheet3,value,evalKeys,eval ,wb ,colist); //第四页 if(keys.size()>0){ XSSFSheet sheet4 = wb.getSheet("Sheet4"); forthSheetContent(sheet4,valueMapgraph,keys,wb ,evalKeys ,wcdmalist); sheet4.setForceFormulaRecalculation(true); } sheet2.setForceFormulaRecalculation(true); sheet1.setForceFormulaRecalculation(true); FileOutputStream out =null; try { out = new FileOutputStream(path); wb.write(out); } catch (Exception e) { logger.error(" ",e); } finally{ try { if(out!=null){ out.close(); } } catch (IOException e) { logger.error(" ",e); } } } /** * sheet1填入工单流水信息 */ public void firstSheetContent(XSSFSheet sheet,Map value,XSSFWorkbook wb ,List<RateColor> colist ,Map pingMap){ CellStyle style = getStyle(wb); workerOrder(sheet,value,style);//工单信息插入 testResult(sheet,value,style,colist,wb);//测试结果插入 pingValue(wb,sheet,pingMap);//ping值插入 } /** * sheet1的工单信息 */ public void workerOrder(XSSFSheet sheet,Map value,CellStyle style){ Row row3 = sheet.getRow(2);//第3行 Row row4 = sheet.getRow(3);//第4行 Row row5 = sheet.getRow(4);//第5行 Row row6 = sheet.getRow(5);//第6行 Row row7 = sheet.getRow(6);//第7行 Row row8 = sheet.getRow(7);//第8行 Row row9 = sheet.getRow(8);//第9行 Row row10 = sheet.getRow(9);//第10行 Row row11 = sheet.getRow(10);//第11行 /*Cell cellb3 = row3.getCell(1);//工单流水号 cellb3.setCellValue((String)value.get("serialnoFlow")); cellb3.setCellStyle(style); Cell cellf3 = row3.getCell(5);//系统接单时间 StringBuilder submitDateTime=new StringBuilder((String)value.get("submitDateTime")); submitDateTime.insert(10," "); cellf3.setCellValue(submitDateTime.toString()); cellf3.setCellStyle(style); Cell cellb4 = row4.getCell(1);//网络类型 cellb4.setCellValue((String)value.get("netType")); cellb4.setCellStyle(style); Cell cellf4 = row4.getCell(5);//受理路径 cellf4.setCellValue((String)value.get("dealPath")); cellf4.setCellStyle(style); Cell cellb5 = row5.getCell(1);//投诉区域 cellb5.setCellValue((String)value.get("area")); cellb5.setCellStyle(style); Cell cellf5 = row5.getCell(5);//最后测试时间 StringBuilder testDateTime=new StringBuilder((String)value.get("testDateTime")); testDateTime.insert(10," "); cellf5.setCellValue(testDateTime.toString()); cellf5.setCellStyle(style); Cell cellb6 = row6.getCell(1);//派单员工号 cellb6.setCellValue((String)value.get("workerid")); cellb6.setCellStyle(style); Cell cellf6 = row6.getCell(5);//业务产品分类 cellf6.setCellValue((String)value.get("operationClassify")); cellf6.setCellStyle(style); Cell cellb7 = row7.getCell(1);//受理号码 cellb7.setCellValue((String)value.get("acceptance")); cellb7.setCellStyle(style); Cell cellf7 = row7.getCell(5);//用户品牌 cellf7.setCellValue((String)value.get("clientid")); cellf7.setCellStyle(style); Cell cellb8 = row8.getCell(1);//客户联系电话 cellb8.setCellValue((String)value.get("customer")); cellb8.setCellStyle(style); Cell cellf8 = row8.getCell(5);//测试次数 cellf8.setCellValue((String)value.get("testTime")); cellf8.setCellStyle(style); Cell cellb9 = row9.getCell(1);//详细投诉地址 cellb9.setCellValue((String)value.get("url")); cellb9.setCellStyle(style); Cell cellb10 = row10.getCell(1);//投诉内容 cellb10.setCellValue((String)value.get("contentrs")); cellb10.setCellStyle(style); Cell cellb11 = row11.getCell(1);//模块内容 cellb11.setCellValue((String)value.get("module")); cellb11.setCellStyle(style);*/ Cell cellb3 = row3.getCell(1);//工单流水号 cellb3.setCellValue((String)value.get("serialnoFlow")); cellb3.setCellStyle(style); Cell cellf3 = row3.getCell(5);//系统接单时间 StringBuilder submitDateTime=new StringBuilder((String)value.get("submitDateTime")); submitDateTime.insert(10," "); cellf3.setCellValue(submitDateTime.toString()); cellf3.setCellStyle(style); Cell cellb4 = row4.getCell(1);//测试环节 cellb4.setCellValue((String)value.get("breakflag")); cellb4.setCellStyle(style); Cell cellf4 = row4.getCell(5);//测试次数 StringBuilder testDateTime=new StringBuilder((String)value.get("testDateTime")); testDateTime.insert(10," "); cellf4.setCellValue(testDateTime.toString()); cellf4.setCellStyle(style); Cell cellb5 = row5.getCell(1);//投诉区域 cellb5.setCellValue((String)value.get("area")); cellb5.setCellStyle(style); Cell cellf5 = row5.getCell(5);//最后测试时间 cellf5.setCellValue((String)value.get("testTime")); cellf5.setCellStyle(style); Cell cellb6 = row6.getCell(1);//派单员工号 cellb6.setCellValue((String)value.get("url")); cellb6.setCellStyle(style); } /** * sheet1的测试结果插入 */ public void testResult(XSSFSheet sheet,Map value,CellStyle style,List<RateColor> colist,XSSFWorkbook wb){ Row row17 = sheet.getRow(16);//第17行 Row row18 = sheet.getRow(17);//第18行 Row row19 = sheet.getRow(18);//第19行 Row row20 = sheet.getRow(19);//第20行 Row row21 = sheet.getRow(20);//第21行 Row row22 = sheet.getRow(21);//第22行 Row row25 = sheet.getRow(24);//第25行 Cell cellb17 = row17.getCell(1);//工单号 String str = (String)value.get("serialno"); StringBuilder serialno=new StringBuilder(str); serialno.insert((str.length()-8)," "); cellb17.setCellValue(serialno.toString()); cellb17.setCellStyle(style); Cell cellf17 = row17.getCell(5);//室内/外 cellf17.setCellValue((String)value.get("indoor")); cellf17.setCellStyle(style); Cell cella18 = row18.getCell(0);//室分/阻碍 名称 cella18.setCellValue((String)value.get("roomName")); cella18.setCellStyle(style); Cell cellb18 = row18.getCell(1);//室分/阻碍 cellb18.setCellValue((String)value.get("room")); cellb18.setCellStyle(style); Cell celle18 = row18.getCell(4);//GPS/区域 名称 celle18.setCellValue((String)value.get("gpsName")); celle18.setCellStyle(style); Cell cellf18 = row18.getCell(5);//GPS/ cellf18.setCellValue((String)value.get("gps")); cellf18.setCellStyle(style); Cell cellb19 = row19.getCell(1);//场景 cellb19.setCellValue((String)value.get("scene")); cellb19.setCellStyle(style); Cell cellf19 = row19.getCell(5);//业务状态 cellf19.setCellValue((String)value.get("operationType")); cellf19.setCellStyle(style); Cell cellb20 = row20.getCell(1);//3G占比 cellb20.setCellValue((String)value.get("wcdmaRatio")); cellb20.setCellStyle(style); Cell cellf20 = row20.getCell(5);//2G占比 cellf20.setCellValue((String)value.get("gsmRatio")); cellf20.setCellStyle(style); Cell cellb21 = row21.getCell(1);//无服务占比 cellb21.setCellValue((String)value.get("noService")); cellb21.setCellStyle(style); Cell cellf21 = row21.getCell(5);//本次综合评价 writeEval((String)value.get("evaluate"),cellf21,wb,colist); cellf21.setCellStyle(style); Cell cellb22 = row22.getCell(1);//实测位置 cellb22.setCellValue((String)value.get("testUrl")); cellb22.setCellStyle(style); /*Cell cella25 = row25.getCell(1);//指标类型 cella25.setCellValue((String)value.get("targetType")); cella25.setCellStyle(style);*/ Cell cellh25 = row25.getCell(7);//测试点数量 cellh25.setCellValue((String)value.get("point")); cellh25.setCellStyle(style); } /** * sheet1的ping值 */ public void pingValue(XSSFWorkbook wb ,XSSFSheet sheet,Map pingMap){ CellStyle style = getStyle(wb); style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION); Row row = sheet.getRow(146); Cell cell1 = row.getCell(1);//丢包率 cell1.setCellValue(pingMap.get("pinglo")==null?"":String.valueOf(pingMap.get("pinglo"))); cell1.setCellStyle(style); Cell cell2 = row.getCell(2);//最大延迟 cell2.setCellValue(pingMap.get("pingdmax")==null?"":String.valueOf(pingMap.get("pingdmax"))); cell2.setCellStyle(style); Cell cell3 = row.getCell(3);//最小延迟 cell3.setCellValue(pingMap.get("pingdmix")==null?"":String.valueOf(pingMap.get("pingdmix"))); cell3.setCellStyle(style); Cell cell4 = row.getCell(4);//平均延迟 cell4.setCellValue(pingMap.get("pingdavg")==null?"":String.valueOf(pingMap.get("pingdavg"))); cell4.setCellStyle(style); Cell cell6 = row.getCell(6);//最大下载速度 cell6.setCellValue(pingMap.get("httpsmax")==null?"":String.valueOf(pingMap.get("httpsmax"))); cell6.setCellStyle(style); Cell cell7 = row.getCell(7);//最小下载速度 cell7.setCellValue(pingMap.get("httpsmin")==null?"":String.valueOf(pingMap.get("httpsmin"))); cell7.setCellStyle(style); Cell cell8 = row.getCell(8);//平均下载速度 cell8.setCellValue(pingMap.get("httpsavg")==null?"":String.valueOf(pingMap.get("httpsavg"))); cell8.setCellStyle(style); Cell cell9 = row.getCell(9);//最大响应时间 cell9.setCellValue(pingMap.get("httptmax")==null?"":String.valueOf(pingMap.get("httptmax"))); cell9.setCellStyle(style); Cell cell10 = row.getCell(10);//最小响应时间 cell10.setCellValue(pingMap.get("httptmix")==null?"":String.valueOf(pingMap.get("httptmix"))); cell10.setCellStyle(style); Cell cell11 = row.getCell(11);//平均响应时间 cell11.setCellValue(pingMap.get("httptavg")==null?"":String.valueOf(pingMap.get("httptavg"))); cell11.setCellStyle(style); } /** * 第二sheet页插入数据 */ public void secondSheetContent(XSSFSheet sheet,List<TrackPoint> gsmlist ,List<TrackPoint> wcdmalist ,XSSFWorkbook wb){ XSSFCellStyle style= getStyle(wb); style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION); style.setFillForegroundColor(new XSSFColor(new Color(59,124,196)));// 设置前端颜色 style.setFillPattern(CellStyle.SOLID_FOREGROUND); int count = 0; //放入2G数据 int gs = gsmlist.size(); int ws = wcdmalist.size(); if(gs>=ws){ count = gs; }else{ count = ws; } if(count>0){ Row row = sheet.createRow(0); int title=0; if(gs>0){ Cell cell00 = row.createCell(title++); cell00.setCellValue("time"); cell00.setCellStyle(style); Cell cell01 = row.createCell(title++); cell01.setCellValue("Rxlev"); cell01.setCellStyle(style); Cell cell02 = row.createCell(title++); cell02.setCellValue("RxQual"); cell02.setCellStyle(style); Cell cell03 = row.createCell(title++); cell03.setCellValue("C/I"); cell03.setCellStyle(style); } if(ws>0){ if(title>0){ title += 2; } Cell cell00 = row.createCell(title++); cell00.setCellValue("time"); cell00.setCellStyle(style); Cell cell01 = row.createCell(title++); cell01.setCellValue("RSCP"); cell01.setCellStyle(style); Cell cell02 = row.createCell(title++); cell02.setCellValue("Ec/No"); cell02.setCellStyle(style); Cell cell03 = row.createCell(title++); cell03.setCellValue("Txpower"); cell03.setCellStyle(style); Cell cell04 = row.createCell(title++); cell04.setCellValue("FTP"); cell04.setCellStyle(style); } int wsg = 0;//判断时候有2G数据,没有3g就从0开始放 if(title>6){ wsg = 6; } for(int i=0;i<count;i++){ Row rows = sheet.createRow(i+1); if(i < gs){ Cell celltime = rows.createCell(0);//time celltime.setCellValue(gsmlist.get(i).getEptime()==null?"":gsmlist.get(i).getEptime()); Cell cellrx = rows.createCell(1);//rxlev cellrx.setCellValue((gsmlist.get(i).getRxlev()==null||gsmlist.get(i).getRxlev()==-9999)?"":gsmlist.get(i).getRxlev()==-9998?"No Service":String.valueOf(gsmlist.get(i).getRxlev())); Cell cellrq = rows.createCell(2);//rxqual cellrq.setCellValue((gsmlist.get(i).getRxqual()==null||gsmlist.get(i).getRxqual()==-9999)?"":gsmlist.get(i).getRxqual()==-9998?"No Service":String.valueOf(gsmlist.get(i).getRxqual())); Cell cellci = rows.createCell(3);//ci cellci.setCellValue((gsmlist.get(i).getCi()==null||gsmlist.get(i).getCi()==-9999)?"":gsmlist.get(i).getCi()==-9998?"No Service":String.valueOf(gsmlist.get(i).getCi())); } if(i < ws){ Cell cellftptime = rows.createCell(wsg);//time cellftptime.setCellValue(wcdmalist.get(i).getEptime()==null?"":wcdmalist.get(i).getEptime()); Cell cellrscp = rows.createCell(wsg+1);//RSCP cellrscp.setCellValue((wcdmalist.get(i).getRscp()==null||wcdmalist.get(i).getRscp()==-9999)?"":wcdmalist.get(i).getRscp()==-9998?"No Service":String.valueOf(wcdmalist.get(i).getRscp())); Cell cellecno = rows.createCell(wsg+2);//Ec/No cellecno.setCellValue((wcdmalist.get(i).getEcno()==null||wcdmalist.get(i).getEcno()==-9999)?"":wcdmalist.get(i).getEcno()==-9998?"No Service":String.valueOf(wcdmalist.get(i).getEcno())); Cell celltxpower = rows.createCell(wsg+3);//Txpower celltxpower.setCellValue((wcdmalist.get(i).getTxpower()==null||wcdmalist.get(i).getTxpower()==-9999)?"":wcdmalist.get(i).getTxpower()==-9998?"No Service":String.valueOf(wcdmalist.get(i).getTxpower())); Cell cellftp = rows.createCell(wsg+4);//ftpSpeed cellftp.setCellValue((wcdmalist.get(i).getFtpSpeed()==null||wcdmalist.get(i).getFtpSpeed()==-9999)?"":wcdmalist.get(i).getFtpSpeed()==-9998?"No Service":String.valueOf(wcdmalist.get(i).getFtpSpeed())); } } } sheet.setColumnWidth(0,21*256); sheet.setColumnWidth(1,10*256); sheet.setColumnWidth(2,10*256); sheet.setColumnWidth(3,10*256); sheet.setColumnWidth(6,21*256); sheet.setColumnWidth(7,10*256); sheet.setColumnWidth(8,10*256); sheet.setColumnWidth(9,10*256); } /** * sheet3数据评价展示 * @param evalKeys * @param eval */ public void threeSheetContent(XSSFSheet sheet,Map value ,List<String> evalKeys,Map eval ,XSSFWorkbook wb ,List<RateColor> colist){ CreationHelper helper = wb.getCreationHelper(); XSSFFont[] fonts = new XSSFFont[colist.size()]; for(int i = 0;i<colist.size();i++){ fonts[i] = wb.createFont(); fonts[i] = ExcelUtil.setFontColor(fonts[i], colist.get(i).getRank_color()); } Row row0 = sheet.createRow(0); Cell cell00 = row0.createCell(0); cell00.setCellValue("实测点个数"); Cell cell01 = row0.createCell(1); cell01.setCellValue((String)value.get("point")); Row row1 = sheet.createRow(1); Cell cell10 = row1.createCell(0); cell10.setCellValue("测试评价"); Cell cell11 = row1.createCell(1); String compEval = ""; //测试总评价 List<Integer> list = new ArrayList<Integer>(); for(String key:evalKeys){ if("gsm".equals(key)){ compEval += "2G:"+eval.get(key); list.add(getColorNum((String) eval.get(key))); } if("wcdma".equals(key)){ compEval += "3G:"+eval.get(key); list.add(getColorNum((String) eval.get(key))); } if("noservice".equals(key)){ compEval += "无"; } } RichTextString rts = helper.createRichTextString(compEval); if(list.size()>0){ if(list.size()==1||list.size()==2){ rts.applyFont(3, 4, fonts[list.get(0)]); } if(list.size()==2){ rts.applyFont(7, 8, fonts[list.get(1)]); } } cell11.setCellValue(rts); //指标评价 int count = 2; for(String valuekey: evalKeys){ int a = 0; a = valuekey.indexOf("_");//判断没有"_c"的key if(a==-1){ if(!(("gsm".equals(valuekey)) ||("wcdma".equals(valuekey)) ||("noservice".equals(valuekey)))){ Row row = sheet.createRow(count); Cell cell0 = row.createCell(0); cell0.setCellValue(valuekey); Cell cell1 = row.createCell(1); String indicator = (String)eval.get(valuekey); int color = getColorNum(indicator); RichTextString rtsVal = helper.createRichTextString(indicator); rtsVal.applyFont(0, 1, fonts[color]); cell1.setCellValue(rtsVal); count++; } } } } /** * sheet4柱状图放入数据 */ public void forthSheetContent(XSSFSheet sheet ,Map map ,List<String> keys,XSSFWorkbook wb ,List<String> evalKeys ,List<TrackPoint> wcdmalist){ XSSFCellStyle style = wb.createCellStyle(); XSSFDataFormat format = wb.createDataFormat(); style.setDataFormat(format.getFormat("0.00%")); List<String> key = getKey(keys ,evalKeys); for(String str:key){ int num = getRowNum(str); if(num == 0){ continue; } Row row1 = sheet.getRow(num);//x的值 Row row2 = sheet.getRow(num+1);//y的值 JSONArray xstr = (JSONArray) map.get(str+"_x"); JSONArray ystr = (JSONArray) map.get(str+"_y"); //X轴放入值 if(num == 2|| num==14){ Cell cell11 = row1.getCell(1); cell11.setCellValue((String)xstr.get(0)); Cell cell12 = row1.getCell(2); cell12.setCellValue((String)xstr.get(1)); Cell cell13 = row1.getCell(3); cell13.setCellValue((String)xstr.get(2)); Cell cell14 = row1.getCell(4); cell14.setCellValue((String)xstr.get(3)); Cell cell15 = row1.getCell(5); cell15.setCellValue((String)xstr.get(4)); Cell cell16 = row1.getCell(6); cell16.setCellValue((String)xstr.get(5)); }else if(num == 8|| num==20){ Cell cell11 = row1.getCell(1); cell11.setCellValue("<"+(String)xstr.get(5)); Cell cell12 = row1.getCell(2); cell12.setCellValue("["+(String)xstr.get(4)+")"); Cell cell13 = row1.getCell(3); cell13.setCellValue("["+(String)xstr.get(3)+")"); Cell cell14 = row1.getCell(4); cell14.setCellValue("["+(String)xstr.get(2)+")"); Cell cell15 = row1.getCell(5); cell15.setCellValue("["+(String)xstr.get(1)+")"); Cell cell16 = row1.getCell(6); cell16.setCellValue(">="+(String)xstr.get(0)); }else{ Cell cell11 = row1.getCell(1); cell11.setCellValue("<"+(String)xstr.get(0)); Cell cell12 = row1.getCell(2); cell12.setCellValue("["+(String)xstr.get(1)+")"); Cell cell13 = row1.getCell(3); cell13.setCellValue("["+(String)xstr.get(2)+")"); Cell cell14 = row1.getCell(4); cell14.setCellValue("["+(String)xstr.get(3)+")"); Cell cell15 = row1.getCell(5); cell15.setCellValue("["+(String)xstr.get(4)+")"); Cell cell16 = row1.getCell(6); cell16.setCellValue(">="+(String)xstr.get(5)); } if(num == 8|| num==20){ //Y轴放入值 Cell cell21 = row2.getCell(1); String str21 = (String) ystr.get(5); cell21.setCellValue("".equals(str21)?0:Double.parseDouble(str21)*0.01); cell21.setCellStyle(style); Cell cell22 = row2.getCell(2); String str22 = (String) ystr.get(4); cell22.setCellValue("".equals(str22)?0:Double.parseDouble(str22)*0.01); cell22.setCellStyle(style); Cell cell23 = row2.getCell(3); String str23 = (String) ystr.get(3); cell23.setCellValue("".equals(str23)?0:Double.parseDouble(str23)*0.01); cell23.setCellStyle(style); Cell cell24 = row2.getCell(4); String str24 = (String) ystr.get(2); cell24.setCellValue("".equals(str24)?0:Double.parseDouble(str24)*0.01); cell24.setCellStyle(style); Cell cell25 = row2.getCell(5); String str25 = (String) ystr.get(1); cell25.setCellValue("".equals(str25)?0:Double.parseDouble(str25)*0.01); cell25.setCellStyle(style); Cell cell26 = row2.getCell(6); String str26 = (String) ystr.get(0); cell26.setCellValue("".equals(str26)?0:Double.parseDouble(str26)*0.01); cell26.setCellStyle(style); }else{ //Y轴放入值 Cell cell21 = row2.getCell(1); String str21 = (String) ystr.get(0); cell21.setCellValue("".equals(str21)?0:Double.parseDouble(str21)*0.01); cell21.setCellStyle(style); Cell cell22 = row2.getCell(2); String str22 = (String) ystr.get(1); cell22.setCellValue("".equals(str22)?0:Double.parseDouble(str22)*0.01); cell22.setCellStyle(style); Cell cell23 = row2.getCell(3); String str23 = (String) ystr.get(2); cell23.setCellValue("".equals(str23)?0:Double.parseDouble(str23)*0.01); cell23.setCellStyle(style); Cell cell24 = row2.getCell(4); String str24 = (String) ystr.get(3); cell24.setCellValue("".equals(str24)?0:Double.parseDouble(str24)*0.01); cell24.setCellStyle(style); Cell cell25 = row2.getCell(5); String str25 = (String) ystr.get(4); cell25.setCellValue("".equals(str25)?0:Double.parseDouble(str25)*0.01); cell25.setCellStyle(style); Cell cell26 = row2.getCell(6); String str26 = (String) ystr.get(5); cell26.setCellValue("".equals(str26)?0:Double.parseDouble(str26)*0.01); cell26.setCellStyle(style); } } //FTP折线图 if(wcdmalist.size()>0){ int count = 500; if(wcdmalist.size()<=500){ count = wcdmalist.size(); } for(int i=0;i<count;i++){ TrackPoint tp = wcdmalist.get(i); Row row = null; if(sheet.getRow(i) == null){ row = sheet.createRow(i); }else{ row = sheet.getRow(i); } Cell cell = null; if(row.getCell(8)==null){ cell = row.createCell(8); }else{ cell = row.getCell(8); } if(!(tp.getFtpSpeed()==null||tp.getFtpSpeed()==-9999||tp.getFtpSpeed()==-9998)){ cell.setCellValue(tp.getFtpSpeed()); } } } } /** * 计算对应key值数据放入第几行 */ public Integer getRowNum(String key){ int num = 0; if("PSC".equals(key)){ num = 14; }else if("Ec/No".equals(key)){ num = 20; }else if("TxPower".equals(key)){ num = 23; }else if("FTP下行".equals(key)||"FTP上行".equals(key)){ num = 26; }else if("BCCH".equals(key)){ num = 2; }else if("RxLev".equals(key)){ num = 5; }else if("RxQual".equals(key)){ num = 8; }else if("C/I".equals(key)){ num = 11; }else if("RSCP".equals(key)){ num = 17; } return num; } /** * 计算有哪些参数的柱状图 * @param keys * @return */ public List<String> getKey(List<String> keys ,List<String> evalKeys){ List<String> key = new ArrayList<String>(); for(String str:keys){ boolean flag = true; String nowStr = str.split("_")[0]; if(key.size()>0){ for(String oldStr:key){ if(oldStr.equals(nowStr)){ flag =false; } } } if(flag){ if("BCCH".equals(nowStr)||"PSC".equals(nowStr)){ key.add(nowStr); }else{ //利用评价参数,判断该展现的柱状图 boolean flagEval = true; for(String eval:evalKeys){ if(nowStr.equals(eval)){ flagEval = false; } } if(!flagEval){ key.add(nowStr); } } } } return key; } /** * 通用样式 */ public XSSFCellStyle getStyle(XSSFWorkbook wb){ XSSFCellStyle style = wb.createCellStyle(); //加边框 style.setBorderTop(XSSFCellStyle.BORDER_THIN); style.setBorderBottom(XSSFCellStyle.BORDER_THIN); style.setBorderLeft(XSSFCellStyle.BORDER_THIN); style.setBorderRight(XSSFCellStyle.BORDER_THIN); style.setAlignment(XSSFCellStyle.ALIGN_LEFT);// 水平居中 style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 垂直居中 return style; } /** * 测试评价带颜色写入 */ public void writeEval(String str,Cell cell ,XSSFWorkbook wb ,List<RateColor> colist){ //设置优良中差颜色 CreationHelper helper = wb.getCreationHelper(); StringBuilder strb = new StringBuilder(str); if(str.length()>=3){ strb.insert(4," "); } RichTextString rts = helper.createRichTextString(strb.toString()); XSSFFont[] fonts = new XSSFFont[colist.size()]; for(int i = 0;i<colist.size();i++){ fonts[i] = wb.createFont(); fonts[i] = ExcelUtil.setFontColor(fonts[i], colist.get(i).getRank_color()); } if(!("无".equals(str)) && str != null){ String[] value =str.split(":"); if(value.length==2){ String eval = (value[1]).trim(); int i = getColorNum(eval); rts.applyFont(3, 4, fonts[i]); }else if(value.length==3){ String eval1 = ((value[1]).trim()).substring(0,1); int i = getColorNum(eval1); rts.applyFont(3, 4, fonts[i]); String eval2 = (value[2]).trim(); int j = getColorNum(eval2); rts.applyFont(8, 9, fonts[j]); } cell.setCellValue(rts); }else{ cell.setCellValue("无"); } } public Integer getColorNum(String eval){ int i = 3; if("优".equals(eval)){ i = 0; }else if("良".equals(eval)){ i = 1; }else if("中".equals(eval)){ i = 2; }else if("差".equals(eval)){ i = 3; } return i; } } <file_sep>/src/main/java/com/complaint/action/vo/VoBean.java package com.complaint.action.vo; /** * * @ClassName: VoBean * @Description: 地图评价前台参数VO * @author: czj * @date: 2013-8-20 下午3:26:02 */ public class VoBean { private String areaids; private String areatext; private String senceids; private String senctext; private String startTime; private String endTime; private String datatype;//1-测试时间,2-接单时间 private String inside;//0-室外,1-室内 private String nettype;//-1全部,1-WCDMA,2-GSM private String testnet;//测试网络 private String testnetName;//测试网络名称 private String testtype; private String testtypeText; private String grad; private String sernos; private String jobtype;//-1全部,1-投诉工单 private String kpi; private String isFirst;//是否二次查询 private String secendSerno;//二次查询工单号 private Integer isDeal; private String testphone; private Integer verify;//审核状态 private double minlat; private double maxlat; private double minlng; private double maxlng; //V1.01.10添加字段 private Integer breakFlag; //测试环节 private String testAddr; //测试地址 private Integer userid; //用户编号(判定区域权限) private String workerOrderNet; //工单网络 private String workerOrderNetName; //工单网络 public Integer getVerify() { return verify; } public void setVerify(Integer verify) { this.verify = verify; } public double getMinlat() { return minlat; } public void setMinlat(double minlat) { this.minlat = minlat; } public double getMaxlat() { return maxlat; } public void setMaxlat(double maxlat) { this.maxlat = maxlat; } public double getMinlng() { return minlng; } public void setMinlng(double minlng) { this.minlng = minlng; } public double getMaxlng() { return maxlng; } public void setMaxlng(double maxlng) { this.maxlng = maxlng; } public String getAreatext() { return areatext; } public void setAreatext(String areatext) { this.areatext = areatext; } public String getAreaids() { return areaids; } public void setAreaids(String areaids) { this.areaids = areaids; } public String getSenceids() { return senceids; } public void setSenceids(String senceids) { this.senceids = senceids; } public String getSenctext() { return senctext; } public void setSenctext(String senctext) { this.senctext = senctext; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public String getInside() { return inside; } public void setInside(String inside) { this.inside = inside; } public String getNettype() { return nettype; } public void setNettype(String nettype) { this.nettype = nettype; } public String getTesttype() { return testtype; } public void setTesttype(String testtype) { this.testtype = testtype; } public String getTesttypeText() { return testtypeText; } public String getDatatype() { return datatype; } public void setDatatype(String datatype) { this.datatype = datatype; } public void setTesttypeText(String testtypeText) { this.testtypeText = testtypeText; } public String getGrad() { return grad; } public void setGrad(String grad) { this.grad = grad; } public String getSernos() { return sernos; } public void setSernos(String sernos) { this.sernos = sernos; } public String getJobtype() { return jobtype; } public void setJobtype(String jobtype) { this.jobtype = jobtype; } public String getTestnet() { return testnet; } public void setTestnet(String testnet) { this.testnet = testnet; } public String getTestnetName() { return testnetName; } public void setTestnetName(String testnetName) { this.testnetName = testnetName; } public String getKpi() { return kpi; } public void setKpi(String kpi) { this.kpi = kpi; } public String getIsFirst() { return isFirst; } public void setIsFirst(String isFirst) { this.isFirst = isFirst; } public String getSecendSerno() { return secendSerno; } public void setSecendSerno(String secendSerno) { this.secendSerno = secendSerno; } public Integer getIsDeal() { return isDeal; } public void setIsDeal(Integer isDeal) { this.isDeal = isDeal; } public String getTestphone() { return testphone; } public void setTestphone(String testphone) { this.testphone = testphone; } public Integer getBreakFlag() { return breakFlag; } public void setBreakFlag(Integer breakFlag) { this.breakFlag = breakFlag; } public String getTestAddr() { return testAddr; } public void setTestAddr(String testAddr) { this.testAddr = testAddr; } public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public String getWorkerOrderNet() { return workerOrderNet; } public void setWorkerOrderNet(String workerOrderNet) { this.workerOrderNet = workerOrderNet; } public String getWorkerOrderNetName() { return workerOrderNetName; } public void setWorkerOrderNetName(String workerOrderNetName) { this.workerOrderNetName = workerOrderNetName; } } <file_sep>/src/main/java/com/complaint/service/InitPartService.java package com.complaint.service; /** * 用于在启动服务器时初始部分资源 */ import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.complaint.dao.IntegrationThresholdColorDao; import com.complaint.model.ColourCode; import com.complaint.model.RateColor; import com.complaint.utils.CreateImgByColors; @Service("initPartService") public class InitPartService { @Autowired private RateColorCodeService rateColorCodeService; @Autowired private ColourCodeService colourCodeService; /** * 初始化综合阈值颜色图片 */ public void initIntegrationMap(String url){ List<RateColor> itc = this.rateColorCodeService.getColoursWithNoPoundSign(); RateColor [] colors = new RateColor[4]; for(int i =0;i<itc.size();i++){ colors[i] = new RateColor(); colors[i] = itc.get(i); colors[i].setRank_color("#"+itc.get(i).getRank_color()); } // 获取生成图片保存路径 String completionPath = url; try { // 生成图片 CreateImgByColors.createImage(colors,completionPath+"/images/integration/w_","●",13,14,13); CreateImgByColors.createImage(colors,completionPath+"/images/integration/g_","▼",14,12,14); CreateImgByColors.createImage(colors,completionPath+"/images/integration/s_","★",14,14,14); } catch (Exception e) { e.printStackTrace(); } } /** * 初始化测试图例图片 */ public void initKpiMap(String url){ List<ColourCode> itc = this.colourCodeService.getColoursWithNoPoundSign(); ColourCode [] colors = new ColourCode[6]; for(int i =0;i<itc.size();i++){ colors[i] = new ColourCode(); colors[i] = itc.get(i); colors[i].setColourcode("#"+itc.get(i).getColourcode()); } // 获取生成图片保存路径 String completionPath = url; try { // 生成图片 CreateImgByColors.createKpiImage(colors,completionPath+"/images/integration/w_","●",18,19,18); CreateImgByColors.createKpiImage(colors,completionPath+"/images/integration/g_","▼",19,16,19); CreateImgByColors.createKpiImage(colors,completionPath+"/images/integration/l_","■",19,16,19); //CreateImgByColors.createKpiImage(colors,completionPath+"/images/integration/s_","◆",23,23,23); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/src/main/webapp/js/user/userlist.js $(function() { var addCount = 0; $('.add').click(function(){ $("#dlg").dialog({ href:contextPath + '/user/addUser', height: 330,width: 435,title: "用户信息", modal: true,closed:false }); $('#dlg').dialog('open'); $.parser.parse('#dlg'); $("#valiSelect").val("0"); }); $(".saveedit").click(function(){ if(addCount == 0){ addCount ++; var type = $("#type").val(); var url = ""; if(type == 0){ url = contextPath + "/user/addUser"; }else{ url = contextPath + "/user/updateUser"; } $('#dataForm').ajaxForm({ url: url, beforeSubmit:function(){ if(!$('#dataForm').form('validate')){ addCount = 0; return false; }else{ return true; } }, success: function(data) { if(data.msg == 1){ $.messager.alert("提示","操作成功!","success",function(){ $('#dlg').dialog('close'); window.location.href = window.location.href; }); }else if (data.msg == -1){ $.messager.alert("提示","该登录名已经存在!","warning"); }else if(data.msg == -100){ //重复提交 $('#dlg').dialog('close'); window.location.href = window.location.href; }else{ $.messager.alert("提示","操作失败!","error",function(){ $('#dlg').dialog('close'); window.location.href = window.location.href; }); } } }); $("#dataForm").submit(); } }); $("#parent").attr('checked',false); $("#parent").click(function () { if($("#parent").attr('checked') == undefined){ $('input[name="ids"]').attr('checked',false); }else{ $('input[name="ids"]').attr('checked',true); } }); $("#delall").click(function(){ var str=""; $("input[name='ids']:checked").each(function(){ str+=$(this).val()+","; }); if(str != "" && str.length > 1){ str = str.substring(0, str.length-1); deleteUser(str); }else{ $.messager.alert("提示","请选择你要删除的用户!","warning"); } }); function deleteUser(ids){ $.messager.confirm('提示', '是否删除你选择的用户?', function(r){ if (r){ $.ajax({ type:"post", url:contextPath +"/user/deleteUser", data:({ids : ids}), success:function(data){ if(data.msg == 1){ $.messager.alert("提示","删除成功!","success",function(){ location.href= contextPath + "/user/userlist"; }); }else{ $.messager.alert("提示","删除失败!","error"); } } }); } }); } var optInit = {callback: function(page_index,jq){ $.ajax({ type:"post", url: contextPath + "/user/userlist/template", data:({name : $("#hiddenval").val(),pageIndex: page_index+1}), success:function(data){ $('#content').html(data); $('.edit').click(function(){ $("#dlg").dialog({ href:contextPath + '/user/updateUser?id='+$(this).attr("id")+"&timestamp1=" + new Date().getTime(), height: 330,width: 435,title: "用户信息", modal: true,closed:false }); $('#dlg').dialog('open'); $.parser.parse('#dlg'); $("#valiSelect").val("1"); }); $(".del").click(function(){ var id = $(this).attr("id"); deleteUser(id); }); $(".resetpsw").click(function(){ var id = $(this).attr("id"); $.messager.confirm('提示', '是否重置该用户的密码?', function(r){ if (r){ $.ajax({ type:"post", url:contextPath +"/user/resetpsw", data:({id : id}), success:function(data){ if(data.msg == 1){ $.messager.alert("提示","密码重置成功!","success"); }else{ $.messager.alert("提示","重置失败!","error"); } } }); } }); }); $("input[name='ids']").each(function(){ $(this).attr('checked',false); }); } }); return false; } }; $("#pager").pagination(pageTotal, optInit); /** * 分配区域 */ $(".access2").live('click' ,function(){ var userid = $(this).attr("id"); var src = contextPath + '/user/arealist?userid='+userid+"&type=0"; //打开区域选择框 $("#areadlg").dialog({ href:src, height: 400,width: 380,title: "选择区域", modal: true,closed:false }); $('#areadlg').dialog('open'); $.parser.parse('#areadlg'); //获取区域 $(".sel_area").unbind('click').click(function(){ var nodes = $('#areadlg').tree('getChecked'); var strids = ""; if(nodes.length > 0){ for(var i = 0; i < nodes.length; i++){ if(nodes[i].id!= -1){ strids += nodes[i].id + ","; } } if(strids !=null && strids != ""){ strids = strids.substring(0,strids.length-1); } } //关闭弹出层 $('#areadlg').dialog('close'); //保存区域 $.ajax({ type:"post", url: contextPath + "/user/saveArea", data:({userid: userid,areas: strids}), success: function(data){ if(data == 1){ $.messager.alert("提示","区域分配成功!","success"); }else{ $.messager.alert("警告","区域分配失败!","warning"); } } }); }); }); }); function search(){ var nameval = $.trim($("#name").val()); $("#hiddenval").val(nameval); $("#name").val(nameval); $("#searchForm").submit(); }<file_sep>/src/main/java/com/complaint/service/StaffAssessService.java package com.complaint.service; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.complaint.dao.StaffAssessDao; import com.complaint.dao.SysConfigDao; import com.complaint.model.GroupManager; import com.complaint.model.GroupScore; import com.complaint.model.StaffAreas; import com.complaint.model.StaffAssess; import com.complaint.model.Sysconfig; import com.complaint.utils.Constant; /** * 人员考核环比 * @author peng * */ @Service("staffAssessService") public class StaffAssessService { private static final Logger logger = LoggerFactory.getLogger(StaffAssessService.class); @Autowired private StaffAssessDao staffAssessDao; @Autowired private SysConfigDao sysConfigDao; public List<StaffAssess> getStaffAssess(Map<String, Object> map){ this.staffAssessDao.getStaffAssess(map); List<StaffAssess> st=(List<StaffAssess>) map.get("depts"); //List<StaffAssess> st = Test.getdata(); return st; } /** * 创建EXCEL * @param path */ public void CreateExcel(String path,Map<String, Object> map ,String type){ SXSSFWorkbook swb = new SXSSFWorkbook(100); //第一个sheet页 Sheet sheet = swb.createSheet("投诉总量环比加扣分"); CellStyle style = getTitleStyle(swb); List<StaffAssess> list = getStaffAssess(map);//查出信息 Row row = sheet.createRow(0);//第一行创建标题 row.setHeight((short)600); String[] titles = null; if(type.equals("2")){ titles = new String[]{"大组","小组","累计实测率","累计实测率得分","月测试及时率","月测试及时率得分","累计解决率","累计解决率得分" ,"累计工单滞留率","累计工单滞留率得分","累计工单驳回率","累计工单驳回率得分","累计工单超时率","累计工单超时率得分","累计工单重派率","累计工单重派率得分","累计重复投诉率","累计重复投诉率得分","累计工单升级率","累计工单升级率得分" ,"月网络投诉工单量","月网络投诉工单量得分","小组KPI考核得分","小组其它加减分","小组综合得分","小组排名","其它加减分原因"}; }else{ titles = new String[]{"大组","小组","累计实测率","累计实测率得分","测试及时率","测试及时率得分","累计解决率","累计解决率得分" ,"累计工单滞留率","累计工单滞留率得分","累计工单驳回率","累计工单驳回率得分","累计工单超时率","累计工单超时率得分","累计工单重派率","累计工单重派率得分","累计重复投诉率","累计重复投诉率得分","累计工单升级率","累计工单升级率得分" ,"网络投诉工单量","网络投诉工单量得分","小组KPI考核得分","小组其它加减分","小组综合得分","小组排名","其它加减分原因"}; } for(int i=0;i<titles.length;i++){ Cell cell = row.createCell(i); cell.setCellValue(titles[i]); cell.setCellStyle(style); } endowValue(sheet,swb,list);//单元格赋值 //第二个sheet页 Sheet sheet1 = swb.createSheet("人员与区域统计数据"); Map<String,Object> samap = new HashMap<String, Object>(); if(type.equals("2")){ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Calendar ca = Calendar.getInstance(); ca.set(Calendar.YEAR,Integer.parseInt(map.get("m_time").toString().split("-")[0])); ca.set(Calendar.MONTH,Integer.parseInt(map.get("m_time").toString().split("-")[1]) - 1); ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH)); String e_time = format.format(ca.getTime()); samap.put("s_time", map.get("m_time").toString() + "-01"); samap.put("e_time", e_time); }else{ samap.put("s_time", map.get("s_time")); samap.put("e_time", map.get("e_time")); } String acctime = this.sysConfigDao.queryData(Constant.RP_CENTER_CUMULATIVE_START_TIME); samap.put("acctime", acctime); List<StaffAreas> sa = this.staffAssessDao.getStaffAreas(samap); String[] ts = new String[]{"人员","区域","总量","升级投诉","超时","按时办结率","重复派单","重复派单率","重复投诉","重复投诉率","真正解决量"}; Row row1 = sheet1.createRow(0);//第一行创建标题 //创建标题 for(int i=0;i<ts.length;i++){ Cell cell = row1.createCell(i); cell.setCellValue(ts[i]); cell.setCellStyle(style); } CellStyle style1 = getStyle(swb); //人员与区域统计数据数据填充 setStaffAreasValue(sheet1,sa,style1); try { FileOutputStream out = new FileOutputStream(path); swb.write(out); out.close(); } catch (FileNotFoundException e) { logger.error("StaffAssessService get FileOutputStream",e); } catch (IOException e) { logger.error("StaffAssessService close FileOutputStream",e); } } /** * 人员与区域统计数据数据填充 * @param sheet * @param sa */ public static void setStaffAreasValue(Sheet sheet,List<StaffAreas> sa,CellStyle style){ int count = 1; for(int i = 0; i < sa.size(); i ++){ Row row = sheet.createRow(count); StaffAreas staff = sa.get(i); List<StaffAreas> list = staff.getList(); int size = list.size(); //合并单元格 sheet.addMergedRegion(new CellRangeAddress(count, count + size - 1, 0,0)); //创建人员单元格 Cell cell = row.getCell(0); if(null == cell){ cell = row.createCell(0); } cell.setCellValue(staff.getName()); if(i == sa.size() - 1){ Row last = sheet.createRow(count + size - 1); Cell lastCell = last.createCell(0); lastCell.setCellStyle(style); } cell.setCellStyle(style); //填充kpi值 for (int j = 0; j < list.size(); j++) { int num = 1; StaffAreas sta = list.get(j); Row r = sheet.getRow(count + j); if(null == r){ r = sheet.createRow(count + j); } Cell cell1 = r.createCell(num ++);//区域 cell1.setCellValue(sta.getAreaname()); cell1.setCellStyle(style); Cell cell2 = r.createCell(num ++);//总量 cell2.setCellValue(sta.getCurr_serialno()); cell2.setCellStyle(style); Cell cell3 = r.createCell(num ++);//升级投诉 cell3.setCellValue(sta.getCurr_upgrade()); cell3.setCellStyle(style); Cell cell4 = r.createCell(num ++);//超时 cell4.setCellValue(sta.getCurr_over()); cell4.setCellStyle(style); //(投诉网络总量-超时量)/投诉网络总量 Cell cell5 = r.createCell(num ++);//按时办结率 BigDecimal ontime_rate = new BigDecimal(sta.getCurr_serialno().equals(0)?0:Float.valueOf(sta.getCurr_serialno() - sta.getCurr_over())/Float.valueOf(sta.getCurr_serialno())*100); cell5.setCellValue((ontime_rate.equals(BigDecimal.ZERO)?"0":ontime_rate.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) + "%"); cell5.setCellStyle(style); Cell cell6 = r.createCell(num ++);//重复派单 cell6.setCellValue(sta.getCurr_send()); cell6.setCellStyle(style); Cell cell7 = r.createCell(num ++);//重复派单率 BigDecimal curr_send_rate = new BigDecimal(sta.getCurr_serialno().equals(0)?0:Float.valueOf(sta.getCurr_send())/Float.valueOf(sta.getCurr_serialno())*100); cell7.setCellValue((curr_send_rate.equals(BigDecimal.ZERO)?"0":curr_send_rate.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) + "%"); cell7.setCellStyle(style); Cell cell8 = r.createCell(num ++);//重复投诉 cell8.setCellValue(sta.getCurr_complaint()); cell8.setCellStyle(style); Cell cell9 = r.createCell(num ++);//重复投诉率 BigDecimal curr_complaint_rate = new BigDecimal(sta.getCurr_serialno().equals(0)?0:Float.valueOf(sta.getCurr_complaint())/Float.valueOf(sta.getCurr_serialno())*100); cell9.setCellValue((curr_complaint_rate.equals(BigDecimal.ZERO)?"0":curr_complaint_rate.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) + "%"); cell9.setCellStyle(style); Cell cell10 = r.createCell(num ++);//真正解决量 cell10.setCellValue(sta.getCurr_solve()); cell10.setCellStyle(style); } count += size; } } /** * Excel标题样式 */ public CellStyle getTitleStyle(SXSSFWorkbook swb){ CellStyle style = swb.createCellStyle(); style.setWrapText(true);//自动换行 //加边框 style.setBorderTop(XSSFCellStyle.BORDER_THIN); style.setBorderBottom(XSSFCellStyle.BORDER_THIN); style.setBorderLeft(XSSFCellStyle.BORDER_THIN); style.setBorderRight(XSSFCellStyle.BORDER_THIN); style.setAlignment(XSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中 style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 垂直居中 return style; } /** * 给单元格赋值 */ public void endowValue(Sheet sheet,SXSSFWorkbook swb ,List<StaffAssess> list){ CellStyle style = getStyle(swb);//一般样式 for(int i =0 ;i<list.size() ;i++){ StaffAssess sa =list.get(i); Row row = sheet.createRow(i+1); int count = 0; Cell cell0 = row.createCell(count++); cell0.setCellValue(sa.getGroup_big_name());//大组 cell0.setCellStyle(style); Cell cell1 = row.createCell(count++); cell1.setCellValue(sa.getGroup_small_name());//小组 cell1.setCellStyle(style); Cell cell2 = row.createCell(count++); cell2.setCellValue(sa.getTotal_test_rate()==null?"-":sa.getTotal_test_rate());//累计实测率 cell2.setCellStyle(style); Cell cell2_s = row.createCell(count++); cell2_s.setCellValue(sa.getTest_score());//累计实测率得分 cell2_s.setCellStyle(style); Cell cell3 = row.createCell(count++); cell3.setCellValue(sa.getCurr_test_timely()==null?"-":sa.getCurr_test_timely());//月测试及时率 cell3.setCellStyle(style); Cell cell3_s = row.createCell(count++); cell3_s.setCellValue(sa.getOntime_score());//月测试及时率得分 cell3_s.setCellStyle(style); Cell cell4 = row.createCell(count++); cell4.setCellValue(sa.getTotal_solve_rate()==null?"-":sa.getTotal_solve_rate());//累计解决率 cell4.setCellStyle(style); Cell cell4_s = row.createCell(count++); cell4_s.setCellValue(sa.getSolve_score());//累计解决率得分 cell4_s.setCellStyle(style); Cell cell5 = row.createCell(count++); cell5.setCellValue(sa.getTotal_delay_rate()==null?"-":sa.getTotal_delay_rate());//累计工单滞留率 cell5.setCellStyle(style); Cell cell5_s = row.createCell(count++); cell5_s.setCellValue(sa.getDelay_score());//累计工单滞留率得分 cell5_s.setCellStyle(style); Cell cell6 = row.createCell(count++); cell6.setCellValue(sa.getTotal_reject_rate()==null?"-":sa.getTotal_reject_rate());//累计工单驳回率 cell6.setCellStyle(style); Cell cell6_s = row.createCell(count++); cell6_s.setCellValue(sa.getReject_score());//累计工单驳回率得分 cell6_s.setCellStyle(style); Cell cell7 = row.createCell(count++); cell7.setCellValue(sa.getTotal_over_rate()==null?"-":sa.getTotal_over_rate());//累计工单超时率 cell7.setCellStyle(style); Cell cell7_s = row.createCell(count++); cell7_s.setCellValue(sa.getOver_score());//累计工单超时率得分 cell7_s.setCellStyle(style); Cell cell8 = row.createCell(count++); cell8.setCellValue(sa.getTotal_send_rate()==null?"-":sa.getTotal_send_rate());//累计工单重派率 cell8.setCellStyle(style); Cell cell8_s = row.createCell(count++); cell8_s.setCellValue(sa.getSend_score());//累计工单重派率得分 cell8_s.setCellStyle(style); Cell cell9 = row.createCell(count++); cell9.setCellValue(sa.getTotal_complaint_rate()==null?"-":sa.getTotal_complaint_rate());//累计重复投诉率 cell9.setCellStyle(style); Cell cell9_s = row.createCell(count++); cell9_s.setCellValue(sa.getComplaint_score());//累计重复投诉率得分 cell9_s.setCellStyle(style); Cell cell10 = row.createCell(count++); cell10.setCellValue(sa.getTotal_upgrade_rate()==null?"-":sa.getTotal_upgrade_rate());//累计工单升级率 cell10.setCellStyle(style); Cell cell10_s = row.createCell(count++); cell10_s.setCellValue(sa.getUpgrade_score());//累计工单升级率得分 cell10_s.setCellStyle(style); Cell cell11 = row.createCell(count++); cell11.setCellValue(sa.getComplaint()==null?"-":sa.getComplaint());//月网络投诉工单量 cell11.setCellStyle(style); Cell cell11_s = row.createCell(count++); cell11_s.setCellValue(sa.getSerialno_score());//月网络投诉工单量得分 cell11_s.setCellStyle(style); Cell cell12 = row.createCell(count++); cell12.setCellValue(sa.getGroup_kpi_score()==null?"-":sa.getGroup_kpi_score());//小组kpi得分 cell12.setCellStyle(style); Cell cell13 = row.createCell(count++); cell13.setCellValue(sa.getGroup_plusMinus_score());//小组加减得分 cell13.setCellStyle(style); Cell cell14 = row.createCell(count++); cell14.setCellValue(sa.getGroup_synthesis_score()==null?"-":sa.getGroup_synthesis_score());//小组综合得分 cell14.setCellStyle(style); String str = null; if(sa.getGroup_rank()==null){ str = "-"; }else{ str = sa.getGroup_rank().toString(); } Cell cell15 = row.createCell(count++); cell15.setCellValue(str);//小组排名 cell15.setCellStyle(style); Cell cell16 = row.createCell(count); cell16.setCellValue(sa.getGroup_plusMinus_cause()==null?"":sa.getGroup_plusMinus_cause());//小组加减分原因 cell16.setCellStyle(style); } } public CellStyle getStyle(SXSSFWorkbook swb){ CellStyle style = swb.createCellStyle(); //加边框 style.setBorderTop(XSSFCellStyle.BORDER_THIN); style.setBorderBottom(XSSFCellStyle.BORDER_THIN); style.setBorderLeft(XSSFCellStyle.BORDER_THIN); style.setBorderRight(XSSFCellStyle.BORDER_THIN); style.setAlignment(XSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中 style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 垂直居中 return style; } public List<StaffAssess> getinfo(Map<String, Object> map){ return getStaffAssess(map); } /** * 查出累积起始时间 * @return */ public String getReportdate(){ Sysconfig sysconfig =sysConfigDao.getAngleconfig(Constant.RP_CENTER_CUMULATIVE_START_TIME); return sysconfig.getConfigvalue(); } /** * 设置累计起始时间 */ @Transactional(rollbackFor=Exception.class) public Integer updateDate(String time)throws Exception{ Map map = new HashMap(); map.put("configvalue", time); map.put("configkey", Constant.RP_CENTER_CUMULATIVE_START_TIME); sysConfigDao.saveAngleconfig(map); return 0; } /** * 查出大组对应,小组对应分数 */ public Map<String ,Object> getScore(){ List<GroupManager> gms = staffAssessDao.getGroupScore(); List<GroupScore> gss = new ArrayList<GroupScore>(); int totalSize =0; GroupScore gsbig = null;//外层循环 List<GroupScore> list = null;//存放每个大组中的小组 GroupScore gssmall = null;//内层循环 for(GroupManager gm:gms){ boolean flag = false;//相同大组,不再加入集合 for(GroupScore g:gss){ if(g.getGroupId()==(gm.getGroup_big_id()==null?-1:gm.getGroup_big_id())){ flag = true; break; } } if(flag){ continue; } list = new ArrayList<GroupScore>(); gsbig = new GroupScore(); gsbig.setGroupId(gm.getGroup_big_id()==null?-1:gm.getGroup_big_id()); String str = ""; if(gm.getGroup_big_name()==null){ str = "未归属大组"; }else{ str = gm.getGroup_big_name(); } gsbig.setGroupName(str); for(GroupManager gmr:gms){ if((gmr.getGroup_big_id()==null?-1:gmr.getGroup_big_id()) == (gm.getGroup_big_id()==null?-1:gm.getGroup_big_id())){ gssmall = new GroupScore(); gssmall.setGroupId(gmr.getGroup_small_id()); gssmall.setGroupName(gmr.getGroup_small_name()); gssmall.setScore(gmr.getScore()==null?0:gmr.getScore()); list.add(gssmall); } } gsbig.setList(list); gsbig.setScore((double)list.size());//算大组格子宽度 totalSize += list.size();//算总共格子个数 gss.add(gsbig); } Map<String ,Object> map = new HashMap<String ,Object>(); map.put("size", totalSize); map.put("scoreMap",gss); return map; } /** * 修改加减分 */ @Transactional(rollbackFor=Exception.class) public Integer updateScore(String[] groupids,String[] scores)throws Exception{ int msg = 1; if(groupids.length==scores.length){ Map<String, Object> map=null; staffAssessDao.deleteScore(); for(int i =0;i<groupids.length;i++){ map = new HashMap<String, Object>(); int groupid = Integer.parseInt(groupids[i]); double modified = getDoubleNum(scores[i]); map.put("groupid", groupid); map.put("modified", modified); staffAssessDao.updateScore(map); msg = 0;//判断数据有修改,并成功 } } return msg; } /** * 获取中心内部考核信息 */ public Map<String ,List<Map>> getConfig(){ Map<String ,List<Map>> map = new HashMap<String ,List<Map>>(); List<Map> steps = staffAssessDao.getCenterStepConfig();//内部考核步长配置 List<Map> report = staffAssessDao.getCenterReportConfig();//内部考核基本配置 map.put("steps", steps); map.put("report", report); return map; } /** * 保存配置信息 */ @Transactional(rollbackFor=Exception.class) public Integer saveConfig(String svgstep ,String annstep ,String basic ,String kpi)throws Exception{ int msg = 0; Map map =null; String [] svgsteps = svgstep.split(","); String [] annsteps = annstep.split(","); String [] kpis =kpi.split(","); for(int i=0;i<svgsteps.length;i++){ double sv = getDoubleNum(svgsteps[i]); double an = getDoubleNum(annsteps[i]); Integer kpiid = Integer.parseInt(kpis[i]); map = new HashMap(); map.put("svg_step", sv); map.put("annular_step", an); map.put("kpi", kpiid); staffAssessDao.saveCenterStepConfig(map); } Map oldmap = new HashMap(); List<Map> report = staffAssessDao.getCenterReportConfig();//内部考核基本配置 String [] basics = basic.split(","); for(int i=0;i<basics.length;i++){ double db = getDoubleNum(basics[i]);//转化数字报错则数据有错 String bs =String.valueOf(db); oldmap = report.get(i);//获取ID值 map = new HashMap(); map.put("val", bs); map.put("id", oldmap.get("ID")); staffAssessDao.saveCenterReportConfig(map); } return msg; } /** * String转double保留两位小数 */ public double getDoubleNum(String str)throws Exception{ double d = Double.parseDouble(str); BigDecimal dd = new BigDecimal(d); d = dd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); return d; } } <file_sep>/src/main/webapp/js/ftp4g/validater.js $(function() { $.extend($.fn.validatebox.defaults.rules, { ip : {//只能输入数字 validator : function(value) { return /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/i.test(value); }, message : 'ip格式,例如172.31.0.43' }, port : {//只能输入数字 validator : function(value) { return /^[0-9]{1,5}$/i.test(value); }, message : '端口号为5位以内数字' }, ftpPath:{ validator : function(value) { var a = value.substring(0,1); var size = value.split("\."); if(a == "/" & size.length>1){ return true; }else{ return false; } }, message: 'ftp下行路径以/开头,加目录名,并且加上文件的后缀' }, ftpup:{ validator : function(value) { var a = value.substring(0,1); if(a == "/"){ return true; }else{ return false; }; }, message: 'ftp上行路径以/开头,加目录名,且不能有中文' }, num : {//只能输入数字 validator : function(value) { return /^[0-9]{0,10}$/i.test(value); }, message : '编号为10以内数字,不输入会给予默认值' }, }); });<file_sep>/src/main/webapp/js/export/staffAssess.js $(function(){ var count = 0; //隐藏加载效果 $("#background").hide(); $("#bar_id").hide(); var msg = $("#msg").val(); if (msg == "1") { $.messager.alert("提示", "查询失败!", "error"); } $("#cc").combobox({ onSelect : function() { var type = parseInt($(this).combobox("getValue")); if(type == 1){ $("#m_timetitle").hide(); $("#m_timediv").hide(); $("#s_timetitle").show(); $("#s_timediv").show(); $("#e_timetitle").show(); $("#e_timediv").show(); }else if(type == 2){ $("#m_timetitle").show(); $("#m_timediv").show(); $("#s_timetitle").hide(); $("#s_timediv").hide(); $("#e_timetitle").hide(); $("#e_timediv").hide(); } $("#t_type").val(type); } }); /** * 下载导入报表页面 */ $("#leadExcel").click(function(){ var t_type = $("#cc").combobox("getValue"); var s_time = $("#s_time").val(); var e_time = $("#e_time").val(); var m_time = $("#m_time").val(); if(validateTime(t_type,s_time,e_time,m_time)){ var url = contextPath+"/staffAssess/download?s_time="+s_time+"&e_time="+e_time+"&m_time="+m_time+"&t_type="+t_type; var obja = document.getElementById("download"); obja.src = url; } }); /** * 查询信息 */ $("#search").click(function(){ var t_type = $("#cc").combobox("getValue"); var s_time = $("#s_time").val(); var e_time = $("#e_time").val(); var m_time = $("#m_time").val(); if(validateTime(t_type,s_time,e_time,m_time)){ //罩子加载效果 $("#background").show(); $("#bar_id").show(); $("#searchForm").submit(); } }); /** * 修改起始时间 */ $("#setBtn").click(function(){ if(count == 0){ count++; var time = $("#reportdate").val(); var oldtime = $("#reportdate").attr("oldVal"); if(time!=oldtime){ $.ajax({ type:"post", url: contextPath+"/staffAssess/updateDate", data: ({time:time}), success: function(data){ count--; if(data==0){ $.messager.alert("提示","起始时间设置成功!","success"); }else{ $.messager.alert("提示", "起始时间设置失败!", "error"); } } }); }else{ $.messager.alert("提示", "时间没有变动!", "error"); count--; } } }); /** * 保存增减分数 */ $("#saveScore").click(function(){ if(count==0){ count++; var groupid=''; var score=''; $("input[name='groupid']").each(function(){ groupid+=$(this).val()+","; }); $("input[name='score']").each(function(){ var num = $(this).val(); if(num!=''&&typeof(num)!='undifend'){ score+=$(this).val()+","; }else{ score+=0+","; } }); groupid = groupid.substring(0,groupid.length-1); score = score.substring(0,score.length-1); var _input = $('input[name="score"]'); var flag = true; for(var i = 0;i<_input.length;i++){ var _val = $(_input[i]).val(); if(!/^(-?\d{1,3})(\.\d{1,2})?$/i.test(_val)){ flag = false; $(_input[i]).css('background-color','red'); } } if(flag){ $.ajax({ type:"post", url: contextPath+"/staffAssess/updateScore", data: ({groupid:groupid,score:score}), success: function(data){ count--; if(data==0){ $.messager.alert("提示","加减分设置成功!","success"); }else if(data==-1){ $.messager.alert("提示", "数据没有变动!", "error"); }else{ $.messager.alert("提示", "加减分设置失败!", "error"); } } }); }else{ $.messager.alert("提示", "请检查数据是否正确!", "error"); count--; } } }); $('input[name="score"]').bind('focus blur',function(e) { if(e.type == 'focus'){ $(this).css('background-color',''); }else{ var _val = $(this).val(); if(!/^(-?\d{1,3})(\.\d{1,2})?$/i.test(_val)){ $(this).css('background-color','red'); } } }); //给分数框和下拉条赋宽度 var width = (parseInt($("#size").val()))*120; var cliwidth = document.body.clientWidth*0.98-122; $("#cliwidth").css("width",cliwidth); $("#zxnbkh").css("width",width); }); window.onresize = function() { var cliwidth = document.body.clientWidth*0.98-122; $("#cliwidth").css("width",cliwidth); }; <file_sep>/src/main/java/com/complaint/service/TolerantService.java package com.complaint.service; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.complaint.dao.BaseDao; import com.complaint.dao.TolerantDao; import com.complaint.model.Tolerante; import com.complaint.model.WorkOrder; import com.complaint.page.PageBean; @Service("tolerantService") public class TolerantService { @Autowired private TolerantDao dao; @Autowired private BaseDao baseDao; public PageBean getTolerantPage(String startTime ,String endTime ,String serialno ,String isTolerant ,String areaids ,Integer pageSize){ //组装查询条件 Map<String ,Object> map = new HashMap<String ,Object>(); map.put("startTime", startTime); map.put("endTime", endTime); map.put("serialno", serialno); map.put("isTolerant", isTolerant); //区域有值进行处理 if(areaids!=null&&!("".equals(areaids))){ if(areaids.indexOf("-1")<0){ //选择全部区域就不赋值,没有areaid默认是全部 //没有选择全部区域,就拆分成list,sql中循环 List<Integer> areas = new ArrayList<Integer>(); String[] str = areaids.split(","); for(String areaid:str){ areas.add(Integer.parseInt(areaid)); } map.put("areas", areas); } } //更具条件查询行数 int count = dao.getTolerantPage(map); PageBean pb = new PageBean(); //统计页数,每页个数 pb.setPageSize(pageSize); pb.setPageIndex(1); pb.setTotalPage(count); return pb; } public List<WorkOrder> getList(String startTime ,String endTime ,String serialno ,String isTolerant ,String areaids ,Integer pageIndex ,Integer pageSize){ List<WorkOrder> list = new ArrayList<WorkOrder>(); //组装查询条件 Map<String ,Object> map = new HashMap<String ,Object>(); map.put("startTime", startTime); map.put("endTime", endTime); map.put("serialno", serialno); map.put("isTolerant", isTolerant); //区域有值进行处理 if(areaids!=null&&!("".equals(areaids))){ if(areaids.indexOf("-1")<0){ //选择全部区域就不赋值,没有areaid默认是全部 //没有选择全部区域,就拆分成list,sql中循环 List<Integer> areas = new ArrayList<Integer>(); String[] str = areaids.split(","); for(String areaid:str){ areas.add(Integer.parseInt(areaid)); } map.put("areas", areas); } } //组装查询页码 map.put("mbound", (pageIndex+1)*pageSize); map.put("lbound", pageIndex*pageSize); //查询当页内容 list = dao.getList(map); return list; } /** * 查询容差信息 * @param serialno * @param areaId * @return */ public List<Integer> getTolerantInfo(String serialno , Integer areaId){ Map<String ,Object> map = new HashMap<String ,Object>(); map.put("serialno", serialno); map.put("areaId", areaId); List<Integer> list = new ArrayList<Integer>(); //根据工单和区域查询该工单容差信息 list = dao.getInfo(map); return list; } @Transactional(rollbackFor=Exception.class) public Integer getUpdateInfo(String serialno , Integer areaId ,String ids ,Integer userId) throws Exception{ //删除对应工单原有容差信息 Map<String ,Object> delmap = new HashMap<String ,Object>(); delmap.put("serialno", serialno); delmap.put("areaId", areaId); dao.deleteInfo(delmap); //添加现在的容差信息 if(ids!=null&&!("".equals(ids))){// String[] str = ids.split(","); List<Integer> list = new ArrayList<Integer>(); if(str.length>0){ for(String id:str){ list.add(Integer.parseInt(id)); } } //有数据才进行,批量插入 //组装批量插入内容 List<Tolerante> tolerantes = new ArrayList<Tolerante>(); Tolerante tolerante = null; for(Integer id : list){ tolerante = new Tolerante(); tolerante.setTolerid(id); tolerante.setSerialno(serialno); tolerante.setAreaId(areaId); tolerante.setUserId(userId); tolerantes.add(tolerante); } //进行批量插入 this.baseDao.batchInsert(TolerantDao.class, tolerantes, 200); } return 1; } } <file_sep>/src/main/java/com/complaint/dao/StaffAssessDao.java package com.complaint.dao; import java.util.List; import java.util.Map; import com.complaint.model.GroupManager; import com.complaint.model.StaffAreas; import com.complaint.model.StaffAssess; /** * 人员考核环比 * @author peng * */ public interface StaffAssessDao { public List<StaffAssess> getStaffAssess(Map<String, Object> map); /** * 查询小组分数 */ List<GroupManager> getGroupScore(); /** * 删除所有加减分 */ void deleteScore(); /** * 修改加减得分 */ void updateScore(Map<String, Object> map); /** * 中心内部考核步长配置 */ List<Map> getCenterStepConfig(); /** * 设置中心内部考核步长 */ void saveCenterStepConfig(Map<String, Object> map); /** * 中心内部考核基本配置 */ List<Map> getCenterReportConfig(); /** * 设置中心内部考核基本配置 */ void saveCenterReportConfig(Map<String, Object> map); /** * 人员与区域统计数据 * @param map * @return */ List<StaffAreas> getStaffAreas(Map<String, Object> map); } <file_sep>/src/main/java/com/complaint/dao/WcdmsTaskLogDao.java package com.complaint.dao; import com.complaint.model.WcdmsTrackLog; public interface WcdmsTaskLogDao extends BatchDao{ void insert(WcdmsTrackLog wcdmsTrackLog); void delTaskWcdmaByFlowid(String flowid); } <file_sep>/src/main/webapp/js/tolerant/tolerant.js $(function(){ var optInit = {callback:function(page_index,jq){ $.ajax({ type:"post", url: contextPath + "/tolerant/tolerant/template", data:({startTime: $("#startTimeHidden").val(),endTime: $("#endTimeHidden").val(),serialno: $("#serialnoHidden").val(),isTolerant:$("#isTolerantHidden").val(),areaids:$("#areaidsHidden").val(),pageIndex: page_index}), success: function(data){ $("#content").html(data); $(".cache1").live('mouseenter',function(){ $(this).css('text-decoration','underline'); $(this).css('color','rgb(0,0,255)'); $(this).css('opacity',1); }); $(".cache1").live('mouseleave',function(){ $(this).css('text-decoration',''); $(this).css('color',''); $(this).css('opacity',''); }); } }); }}; $("#pager").pagination(pageTotal, optInit);//回调 //增加页面打开 $('.compare_test').live('click',function(){ var areaId = $(this).attr('val'); var serialno = $(this).attr('serialno'); $("#dlg").dialog({ href:contextPath + '/tolerant/edit?serialno='+serialno+"&areaId="+areaId, height: 400,width: 750,title: "请选择容差指标", modal: true,closed:false }); $('#dlg').dialog('open'); $.parser.parse('#dlg'); }); //保存容差修改 $(".save").live('click' ,function(){ var str=""; $("input[name = \"tolerantval\"]:checked").each(function(){ str+=$(this).val()+","; }); str = str.substring(0,str.length-1); var serialno = $("#serialno_info").val(); var areaId = $("#areaId_info").val(); $.ajax({ type:"post", url: contextPath + "/tolerant/update", data:({serialno : serialno ,areaId : areaId , ids : str}), success:function(data){ if(data.msg == 1){ $('#dlg').dialog('close'); $.messager.alert("提示","修改成功!","success" ,function(){ $("#reload").submit(); }); }else{ $.messager.alert("提示","删除失败!","error"); } } }); }); $("#areas").combobox({ onShowPanel:function(){ $("#areas").combobox("hidePanel"); var src = contextPath + '/workorder/arealist?areaids='+$("#areaids").val()+"&type=0"; $("#areadlg").dialog({ href:src, height: 400,width: 380,title: "选择区域", modal: true,closed:false }); $('#areadlg').dialog('open'); $.parser.parse('#areadlg'); $(".sel_area").unbind('click').click(function(){ var nodes = $('#areadlg').tree('getChecked'); var strtext = ""; var strids = ""; if(nodes.length > 0){ for(var i = 0; i < nodes.length; i++){ strids += nodes[i].id + ","; strtext += nodes[i].text + ","; } if(strids !=null && strids != ""){ strids = strids.substring(0,strids.length-1); $("#areaids").val(strids); } if(strtext !=null && strtext != ""){ strtext = strtext.substring(0,strtext.length-1); $("#areas").combobox("setText",strtext); $("#areatext").val(strtext); } }else{ $("#areaids").val('-1'); $("#areatext").val('全部'); $("#areas").combobox("setText",'全部'); } $('#areadlg').dialog('close'); }); } }); }); function search(){ var startTime = $("input[name='startTime']").val(); var endTime = $("input[name='endTime']").val(); if(startTime!=null&&startTime!=''&&endTime!=null&&endTime!=''){ $("#searchForm").submit(); }else{ $.messager.alert("警告","时间不能为空!","error"); } }<file_sep>/src/main/java/com/complaint/security/LoginAuthenticationFailure.java package com.complaint.security; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.LockedException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.session.SessionAuthenticationException; public class LoginAuthenticationFailure implements AuthenticationFailureHandler{ @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { response.setContentType("application/json;charset=UTF-8"); PrintWriter printOut = response.getWriter(); try { if(exception instanceof UsernameNotFoundException) printOut.write("{\"status\":0,\"msg\":\"该用户名不存在\"}"); else if(exception instanceof BadCredentialsException) printOut.write("{\"status\":0,\"msg\":\"用户名或密码错误!\"}"); else if(exception instanceof LockedException) printOut.write("{\"status\":0,\"msg\":\"当前用户账号已经被锁定!\"}"); else if(exception instanceof SessionAuthenticationException) printOut.write("{\"status\":0,\"msg\":\"当前用户已登陆,登陆失败!\"}"); }catch(Exception ex){ ex.printStackTrace(); }finally{ printOut.flush(); printOut.close(); } } } <file_sep>/src/main/webapp/js/validater.js $(function() { $.extend($.fn.validatebox.defaults.rules, { /** * 综合阈值 */ integration : {//只能输入数字 validator : function(value) { return /^(([1-9]\d{0,1})|(\d{1})){1}$/i.test(value); }, message : '请输入1-2位整数' }, absolutely : {//只能输入数字 validator : function(value) { return /^([1][0][0]){1}$/i.test(value); }, message : '最大值只能为100' }, /** * 评级阈值验证开始 */ rxLevFigure : {//只能输入数字 validator : function(value) { return /^(\-){1}[1-9]\d{1,2}$/i.test(value); }, message : 'RxLev参考取值范围为-47 ~ -110' }, rxQualFigure : {//只能输入数字 validator : function(value) { return /^[0-7]$/i.test(value); }, message : 'RxQual参考取值范围为0 ~ 7' }, ciFigure : {//只能输入数字 validator : function(value) { return /^(\-)?\d{1,3}$/i.test(value)&&(parseFloat(value)>=-30&&parseFloat(value)<=30); }, message : 'C/I参考取值范围为-30 ~ 30' }, rscpFigure : {//只能输入数字 validator : function(value) { return /^(((\-){1}[1-9](\d{1,2})?)|[0]){1}$/.test(value); }, message : 'Rscp参考取值范围为-115 ~ 0' }, ecnoFigure : {//只能输入数字 validator : function(value) { return /^(((\-){1}\d{1,3})|[0]){1}$/i.test(value); }, message : 'Ec/No参考取值范围为-30 ~ 0' }, txpowerFigure : {//只能输入数字 validator : function(value) { return /^(\-)?\d{1,3}$/i.test(value); }, message : 'TxPower参考取值范围为-50 ~ 50' }, rsrpFigure : {//只能输入数字 validator : function(value) { return /^(((\-){1}[1-9](\d{1,2})?)|[0]){1}$/.test(value) && parseFloat(value)>=-130 && parseFloat(value)<=0; }, message : 'RSRP参考取值范围为-130 ~ 0dBm' }, rsrqFigure : {//只能输入数字 validator : function(value) { return /^(((\-){1}[1-9](\d{1,2})?)|[0]){1}$/.test(value) && parseFloat(value)>=-30 && parseFloat(value)<=0; }, message : 'RSRQ参考取值范围为0 ~ -30db' }, sinrFigure : {//只能输入数字 validator : function(value) { return /^((((\-){1})?[1-9](\d{1,2})?)|[0]){1}$/.test(value) && parseFloat(value)>=-30 && parseFloat(value)<=30; }, message : 'SINR参考取值范围为30 ~ -30db' }, ftpupFigure : {//只能输入数字 validator : function(value) { return /^\d{1,4}$/i.test(value); }, message : 'FTP上传参考取值范围为0 ~ 5830Kbps' }, ftpdownFigure : {//只能输入数字 validator : function(value) { return /^\d{1,4}$/i.test(value); }, message : 'FTP下载参考取值范围为0 ~ 7372Kbps' }, ftpupLteFigure : {//只能输入数字 validator : function(value) { return /^\d{1,8}$/i.test(value); }, message : 'FTP上传参考取值范围为0 ~ 1500000Kbps' }, ftpdownLteFigure : {//只能输入数字 validator : function(value) { return /^\d{1,8}$/i.test(value); }, message : 'FTP下载参考取值范围为0 ~ 1500000Kbps' }, aotherFigure : {//只能输入数字 validator : function(value) { return /^(\-){1}\d{1,3}$/i.test(value); }, message : '只能输入3位及以下的负数 ' }, onlyFigure : {//只能输入3位及以下的正负数 validator : function(value) { return /^(\-)?\d{1,3}$/i.test(value); }, message : '只能输入3位及以下的正、负数 ' }, speedFigure : {//只能输入数字 validator : function(value) { return /^\d{1,4}$/i.test(value); }, message : '只能为4位及以下正整数' }, maxValue : {// 百分比中-100] validator : function(value) { return /^(\[|\(){1}((([1-9]([0-9])?(\.[0-9]([0-9])?)?)|([0]\.[1-9]([0-9])?)|([0]\.[0][1-9]))){1}[,][1][0][0](\]){1}$/i.test(value); }, message : '阈值的最小值应该以,100]结尾' }, normalValue : {// 百分比中[1-99] validator : function(value) { return /^(\[|\(){1}([1-9])?\d(\.\d(\d)?)?[,]((([1-9])?\d(\.\d(\d)?)?)|([1][0][0])){1}(\]|\)){1}$/i.test(value); }, message : '阈值的占比范围应该为0~100的开闭区间,最多包含两位小数' }, minValue : {// 百分比中[0- validator : function(value) { return /^\[[0][,]((([1-9]([0-9])?(\.[0-9]([0-9])?)?)|([0]\.[1-9]([0-9])?)|([0]\.[0][1-9]))){1}(\]|\)){1}$/i.test(value); }, message : '阈值的最小值应该以(0,开始' }, ftpMax : {// 平均速度最大值可到+∞) validator : function(value) { return /^(\[|\(){1}(([1-9]\d{0,8})|[0]){1}(([,](\+){1}[∞](\)){1})|([,][1-9]\d{0,8}(\)|\]))|(\))){1}$/i.test(value); }, message : '平均速度格式不正确,范围为[0,+∞),如果不填右边参数,默认为正无穷' }, ftpNormal : {// 平均速度一般值 validator : function(value) { return /^(\[|\(){1}\d{1,8}[,]\d{1,8}(\]|\)){1}$/i.test(value); }, message : '平均速度格式不正确,应该以4位数字组成横纵坐标逗号隔开,中括号或小括号包含' }, ftpMin : {// 平均速度最小值可以到零 validator : function(value) { return /^(\[){1}(0)[,][1-9]\d{0,8}(\]|\)){1}$/i.test(value); }, message : '平均速度格式不正确,最小值应该以(0,开始' }, /** * 评级阈值验证结束 */ idcard : {// 验证身份证 validator : function(value) { return /^\d{15}(\d{2}[A-Za-z0-9])?$/i.test(value); }, message : '身份证号码格式不正确' }, alphanumeric :{ validator : function(value){ return /^[A-Za-z0-9.]+$/i.test(value); }, message : '只能为字母,数字和点' }, float:{ validator : function(value){ return /^(-?\d+)(\.\d{1,2})?$/i.test(value); }, message : '请输入浮点数(两位有效数字)' }, uuid:{ validator : function(value){ return /^[0-9]{15}$/i.test(value); }, message : '只能为15位数字' }, equalsArray:{ validator: function(value,param){ var count = 0; $('input['+param[0]+'="'+param[1]+'"]').each(function(){ var _me = $(this).val(); if(_me != null && _me != "" && typeof(_me) != "undefined"){ if(_me == value){ count ++; } } }); if(count > 1){ return false; }else{ return true; } }, message: '请不要输入相同的{2}!' }, minLength: { validator: function(value, param){ return value.length >= param[0]; }, message: '请输入至少{0}个字符.' }, length:{validator:function(value,param){ var len=$.trim(value).length; return len>=param[0]&&len<=param[1]; }, message:"输入内容长度必须介于{0}和{1}之间." }, phone : {// 验证电话号码 validator : function(value) { return /^1[3-9]{1}[0-9]{9}$/i.test(value); }, message : '请输入正确的手机号码(如:13888888888)' }, mobile : {// 验证手机号码 validator : function(value) { return /^(13|15|18)\d{9}$/i.test(value); }, message : '手机号码格式不正确' }, intOrFloat : {// 验证整数或小数 validator : function(value) { return /^\d+(\.\d+)?$/i.test(value); }, message : '请输入数字,并确保格式正确' }, currency : {// 验证货币 validator : function(value) { return /^\d+(\.\d+)?$/i.test(value); }, message : '货币格式不正确' }, qq : {// 验证QQ,从10000开始 validator : function(value) { return /^[1-9]\d{4,9}$/i.test(value); }, message : 'QQ号码格式不正确' }, integer : {// 验证整数 validator : function(value) { return /^[+]?[1-9]+\d*$/i.test(value); }, message : '请输入整数' }, age : {// 验证年龄 validator : function(value) { return /^(?:[1-9][0-9]?|1[01][0-9]|120)$/i.test(value); }, message : '年龄必须是0到120之间的整数' }, chinese : {// 验证中文 validator : function(value) { return /^[\Α-\¥]+$/i.test(value); }, message : '请输入中文' }, ench: { validator: function(value,param){ var c = /^[\u4E00-\u9FA5\uF900-\uFA2Da-zA-Z]{1,}$/; d = new RegExp(c).test(value); return d; }, message: '只能输入中文或字母' }, english : {// 验证英语 validator : function(value) { return /^[A-Za-z]+$/i.test(value); }, message : '请输入英文' }, unnormal : {// 验证是否包含空格和非法字符 validator : function(value) { return /.+/i.test(value); }, message : '输入值不能为空和包含其他非法字符' }, username : {// 验证用户名 validator : function(value) { return /^[a-zA-Z][a-zA-Z0-9_]{5,15}$/i.test(value); }, message : '用户名不合法(字母开头,允许6-16字节,允许字母数字下划线)' }, faxno : {// 验证传真 validator : function(value) { // return /^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/i.test(value); return /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(value); }, message : '传真号码不正确' }, zip : {// 验证邮政编码 validator : function(value) { return /^[1-9]\d{5}$/i.test(value); }, message : '邮政编码格式不正确' }, ip : {// 验证IP地址 validator : function(value) { return /\d+\.\d+\.\d+\.\d+/i.test(value); }, message : 'IP地址格式不正确' }, port : {// 验证端口 validator : function(value) { return /^([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])?$/i.test(value); }, message : '端口格式不正确' }, name : {// 验证姓名,可以是中文或英文 validator : function(value) { return /^[\Α-\¥]+$/i.test(value)|/^\w+[\w\s]+\w+$/i.test(value); }, message : '请输入姓名' }, date : {// 验证姓名,可以是中文或英文 validator : function(value) { //格式yyyy-MM-dd或yyyy-M-d return /^(?:(?!0000)[0-9]{4}([-]?)(?:(?:0?[1-9]|1[0-2])\1(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])\1(?:29|30)|(?:0?[13578]|1[02])\1(?:31))|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)([-]?)0?2\2(?:29))$/i.test(value); }, message : '清输入合适的日期格式' }, msn:{ validator : function(value){ return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value); }, message : '请输入有效的msn账号(例:abc@hotnail(msn/live).com)' }, same:{ validator : function(value, param){ if($("#"+param[0]).val() != "" && value != ""){ return $("#"+param[0]).val() == value; }else{ return true; } }, message : '两次输入的密码不一致!' }, vname:{// 验证姓名,只能为中文,字母,中划线,下划线 validator : function(value) { return /^[\u4E00-\u9FA5\uF900-\uFA2Da-zA-Z\-\_]{1,}$/.test(value); }, message : '只能为中文,字母,中划线,下划线' }, maxLength:{ validator: function(value, param){ return value.length < param[0]; }, message: '最多只能输入{0}个字符.' }, telPhone:{//验证座机或者手机号码 validator : function(value) { return /^(\d{3}-|\d{4}-)?(\d{8}|\d{7})?$/.test(value) || /^1[3-9]{1}[0-9]{9}$/.test(value); }, message: '请输入电话号码(座机或手机)' }, password:{ validator : function(value) { return /^[0-9a-zA-Z\_\.\-\!\@\#\$\%|^\&\*]{1,}$/.test(value); }, message: '只能为数字,字母,下划线,中划线和常见的特殊符号' }, ftpPath:{ validator : function(value) { var a = value.substring(0,1); var size = value.split("\."); if(a == "/" & size.length>1){ return true; }else{ return false; } }, message: 'ftp路径以/开头,加目录名,并且加上文件的后缀' }, ftpup:{ validator : function(value) { var a = value.substring(0,1); if(a == "/"){ return true; }else{ return false; } }, message: 'ftp路径以/开头,加目录名' }, selectCheck: { validator: function(value,param){ if($("#"+param[1]).val()==0){ $("#"+param[1]).val("1"); return true; }else{ return $("#"+param[0]).combo("getValue")!=-1; } }, message: '该选项是必选项' }, lengthb:{ validator:function(value,param){ var len=0; for(var i = 0; i < value.length; i ++){ if((value.charCodeAt(i)>=0) && (value.charCodeAt(i)<=255)){ len+=1; }else{ len+=2; } } return len>=param[0]&&len<=param[1]; }, message : '输入内容长度必须介于{0}和{1}字节之间.' }, assessScore : {//只能输入数字 validator : function(value) { var str = value.split("."); if(str.length==1){ if(!/^(\-)?\d{1,3}$/i.test(value)){ $.fn.validatebox.defaults.rules.assessScore.message="请输入3位以内数字"; return false; }else{ return true; } }else if(str.length==2){ var str1 = str[0]; var str2 = str[1]; if(!/^(\-)?\d{1,3}$/i.test(str1)){ $.fn.validatebox.defaults.rules.assessScore.message="整数位数请输入3位以内数字"; return false; }else if(!/^\d{1,2}$/i.test(str2)){ $.fn.validatebox.defaults.rules.assessScore.message="小数位数请输入2位以内数字"; return false; } return true; }else{ $.fn.validatebox.defaults.rules.assessScore.message="请输入数字"; return false; } }, message : '' }, centerStep : {//只能输入数字 validator : function(value) { return /^\d{1,3}(([.]\d{1,2}){1})?$/i.test(value); }, message : '请输入三位以内的数字,若有小数请不要超过小数点后两位!' } }); });<file_sep>/src/main/java/com/complaint/model/KpiFlshData.java package com.complaint.model; import java.util.ArrayList; import java.util.List; public class KpiFlshData { private List<String> x =new ArrayList<String>();//室外X轴 private List<String> indoor_x =new ArrayList<String>();//室内X轴 private List<Percent> y=new ArrayList<Percent>(); private String kpiId; private String netType; private String kpiname; private Double max; private Double min; private Double avg; private String gradName;//评级名称优、良、中、差 private String gradColor;//评级对应的颜色值 private List<Percent> ftp=new ArrayList<Percent>();//ftp上下行单独查询 public List<Percent> getFtp() { return ftp; } public void setFtp(List<Percent> ftp) { this.ftp = ftp; } public String getKpiname() { return kpiname; } public void setKpiname(String kpiname) { this.kpiname = kpiname; } public String getNetType() { return netType; } public List<String> getX() { return x; } public void setX(List<String> x) { this.x = x; } public List<Percent> getY() { return y; } public void setY(List<Percent> y) { this.y = y; } public void setNetType(String netType) { this.netType = netType; } public String getKpiId() { return kpiId; } public void setKpiId(String kpiId) { this.kpiId = kpiId; } public String getType() { return type; } public void setType(String type) { this.type = type; } private String type; public Double getMax() { return max; } public void setMax(Double max) { this.max = max; } public Double getMin() { return min; } public void setMin(Double min) { this.min = min; } public Double getAvg() { return avg; } public void setAvg(Double avg) { this.avg = avg; } public List<String> getIndoor_x() { return indoor_x; } public void setIndoor_x(List<String> indoor_x) { this.indoor_x = indoor_x; } public String getGradName() { return gradName; } public void setGradName(String gradName) { this.gradName = gradName; } public String getGradColor() { return gradColor; } public void setGradColor(String gradColor) { this.gradColor = gradColor; } } <file_sep>/src/main/java/com/complaint/service/FileDeleteTaskService.java package com.complaint.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.complaint.schedual.context.Context; import com.complaint.utils.Constant; /** * 终端管理批量导入错误文件删除任务类 * @author tian.bo */ @Service("fileDeleteTaskService") public class FileDeleteTaskService implements TaskService { private static Logger log = LoggerFactory.getLogger(FileDeleteTaskService.class); public Object runTask(Context context) { String terminal_error_path = String.format("%s%s", context.getServletContext().getRealPath(""),Constant.CAS_SYSTEM_TERMINAL_ERROR_PATH); String gis_template_export_path = String.format("%s%s", context.getServletContext().getRealPath(""),Constant.CAS_GIS_TEMPLATE_EXPORT_PATH); String gis_report_export_path = String.format("%s%s", context.getServletContext().getRealPath(""),Constant.CAS_REPORT_TEMPLATE_EXPORT_PATH); new Thread(new FileDeleteThread(terminal_error_path)).start(); new Thread(new FileDeleteThread(gis_template_export_path)).start(); new Thread(new FileDeleteThread(gis_report_export_path)).start(); return null; } class FileDeleteThread implements Runnable { String path; DeleteFileTask task; public FileDeleteThread(String path){ this.path = path; task = new DeleteFileTask(path); } public void run() { try { if(task != null){ task.run(); log.info("Mission success !!"); } } catch (Exception e) { log.error(String.format("delete file error.path=%s", path),e); } } } } <file_sep>/src/main/java/com/complaint/model/WcdmsTrackLog.java package com.complaint.model; import java.math.BigDecimal; import java.util.Date; import org.codehaus.jackson.map.annotate.JsonSerialize; import com.complaint.action.JsonDateSerializer; public class WcdmsTrackLog { private String wcdmaid; private String flowid; private String uuid; private Integer areaid; private Short inside; private Date epTime; private Date testtime; private Short ftptype; private BigDecimal longitude; private BigDecimal latitude; private BigDecimal longitudeBmap; private BigDecimal latitudeBmap; private BigDecimal longitudeModify; private BigDecimal latitudeModify; private BigDecimal positionX; private BigDecimal positionY; private Short realnetType; private Long lac; private Long cid; private Integer psc; private Integer frequl; private Integer freqdl; private Integer rscp; private Integer ecNo; private BigDecimal txpower; private BigDecimal ftpSpeed; private Integer aPsc1; private Integer aRscp1; private Integer aEcNo1; private Integer aArfcn1; private Integer aPsc2; private Integer aRscp2; private Integer aEcNo2; private Integer aArfcn2; private Integer aPsc3; private Integer aRscp3; private Integer aEcNo3; private Integer aArfcn3; private Integer mPsc1; private Integer mRscp1; private Integer mEcNo1; private Integer mArfcn1; private Integer mPsc2; private Integer mRscp2; private Integer mEcNo2; private Integer mArfcn2; private Integer mPsc3; private Integer mRscp3; private Integer mEcNo3; private Integer mArfcn3; private Integer mPsc4; private Integer mRscp4; private Integer mEcNo4; private Integer mArfcn4; private Integer mPsc5; private Integer mRscp5; private Integer mEcNo5; private Integer mArfcn5; private Integer mPsc6; private Integer mRscp6; private Integer mEcNo6; private Integer mArfcn6; private Integer dPsc1; private Integer dRscp1; private Integer dEcNo1; private Integer dArfcn1; private Integer dPsc2; private Integer dRscp2; private Integer dEcNo2; private Integer dArfcn2; private Short gpsType; private Long lac_1; private Long cid_1; private Long lac_2; private Long cid_2; private Short arithmeticType; private Long range; private Short isequal; private Short type; public Date getTesttime() { return testtime; } public void setTesttime(Date testtime) { this.testtime = testtime; } public Short getGpsType() { return gpsType; } public void setGpsType(Short gpsType) { this.gpsType = gpsType; } public String getWcdmaid() { return wcdmaid; } public void setWcdmaid(String wcdmaid) { this.wcdmaid = wcdmaid == null ? null : wcdmaid.trim(); } public String getFlowid() { return flowid; } public void setFlowid(String flowid) { this.flowid = flowid == null ? null : flowid.trim(); } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid == null ? null : uuid.trim(); } public Integer getAreaid() { return areaid; } public void setAreaid(Integer areaid) { this.areaid = areaid; } public Short getInside() { return inside; } public void setInside(Short inside) { this.inside = inside; } public Date getEpTime() { return epTime; } public void setEpTime(Date epTime) { this.epTime = epTime; } public BigDecimal getLongitude() { return longitude; } public void setLongitude(BigDecimal longitude) { this.longitude = longitude; } public BigDecimal getLatitude() { return latitude; } public void setLatitude(BigDecimal latitude) { this.latitude = latitude; } public BigDecimal getLongitudeModify() { return longitudeModify; } public void setLongitudeModify(BigDecimal longitudeModify) { this.longitudeModify = longitudeModify; } public BigDecimal getLatitudeModify() { return latitudeModify; } public void setLatitudeModify(BigDecimal latitudeModify) { this.latitudeModify = latitudeModify; } public BigDecimal getPositionX() { return positionX; } public void setPositionX(BigDecimal positionX) { this.positionX = positionX; } public BigDecimal getPositionY() { return positionY; } public void setPositionY(BigDecimal positionY) { this.positionY = positionY; } public Short getRealnetType() { return realnetType; } public void setRealnetType(Short realnetType) { this.realnetType = realnetType; } public Long getLac() { return lac; } public void setLac(Long lac) { this.lac = lac; } public Long getCid() { return cid; } public void setCid(Long cid) { this.cid = cid; } public Integer getPsc() { return psc; } public void setPsc(Integer psc) { this.psc = psc; } public Integer getFrequl() { return frequl; } public void setFrequl(Integer frequl) { this.frequl = frequl; } public Integer getFreqdl() { return freqdl; } public void setFreqdl(Integer freqdl) { this.freqdl = freqdl; } public Integer getRscp() { return rscp; } public void setRscp(Integer rscp) { this.rscp = rscp; } public Integer getEcNo() { return ecNo; } public void setEcNo(Integer ecNo) { this.ecNo = ecNo; } public BigDecimal getTxpower() { return txpower; } public void setTxpower(BigDecimal txpower) { this.txpower = txpower; } public BigDecimal getFtpSpeed() { return ftpSpeed; } public void setFtpSpeed(BigDecimal ftpSpeed) { this.ftpSpeed = ftpSpeed; } public Integer getaPsc1() { return aPsc1; } public void setaPsc1(Integer aPsc1) { this.aPsc1 = aPsc1; } public Integer getaRscp1() { return aRscp1; } public void setaRscp1(Integer aRscp1) { this.aRscp1 = aRscp1; } public Integer getaEcNo1() { return aEcNo1; } public void setaEcNo1(Integer aEcNo1) { this.aEcNo1 = aEcNo1; } public Integer getaArfcn1() { return aArfcn1; } public void setaArfcn1(Integer aArfcn1) { this.aArfcn1 = aArfcn1; } public Integer getaPsc2() { return aPsc2; } public void setaPsc2(Integer aPsc2) { this.aPsc2 = aPsc2; } public Integer getaRscp2() { return aRscp2; } public void setaRscp2(Integer aRscp2) { this.aRscp2 = aRscp2; } public Integer getaEcNo2() { return aEcNo2; } public void setaEcNo2(Integer aEcNo2) { this.aEcNo2 = aEcNo2; } public Integer getaArfcn2() { return aArfcn2; } public void setaArfcn2(Integer aArfcn2) { this.aArfcn2 = aArfcn2; } public Integer getaPsc3() { return aPsc3; } public void setaPsc3(Integer aPsc3) { this.aPsc3 = aPsc3; } public Integer getaRscp3() { return aRscp3; } public void setaRscp3(Integer aRscp3) { this.aRscp3 = aRscp3; } public Integer getaEcNo3() { return aEcNo3; } public void setaEcNo3(Integer aEcNo3) { this.aEcNo3 = aEcNo3; } public Integer getaArfcn3() { return aArfcn3; } public void setaArfcn3(Integer aArfcn3) { this.aArfcn3 = aArfcn3; } public Integer getmPsc1() { return mPsc1; } public void setmPsc1(Integer mPsc1) { this.mPsc1 = mPsc1; } public Integer getmRscp1() { return mRscp1; } public void setmRscp1(Integer mRscp1) { this.mRscp1 = mRscp1; } public Integer getmEcNo1() { return mEcNo1; } public void setmEcNo1(Integer mEcNo1) { this.mEcNo1 = mEcNo1; } public Integer getmArfcn1() { return mArfcn1; } public void setmArfcn1(Integer mArfcn1) { this.mArfcn1 = mArfcn1; } public Integer getmPsc2() { return mPsc2; } public void setmPsc2(Integer mPsc2) { this.mPsc2 = mPsc2; } public Integer getmRscp2() { return mRscp2; } public void setmRscp2(Integer mRscp2) { this.mRscp2 = mRscp2; } public Integer getmEcNo2() { return mEcNo2; } public void setmEcNo2(Integer mEcNo2) { this.mEcNo2 = mEcNo2; } public Integer getmArfcn2() { return mArfcn2; } public void setmArfcn2(Integer mArfcn2) { this.mArfcn2 = mArfcn2; } public Integer getmPsc3() { return mPsc3; } public void setmPsc3(Integer mPsc3) { this.mPsc3 = mPsc3; } public Integer getmRscp3() { return mRscp3; } public void setmRscp3(Integer mRscp3) { this.mRscp3 = mRscp3; } public Integer getmEcNo3() { return mEcNo3; } public void setmEcNo3(Integer mEcNo3) { this.mEcNo3 = mEcNo3; } public Integer getmArfcn3() { return mArfcn3; } public void setmArfcn3(Integer mArfcn3) { this.mArfcn3 = mArfcn3; } public Integer getmPsc4() { return mPsc4; } public void setmPsc4(Integer mPsc4) { this.mPsc4 = mPsc4; } public Integer getmRscp4() { return mRscp4; } public void setmRscp4(Integer mRscp4) { this.mRscp4 = mRscp4; } public Integer getmEcNo4() { return mEcNo4; } public void setmEcNo4(Integer mEcNo4) { this.mEcNo4 = mEcNo4; } public Integer getmArfcn4() { return mArfcn4; } public void setmArfcn4(Integer mArfcn4) { this.mArfcn4 = mArfcn4; } public Integer getmPsc5() { return mPsc5; } public void setmPsc5(Integer mPsc5) { this.mPsc5 = mPsc5; } public Integer getmRscp5() { return mRscp5; } public void setmRscp5(Integer mRscp5) { this.mRscp5 = mRscp5; } public Integer getmEcNo5() { return mEcNo5; } public void setmEcNo5(Integer mEcNo5) { this.mEcNo5 = mEcNo5; } public Integer getmArfcn5() { return mArfcn5; } public void setmArfcn5(Integer mArfcn5) { this.mArfcn5 = mArfcn5; } public Integer getmPsc6() { return mPsc6; } public void setmPsc6(Integer mPsc6) { this.mPsc6 = mPsc6; } public Integer getmRscp6() { return mRscp6; } public void setmRscp6(Integer mRscp6) { this.mRscp6 = mRscp6; } public Integer getmEcNo6() { return mEcNo6; } public void setmEcNo6(Integer mEcNo6) { this.mEcNo6 = mEcNo6; } public Integer getmArfcn6() { return mArfcn6; } public void setmArfcn6(Integer mArfcn6) { this.mArfcn6 = mArfcn6; } public Integer getdPsc1() { return dPsc1; } public void setdPsc1(Integer dPsc1) { this.dPsc1 = dPsc1; } public Integer getdRscp1() { return dRscp1; } public void setdRscp1(Integer dRscp1) { this.dRscp1 = dRscp1; } public Integer getdEcNo1() { return dEcNo1; } public void setdEcNo1(Integer dEcNo1) { this.dEcNo1 = dEcNo1; } public Integer getdArfcn1() { return dArfcn1; } public void setdArfcn1(Integer dArfcn1) { this.dArfcn1 = dArfcn1; } public Integer getdPsc2() { return dPsc2; } public void setdPsc2(Integer dPsc2) { this.dPsc2 = dPsc2; } public Integer getdRscp2() { return dRscp2; } public void setdRscp2(Integer dRscp2) { this.dRscp2 = dRscp2; } public Integer getdEcNo2() { return dEcNo2; } public void setdEcNo2(Integer dEcNo2) { this.dEcNo2 = dEcNo2; } public Integer getdArfcn2() { return dArfcn2; } public void setdArfcn2(Integer dArfcn2) { this.dArfcn2 = dArfcn2; } public Short getFtptype() { return ftptype; } public void setFtptype(Short ftptype) { this.ftptype = ftptype; } public Long getLac_1() { return lac_1; } public void setLac_1(Long lac_1) { this.lac_1 = lac_1; } public Long getCid_1() { return cid_1; } public void setCid_1(Long cid_1) { this.cid_1 = cid_1; } public Long getLac_2() { return lac_2; } public void setLac_2(Long lac_2) { this.lac_2 = lac_2; } public Long getCid_2() { return cid_2; } public void setCid_2(Long cid_2) { this.cid_2 = cid_2; } public Short getArithmeticType() { return arithmeticType; } public void setArithmeticType(Short arithmeticType) { this.arithmeticType = arithmeticType; } public Long getRange() { return range; } public void setRange(Long range) { this.range = range; } public Short getIsequal() { return isequal; } public void setIsequal(Short isequal) { this.isequal = isequal; } public BigDecimal getLongitudeBmap() { return longitudeBmap; } public void setLongitudeBmap(BigDecimal longitudeBmap) { this.longitudeBmap = longitudeBmap; } public BigDecimal getLatitudeBmap() { return latitudeBmap; } public void setLatitudeBmap(BigDecimal latitudeBmap) { this.latitudeBmap = latitudeBmap; } public Short getType() { return type; } public void setType(Short type) { this.type = type; } } <file_sep>/src/main/java/com/complaint/service/ExportExcelService.java package com.complaint.service; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.util.IOUtils; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.context.WebApplicationContext; import com.complaint.dao.ExportExcelDao; import com.complaint.dao.SysConfigDao; import com.complaint.model.ComplainEvaluate; import com.complaint.model.ComplainStatistics; import com.complaint.model.Group; import com.complaint.model.MostTestRate; import com.complaint.model.QualTopAndLast; import com.complaint.model.QualtyReport; import com.complaint.model.RateColor; import com.complaint.model.WorkOrder; import com.complaint.utils.Constant; import com.complaint.utils.DateUtils; import com.complaint.utils.ExcelUtil; import com.complaint.utils.ReflectUtil; @Service("exportExcelService") public class ExportExcelService { @Autowired private ExportExcelDao exportExcelDao; @Autowired private StatAndEvalReportService statAndEvalReportService; @Autowired private SysConfigDao sysConfigDao; public void writeInExcel(WebApplicationContext ctx, int type, String starttime, String endtime, String areaids, String filePath, String name) throws Exception { String tempPath = filePath + Constant.CAS_TEMPLATE_PATH; filePath = filePath + Constant.CAS_REPORT_TEMPLATE_EXPORT_PATH; Map<String, Object> mapParam = new LinkedHashMap<String, Object>(); mapParam.put("type", type); mapParam.put("starttime", starttime); mapParam.put("endtime", endtime); mapParam.put("queryAreaIds", areaids); Map messMap = statAndEvalReportService.getAllStatAndEval(ctx, mapParam); ComplainStatistics statistics = (ComplainStatistics) messMap .get("stat"); ComplainEvaluate evaluate = (ComplainEvaluate) messMap.get("eval"); // 评分类 MostTestRate mostTestRate = (MostTestRate) messMap.get("mostTestRate"); // 取值 int size = statistics.getArea_id().length; // 模板名称 String fileName = ""; // 标题 String title = ""; // 标题下一行,|主要为了能找到区域值得起止位置 String content = "月实测量最多的区域是|" + mostTestRate.getCurr_max_test() + "," + "最少的区域是|" + mostTestRate.getCurr_min_test() + ";" + "累计实测率最高的区域是|" + mostTestRate.getTotal_max_test() + "," + "最低的区域是|" + mostTestRate.getTotal_min_test() + ";" + "月3G综合评价最好的区域是|" + mostTestRate.getComp_eval_3g_max() + "," + "最差的区域是|" + mostTestRate.getComp_eval_3g_min() + ";" + "月2G综合评价最好的区域是|" + mostTestRate.getComp_eval_2g_max() + "," + "最差的区域是|" + mostTestRate.getComp_eval_2g_min() + "。"; String[] strarArr = null; String titleVal = ""; if (starttime != null && !"".equals(starttime) && endtime != null && !"".equals(endtime)) { strarArr = starttime.split("-"); } // 设置标题内容 if (type == 1) { if (strarArr != null && strarArr.length > 0) { titleVal = DateUtils.dateFormat(starttime); } fileName = "template_day.xlsx"; title = "移动网络投诉测试日报 - (" + titleVal + ")"; content = content.replaceAll("月", "日"); } else if (type == 2) { if (strarArr != null && strarArr.length > 0) { titleVal = DateUtils.dateFormat(starttime) + "-" + DateUtils.dateFormat(endtime); } fileName = "template_week.xlsx"; title = "移动网络投诉测试周报-(" + titleVal + ")"; content = content.replaceAll("月", "周").replace("。", ";") + "周3G综合改善最大的区域是|" + mostTestRate.getComp_impr_3g_max() + "," + "最小的区域是|" + mostTestRate.getComp_impr_3g_min() + ";" + "周2G综合改善最大的区域是|" + mostTestRate.getComp_impr_2g_max() + "," + "最小的区域是|" + mostTestRate.getComp_impr_2g_min() + ";" + "周测试及时率最好的区域是|" + mostTestRate.getTimely_rate_max() + "," + "最差的区域是|" + mostTestRate.getTimely_rate_min() + "。"; } else { if (strarArr != null && strarArr.length > 0) { titleVal = strarArr[0] + "年" + strarArr[1] + "月"; } fileName = "template_month.xlsx"; title = "移动网络投诉测试月报-(" + titleVal + ")"; content = content.replace("。", ";") + "月3G综合改善最大的区域是|" + mostTestRate.getComp_impr_3g_max() + "," + "最小的区域是|" + mostTestRate.getComp_impr_3g_min() + ";" + "月2G综合改善最大的区域是|" + mostTestRate.getComp_impr_2g_max() + "," + "最小的区域是|" + mostTestRate.getComp_impr_2g_min() + ";" + "月测试及时率最好的区域是|" + mostTestRate.getTimely_rate_max() + "," + "最差的区域是|" + mostTestRate.getTimely_rate_min() + "。"; } // 获取累计起始时间 String defDate = sysConfigDao.queryData(Constant.REPORTDATE); // 模板路径 String temp = tempPath + fileName; copyFile(temp, filePath, name); // 读取Excel FileInputStream file = new FileInputStream(filePath + name); XSSFWorkbook workbook = new XSSFWorkbook(file); // 第一个sheet XSSFSheet sheet = workbook.getSheetAt(0); // 设置标题 以及标题 setTitle(workbook, title, size + 3, defDate); // 设置top setTopVal(workbook,content,4,size + 3,0); // 获取颜色装入数组 List<RateColor> colorsList = exportExcelDao.queryColors(); String[] colors = new String[colorsList.size()]; for (int i = 0; i < colorsList.size(); i++) { RateColor rc = colorsList.get(i); colors[rc.getRank_code() - 1] = rc.getRank_color(); } // 设置指标优良中差的背景颜色 if (type == 1) { ExcelUtil.setKpiBGColor(workbook, sheet, 15, 54, 2, colors); } else { ExcelUtil.setKpiBGColor(workbook, sheet, 17, 56, 2, colors); } String green = "#00FF00", red = "#FF0000"; // 边框样式 XSSFCellStyle style = ExcelUtil.setBackColorByCustom(workbook, ""); XSSFCellStyle greenStyle = ExcelUtil.setBackColorByCustom(workbook, green); XSSFCellStyle redStyle = ExcelUtil.setBackColorByCustom(workbook, red); // 依次填充值 int count = 4; // 区域名称 setValues(sheet, style, greenStyle, redStyle, count++, statistics.getArea_name(), 4,0); // 累积工单量 setValues(sheet, style, greenStyle, redStyle, count++, statistics.getTotal_workorder(), 4,0); // 当前工单量 setValues(sheet, style, greenStyle, redStyle, count++, statistics.getCurr_workorder(), 4,0); // 累积实测量 setValues(sheet, style, greenStyle, redStyle, count++, statistics.getTotal_test(), 0,0); // 当前实测量 setValues(sheet, style, greenStyle, redStyle, count++, statistics.getCurr_test(), 0,0); // 当前实测排名 setValues(sheet, style, greenStyle, redStyle, count++, statistics.getCurr_test_rank(), 1,0); // 累积实测率 setValues(sheet, style, greenStyle, redStyle, count++, statistics.getTotal_test_rate(), 0,0); // 累积实测排名 setValues(sheet, style, greenStyle, redStyle, count++, statistics.getTotal_test_rate_rank(), 1,0); if (type != 1) { // 及时率 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getTimely_rate(), 0,0); // 及时率排名 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getTimely_rate_rank(), 1,0); // ExcelUtil.setValues(sheet, style, greenStyle, redStyle, count++, // evaluate.getTimely_rate_rank(),1,0); } // 当前室内测试量 setValues(sheet, style, greenStyle, redStyle, count++, statistics.getCurr_in_test(), 4,0); // 当前室外测试量 setValues(sheet, style, greenStyle, redStyle, count++, statistics.getCurr_out_test(), 4,0); // rscp 优良中差 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getRscp_a(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getRscp_b(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getRscp_c(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getRscp_d(), 4,0); // ecno 优良中差 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getEc_no_a(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getEc_no_b(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getEc_no_c(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getEc_no_d(), 4,0); // Txpower 优良中差 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getTxpower_a(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getTxpower_b(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getTxpower_c(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getTxpower_d(), 4,0); // FTP上行 优良中差 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getFtp_up_a(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getFtp_up_b(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getFtp_up_c(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getFtp_up_d(), 4,0); // FTP下行 优良中差 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getFtp_down_a(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getFtp_down_b(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getFtp_down_c(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getFtp_down_d(), 4,0); // Rxlev 优良中差 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getRxlev_a(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getRxlev_b(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getRxlev_c(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getRxlev_d(), 4,0); // Rxqual 优良中差 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getRxqual_a(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getRxqual_b(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getRxqual_c(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getRxqual_d(), 4,0); // Ci 优良中差 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getCi_a(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getCi_b(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getCi_c(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getCi_d(), 4,0); // 3g综合评价 优良中差 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getComp_eval_3g_a(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getComp_eval_3g_b(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getComp_eval_3g_c(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getComp_eval_3g_d(), 4,0); // 2g综合评价 优良中差 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getComp_eval_2g_a(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getComp_eval_2g_b(), 4,0); setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getComp_eval_2g_c(), 4,0); setValues(sheet, style, greenStyle, redStyle, count, evaluate.getComp_eval_2g_d(), 4,0); if (type != 1) { count++; // 3G综合改善得分 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getComp_impr_value_3g(), 4,0); // 2G综合改善得分 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getComp_impr_value_2g(), 4,0); // 3G改善比例 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getComp_impr_ratio_3g(), 4,0); // 2G改善比例 setValues(sheet, style, greenStyle, redStyle, count++, evaluate.getComp_impr_ratio_2g(), 4,0); } // 写入excel FileOutputStream os = new FileOutputStream(filePath + name); workbook.write(os); os.flush(); os.close(); } /** * */ private void setTitle(XSSFWorkbook workbook, String title, int lastcol, String defDate) { XSSFSheet sheet = workbook.getSheetAt(0); int firstrow = 1, lastrow = 1, firstcol = 0; if (lastcol < 7) { lastcol = 7; } // 合并单元格 sheet.addMergedRegion(new CellRangeAddress(firstrow, lastrow, firstcol, lastcol - 1)); // 设置标题 XSSFRow row = sheet.createRow(1); XSSFCell cell = row.createCell(0); XSSFCellStyle style = ExcelUtil.setBackColorByCustom(workbook, "#009400"); XSSFFont[] fonts = new XSSFFont[2]; CreationHelper helper = workbook.getCreationHelper(); RichTextString rts = helper.createRichTextString(title); fonts[0] = workbook.createFont(); fonts[1] = workbook.createFont(); // 设置字体大小 fonts[0].setFontHeightInPoints((short) 16); // 设置字体 fonts[0].setFontName("宋体"); // 加粗 fonts[0].setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); fonts[1].setFontHeightInPoints((short) 14); fonts[1].setFontName("宋体"); fonts[1].setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); rts.applyFont(0, title.indexOf("(") - 1, fonts[0]); rts.applyFont(title.indexOf("(") - 1, title.length(), fonts[1]); // 水平居中 style.setAlignment(XSSFCellStyle.ALIGN_CENTER_SELECTION); // 垂直居中 style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 设置高 row.setHeightInPoints(24);// 设置行高24像素 // style.setFont(font[0]); // 设置背景颜色 // ExcelUtil.setBackColorByCustom(style, "#009400"); // 设置边框线 ExcelUtil.setBorder(lastcol - 1, 0, row, workbook); style.setBorderTop(XSSFCellStyle.BORDER_THIN); style.setBorderBottom(XSSFCellStyle.BORDER_THIN); cell.setCellValue(rts); cell.setCellStyle(style); // 设置累计起始时间 sheet.addMergedRegion(new CellRangeAddress(firstrow + 1, lastrow + 1, firstcol, lastcol - 1)); XSSFRow row_defDate = sheet.createRow(2); XSSFCell cell_defDate = row_defDate.createCell(0); XSSFCellStyle style_defDate = ExcelUtil.setBackColorByCustom(workbook, "#009400"); ; XSSFFont font = workbook.createFont(); // ExcelUtil.setBackColorByCustom(style_defDate, "#009400"); String defDateVal = "累计起始时间-" + defDate; // 设置边框线 ExcelUtil.setBorder(lastcol - 1, 0, row_defDate, workbook); style_defDate.setBorderTop(XSSFCellStyle.BORDER_THIN); style_defDate.setBorderBottom(XSSFCellStyle.BORDER_THIN); style_defDate.setAlignment(XSSFCellStyle.ALIGN_RIGHT); style_defDate.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); font.setFontName("宋体"); font.setFontHeightInPoints((short) 11); style_defDate.setFont(font); row_defDate.setHeightInPoints(24); cell_defDate.setCellStyle(style_defDate); cell_defDate.setCellValue(defDateVal); } /** * 设置最好最差 * @param workbook * @param content * @param lastcol */ private void setTopVal(XSSFWorkbook workbook, String content, int firstrow,int lastcol,int sheetIndex){ XSSFSheet sheet = workbook.getSheetAt(sheetIndex); if(sheet == null){ sheet = workbook.createSheet("top5"); } if (lastcol < 7) { lastcol = 7; } CreationHelper helper = workbook.getCreationHelper(); // 设置标题下一行 sheet.addMergedRegion(new CellRangeAddress(firstrow - 1, firstrow -1, 0, lastcol - 1)); String text = content.replace("|", ""); String green = "#00FF00", red = "#FF0000"; RichTextString rts1 = helper.createRichTextString(text); XSSFFont[] fonts1 = new XSSFFont[2]; fonts1[0] = workbook.createFont(); fonts1[1] = workbook.createFont(); fonts1[0] = ExcelUtil.setFontColor(fonts1[0], green); fonts1[1] = ExcelUtil.setFontColor(fonts1[1], red); int len = ExcelUtil.countCharNum(content, '|'); for (int i = 0; i < len; i++) { int start = ExcelUtil.getIndex(content, i + 1, '|') - i; int end = 0; if (i == (len - 1)) { end = text.length() - 1; } else { if (i % 2 == 0) { end = ExcelUtil.getIndex(text, (i + 1) / 2 + 1, ','); } else { end = ExcelUtil.getIndex(text, i / 2 + 1, ';'); } } rts1.applyFont(start, end, fonts1[i % 2]); } XSSFRow row1 = sheet.createRow(firstrow-1); XSSFCell cell1 = row1.createCell(0); cell1.setCellValue(rts1); XSSFCellStyle style1 = workbook.createCellStyle(); // 自动换行 style1.setWrapText(true); // 水平居左 style1.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 垂直居中 // style1.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); float width = 0; for (int i = 0; i < lastcol; i++) { width += sheet.getColumnWidth(i) / 256 - 0.625; } int strLength = ExcelUtil.getStrLength(text); if (width != 0) { row1.setHeightInPoints((float) Math.ceil((float) strLength / width) * 15 + 2); } style1.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); ExcelUtil.setBorder(lastcol - 1, 0, row1, workbook); style1.setBorderBottom(XSSFCellStyle.BORDER_THIN); style1.setBorderRight(XSSFCellStyle.BORDER_THIN); cell1.setCellStyle(style1); } /** * 填充值 * * @param sheet * @param rownum * 行 * @param strVal * 值 * @param num * 分公司及全网不列入颜色标识中 * @param sort * 0越大越好 1越小越好(0、1最好最差都有) 2越大越差 3、越小越差 (2、3只有最差) 4不操作 */ private void setValues(XSSFSheet sheet, XSSFCellStyle style, XSSFCellStyle greenStyle, XSSFCellStyle redStyle, int rownum, String[] strVal, int sort,int num) { Float max = null, min = null; if (sort != 4) { String str = strVal[0].replace("%", ""); max = Float.parseFloat(str); min = Float.parseFloat(str); // 获取最大最小值 if (strVal.length - num > 1) { for (int i = 3; i < strVal.length + 3 - num; i++) { String temp = strVal[i - 3].replace("%", ""); if (max < Float.parseFloat(temp)) { max = Float.parseFloat(temp); } if (min > Float.parseFloat(temp)) { min = Float.parseFloat(temp); } } } else { max = null; min = null; } } // 得到行 XSSFRow row = sheet.getRow(rownum); if (null == row) { row = sheet.createRow(rownum); } int len = strVal.length; // 给单元格赋值并给相应的单元格填充颜色 for (int i = 3; i < len + 3; i++) { XSSFCell cell = row.getCell(i); if (null == cell) { cell = row.createCell(i); } XSSFCellStyle setStyle = style; cell.setCellValue((strVal[i - 3]==null || strVal[i - 3].equals(""))?"-":strVal[i - 3]); if(i < len + 3 - num && max != null && min != null){ if (sort != 4 && (strVal[i - 3]!=null || !strVal[i - 3].equals(""))) { int t = ExcelUtil.getBgColor(Float.parseFloat(strVal[i - 3].replace("%", "")), max, min, sort); if(t == 0){ setStyle = greenStyle; }else if(t == 1){ setStyle = redStyle; } } } cell.setCellStyle(setStyle); } } /** * * @param workbook * @param sheet * @param rownum * 行数 * @param intVal * @param sort 越大越好 1越小越好(0、1最好最差都有) 2越大越差 3、越小越差 (2、3只有最差) 4不操作 */ private void setValues(XSSFSheet sheet, XSSFCellStyle style, XSSFCellStyle greenStyle, XSSFCellStyle redStyle, int rownum, Integer[] intVal, int sort,int num) { Integer max = null, min = null; // 填充背景颜色 if (intVal.length - num > 1) { max = ExcelUtil.getMax(intVal,num); min = ExcelUtil.getMin(intVal,num); } XSSFRow row = sheet.getRow(rownum); if (null == row) { row = sheet.createRow(rownum); } int len = intVal.length; for (int i = 3; i < len + 3; i++) { XSSFCell cell = row.getCell(i); if (null == cell) { cell = row.createCell(i); } if(intVal[i - 3]==null){ cell.setCellValue("-"); }else{ cell.setCellValue(intVal[i - 3]); } XSSFCellStyle setStyle = style; if(i < len + 3 - num && max != null && min != null){ if (sort != 4 && intVal[i - 3]!=null) { int t = ExcelUtil.getBgColor(Float.valueOf(intVal[i - 3]), Float.valueOf(max), Float.valueOf(min), sort); if(t == 0){ setStyle = greenStyle; }else if(t == 1){ setStyle = redStyle; } } } cell.setCellStyle(setStyle); } } /** * * @param workbook * @param sheet * @param rownum * 行数 * @param intVal * @param sort 越大越好 1越小越好(0、1最好最差都有) 2越大越差 3、越小越差 (2、3只有最差) 4不操作 */ private void setValues(XSSFSheet sheet, XSSFCellStyle style, XSSFCellStyle greenStyle, XSSFCellStyle redStyle, int rownum, Double[] intVal, int sort,int num) { Double max = null, min = null; // 填充背景颜色 if (intVal.length - num > 1) { max = ExcelUtil.getMax(intVal,num); min = ExcelUtil.getMin(intVal,num); } XSSFRow row = sheet.getRow(rownum); if (null == row) { row = sheet.createRow(rownum); } int len = intVal.length; for (int i = 3; i < len + 3; i++) { XSSFCell cell = row.getCell(i); if (null == cell) { cell = row.createCell(i); } if(intVal[i - 3]==null){ cell.setCellValue("-"); }else{ cell.setCellValue(intVal[i - 3]); } XSSFCellStyle setStyle = style; if(i < len + 3 - num && max != null && min != null){ if (sort != 4 && intVal[i - 3]!=null) { int t = ExcelUtil.getBgColor(intVal[i - 3], max, min, sort); if(t == 0){ setStyle = greenStyle; }else if(t == 1){ setStyle = redStyle; } } } cell.setCellStyle(setStyle); } } /** * 得到优良中差颜色 * * @return */ public List<RateColor> getColors() { return exportExcelDao.queryColors(); } /** * 拷贝模板到指定位子 * * @throws IOException */ public void copyFile(String inputpath, String outpath, String name) throws IOException { File path = new File(outpath); if (!path.exists() && !path.isDirectory()) { path.mkdirs(); } FileInputStream fis = null; FileOutputStream fos = null; fis = new FileInputStream(inputpath); fos = new FileOutputStream(outpath + name); IOUtils.copy(fis, fos); fos.flush(); fos.close(); } /** * 创建质量报表excel * @param ctx * @param type * @param starttime * @param endtime * @param areaids * @param filePath * @param name * @throws Exception */ public void writeQualExcel(WebApplicationContext ctx, int type, String starttime, String endtime, String areaids, String filePath, String name) throws Exception { String tempPath = filePath + Constant.CAS_TEMPLATE_PATH; filePath = filePath + Constant.CAS_REPORT_TEMPLATE_EXPORT_PATH; Map<String, Object> param = new LinkedHashMap<String, Object>(); param.put("type", type); param.put("starttime", starttime); param.put("endtime", endtime); Map<String,QualTopAndLast> map = statAndEvalReportService.getTopAndLast(ctx, param); QualTopAndLast top1 = map.get("top1"); QualTopAndLast top5 = map.get("top5"); // 模板名称 String fileName = ""; // 标题 String title = ""; String[] strarArr = null; String titleVal = ""; if (starttime != null && !"".equals(starttime) && endtime != null && !"".equals(endtime)) { strarArr = starttime.split("-"); } // 设置标题内容 if (type == 1) { if (strarArr != null && strarArr.length > 0) { titleVal = DateUtils.dateFormat(starttime); } fileName = "template_qual_day.xlsx"; title = "移动网络投诉处理质量日报 - (" + titleVal + ")"; } else if (type == 2) { if (strarArr != null && strarArr.length > 0) { titleVal = DateUtils.dateFormat(starttime) + "-" + DateUtils.dateFormat(endtime); } fileName = "template_qual_week.xlsx"; title = "移动网络投诉处理质量周报-(" + titleVal + ")"; } else { if (strarArr != null && strarArr.length > 0) { titleVal = strarArr[0] + "年" + strarArr[1] + "月"; } fileName = "template_qual_month.xlsx"; title = "移动网络投诉处理质量月报-(" + titleVal + ")"; } // 获取累计起始时间 String defDate = sysConfigDao.queryData(Constant.RP_QUALITY_CUMULATIVE_START_TIME); // 模板路径 String temp = tempPath + fileName; copyFile(temp, filePath, name); // 读取Excel FileInputStream file = new FileInputStream(filePath + name); XSSFWorkbook workbook = new XSSFWorkbook(file); // 第一个sheet XSSFSheet sheet = workbook.getSheetAt(0); param.put("area_id", areaids); //获取质量报表数据 QualtyReport qr = statAndEvalReportService.getQualityReportData(ctx, param); //获取数据的列数 int size = qr.getAreaid().length; // 设置标题 以及标题的下一行内容 setTitle(workbook, title, size + 3, defDate); // 设置标题 setTopVal(workbook, getContent(top1, type,0),4, size + 3,0); //设置top5 setTopVal(workbook, getContent(top5, type,1),1, 15,1); String green = "#00FF00", red = "#FF0000"; // 边框样式 XSSFCellStyle style = ExcelUtil.setBackColorByCustom(workbook, ""); XSSFCellStyle greenStyle = ExcelUtil.setBackColorByCustom(workbook, green); XSSFCellStyle redStyle = ExcelUtil.setBackColorByCustom(workbook, red); // 依次填充值 int count = 4; int groupnum = this.countGroup(); //设置区域分类 setGroupCell(workbook,sheet,count++,groupnum,qr.getAreaid(),qr.getAreaname()); // 区域名称 setValues(sheet, style,greenStyle,redStyle, count++, qr.getAreaname(), 4,groupnum); // 投诉处理质量综合评分 setValues(sheet, style,greenStyle,redStyle, count++, qr.getComp_score(), 4,groupnum); // 投诉处理质量综合排名 setValues(sheet, style,greenStyle,redStyle, count++, qr.getComp_score_rank(), 1,groupnum); // 移动网络服务考核得分 setValues(sheet, style,greenStyle,redStyle, count++, qr.getAssess_score(), 4,groupnum); // 累计需实测工单量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_workorder(), 4,groupnum); // 月需实测工单量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_workorder(), 4,groupnum); // 累计实测量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_test(), 4,groupnum); // 月实测量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_test(), 4,groupnum); // 累计实测率 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_test_rate(), 0,groupnum); if(type != 1){ // 月测试及时率 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_test_timely(), 4,groupnum); } // 累计网络投诉工单量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_serialno(), 4,groupnum); // 累计解决工单量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_solve(), 4,groupnum); // 累计解决率 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_solve_rate(), 0,groupnum); // 月网络投诉工单量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_serialno(), 4,groupnum); // 月解决工单量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_solve(), 4,groupnum); // 累计优化解决量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_major_solve(), 4,groupnum); // 累计优化解决比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_major_solve_rate(), 4,groupnum); // 月优化解决量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_major_solve(), 4,groupnum); // 月优化解决比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_major_solve_rate(), 4,groupnum); // 累计建设解决量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_build_solve(), 4,groupnum); // 累计建设解决比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_build_solve_rate(), 4,groupnum); // 月建设解决量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_build_solve(), 4,groupnum); // 月建设解决比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_build_solve_rate(), 4,groupnum); // 累计维护解决量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_maintain_solve(), 4,groupnum); // 累计维护解决比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_maintain_solve_rate(), 4,groupnum); // 月维护解决量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_maintain_solve(), 4,groupnum); // 月维护解决比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_maintain_solve_rate(), 4,groupnum); // 累计其它真正解决量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_other_solve(), 4,groupnum); // 累计其它真正解决比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_other_solve_rate(), 4,groupnum); // 月其它真正解决量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_other_solve(), 4,groupnum); // 月其它真正解决比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_other_solve_rate(), 4,groupnum); // 累计工单滞留量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_delay(), 4,groupnum); // 累计工单滞留率 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_delay_rate(), 1,groupnum); // 累计优化工单滞留量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_major_delay(), 4,groupnum); // 累计优化工单滞留比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_major_delay_rate(), 4,groupnum); // 累计建设工单滞留量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_build_delay(), 4,groupnum); // 累计建设工单滞留比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_build_delay_rate(), 4,groupnum); // 累计维护工单滞留量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_maintain_delay(), 4,groupnum); // 累计维护工单滞留比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_maintain_delay_rate(), 4,groupnum); // 累计工单驳回量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_reject(), 4,groupnum); // 月工单驳回量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_reject(), 4,groupnum); // 累计工单驳回率 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_reject_rate(), 2,groupnum); // 累计优化工单驳回量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_major_reject(), 4,groupnum); // 累计优化工单驳回比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_major_reject_rate(), 4,groupnum); // 月优化工单驳回量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_major_reject(), 4,groupnum); // 月优化工单驳回比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_major_reject_rate(), 4,groupnum); // 累计建设工单驳回量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_build_reject(), 4,groupnum); // 累计建设工单驳回比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_build_reject_rate(), 4,groupnum); // 月建设工单驳回量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_build_reject(), 4,groupnum); // 月建设工单驳回比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_build_reject_rate(), 4,groupnum); // 累计维护工单驳回量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_maintain_reject(), 4,groupnum); // 累计维护工单驳回比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_maintain_reject_rate(), 4,groupnum); // 月维护工单驳回量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_maintain_reject(), 4,groupnum); // 月维护工单驳回比 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_maintain_reject_rate(), 4,groupnum); // 累计工单超时量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_over(), 4,groupnum); // 月工单超时量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_over(), 4,groupnum); // 累计工单超时率 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_over_rate(), 2,groupnum); // 累计工单重派量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_send(), 4,groupnum); // 月工单重派量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_send(), 4,groupnum); // 累计工单重派率 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_send_rate(), 2,groupnum); // 累计工单重复投诉量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_complaint(), 4,groupnum); // 月工单重复投诉量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_complaint(), 4,groupnum); // 累计重复投诉率 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_complaint_rate(), 2,groupnum); // 累计工单升级量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_upgrade(), 4,groupnum); // 月工单升级量 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_upgrade(), 4,groupnum); // 累计工单升级率 setValues(sheet, style,greenStyle,redStyle, count++, qr.getTotal_upgrade_rate(), 2,groupnum); if(type !=1 ){ // 周3G综合改善评分 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_wcdma_impr(), 4,groupnum); // 周2G综合改善评分 setValues(sheet, style,greenStyle,redStyle, count++, qr.getCurr_gsm_impr(), 4,groupnum); // 周3G综合改善比例 setValues(sheet, style,greenStyle,redStyle, count++, qr.getRatio_wcdma_impr(), 4,groupnum); // 周2G综合改善比例 setValues(sheet, style,greenStyle,redStyle, count++, qr.getRatio_gsm_impr(), 4,groupnum); } FileOutputStream os = new FileOutputStream(filePath + name); workbook.write(os); os.flush(); os.close(); } /** * * @param workbook * @param sheet * @param rownum * @param groupnum * @param areaid * @param areaname */ private void setGroupCell(XSSFWorkbook workbook,XSSFSheet sheet,int rownum,int groupnum,Integer[] areaid,String[] areaname){ //样式 XSSFCellStyle style = workbook.createCellStyle(); //设置边框 style.setAlignment(XSSFCellStyle.ALIGN_CENTER); style.setBorderTop(XSSFCellStyle.BORDER_THIN); style.setBorderLeft(XSSFCellStyle.BORDER_THIN); style.setBorderBottom(XSSFCellStyle.BORDER_THIN); style.setBorderRight(XSSFCellStyle.BORDER_THIN); // 水平居中 style.setAlignment(XSSFCellStyle.ALIGN_CENTER_SELECTION); // 垂直居中 style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); List<Group> groups =this.getAreaInGroup(); XSSFRow row = sheet.getRow(rownum); int index = 3; if (null == row) { row = sheet.createRow(rownum); } Group group = null; int count = 0; for (int i = 0; i < groups.size(); i++) { group = groups.get(i); int num = 0; for (int j = 0; j < areaid.length; j++) { if(j < areaid.length - groupnum && group.getAreas() != null && group.getAreas().indexOf(areaid[j].toString()) >= 0){ num ++; } } if(num > 0){ sheet.addMergedRegion(new CellRangeAddress(rownum, rownum, count + index, count + num - 1 + index)); XSSFCell cell = row.getCell(count + index); if(null == cell){ cell = row.createCell(count + index); } cell.setCellValue(group.getGroupname()); cell.setCellStyle(style); } count += num; } if(count + groupnum != areaid.length){ sheet.addMergedRegion(new CellRangeAddress(rownum, rownum, count + index, areaid.length - groupnum + index - 1)); XSSFCell cell = row.getCell(count + index); if(null == cell){ cell = row.createCell(count + index); } cell.setCellValue("未归属区域"); cell.setCellStyle(style); } for (int i = areaname.length - groupnum; i < areaname.length; i++) { sheet.addMergedRegion(new CellRangeAddress(rownum, rownum + 1, i + index, i + index)); XSSFCell cell = row.getCell(i + index); if(null == cell){ cell = row.createCell(i + index); } cell.setCellValue(areaname[i]); cell.setCellStyle(style); } } private String getContent(QualTopAndLast top,int type,int issort){ String content = "投诉处理质量综合评分最高|" + top.getComp_score_max() + "," + "最低|" + top.getComp_score_min() + ";" +"累计实测率最高|" + top.getTotal_max_rate() + "," + "最低|" + top.getTotal_min_rate() + ";" + "累计真正解决率最高|" + top.getTotal_solve_rate_max() + "," + "最低|" + top.getTotal_solve_rate_min() + ";" + "累计工单滞留率最低|" + sortDesc(top.getTotal_delay_rate_min(),issort) + "," + "最高|" + top.getTotal_delay_rate_max() + ";" + "累计工单驳回率最低|" + sortDesc(top.getTotal_reject_rate_min(),issort) + "," + "最高|" + top.getTotal_reject_rate_max() + ";" + "累计工单超时率最低|" + sortDesc(top.getTotal_over_rate_min(),issort) + "," + "最高|" + top.getTotal_over_rate_max() + ";" + "累计工单重派率最低|" + sortDesc(top.getTotal_send_rate_min(),issort) + "," + "最高|" + top.getTotal_send_rate_max() + ";" + "累计工单重复投诉率最低|" + sortDesc(top.getTotal_complaint_rate_min(),issort) + "," + "最高|" + top.getTotal_complaint_rate_max() + ";" + "累计工单升级率最低|" + sortDesc(top.getTotal_upgrade_rate_min(),issort) + "," + "最高|" + top.getTotal_upgrade_rate_max() + "。"; if(type == 2){ content = content.replace("。", ";") + "周测试及时率最高|" + top.getCurr_test_timely_max() + "," + "最低|" + top.getCurr_test_timely_min() + "。"; }else if(type == 3){ content = content.replace("。", ";") + "月测试及时率最高|" + top.getCurr_test_timely_max() + "," + "最低|" + top.getCurr_test_timely_min() + "。"; } return content.replaceAll("null", "无"); } /** * * @param kpi * @param type * @return */ private String sortDesc(String kpi,int issort){ String str = ""; if(issort == 1){ if(!"".equals(kpi)){ String[] arr = kpi.split("、"); for(int i = arr.length - 1; i >= 0; i --){ str += arr[i] + "、"; } if(!"".equals(str)){ str = str.substring(0, str.length() - 1); } } }else{ str = kpi; } return str; } /** * 查询分公司数量 * @return */ public int countGroup(){ return exportExcelDao.countGroupNum() + 1; } public List<Group> getAreaInGroup(){ return exportExcelDao.queryAreaInGroup(); } /** * 根据区间时间导出实测量 * @param area_id * @param starttime * @param endtime * @param type 报表类型 1-测试报告 2-质量报告 * @param islei 是否累计 1-累计 2-非累计 * @param groupId组ID ,-1为全网 * @return */ public Map<String,String> excelSerialno(String area_id,String groupid,String starttime, String endtime,String systime,Integer type,Integer islei,String filePath){ Map<String, String> rpt = new HashMap<String, String>(); rpt.put("sucFlag", "成功"); rpt.put("testType", islei.toString()); rpt.put("reportType", type.toString()); String path=""; try { String key=""; if(type==1) key="reportdate"; if(type==2) key="rp_quality_cumulative_start_time"; //String systime=exportExcelDao.queryDefDate(key); Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("area_id", area_id); map.put("groupid", groupid); map.put("endtime", endtime); map.put("reportType", type); if(islei==1){ map.put("starttime", systime); }else{ map.put("starttime", starttime); } map.put("systime", systime); List<WorkOrder> list=this.exportExcelDao.excelSerialno(map); //创建excel准备 //文件夹路径 String fp =filePath+Constant.CAS_REPORT_TEMPLATE_EXPORT_PATH; //生成文件名称 path =String.valueOf(System.currentTimeMillis())+(int)(Math.random()*99999); //生成的excel路径 String excelPath=fp+path+".xlsx"; //生成excel //列标题 String[] colTitles = new String[]{"工单号","投诉时间","要求回复时间","投诉地址","投诉电话","投诉网络"}; //取值方法名 String[] methodNames = new String[]{"getSerialno","getSubmitDatetime","getRequestDatetime","getProblemsAddress","getAcceptanceNumber","getNetWorktype"}; SXSSFWorkbook wbk= new SXSSFWorkbook(); Sheet sheet = wbk.createSheet("report"); CellStyle style = getStyle(wbk); //设置表标题 Row row =sheet.createRow(0); for(int i=0;i<colTitles.length;i++){ Cell cell = row.createCell(i); cell.setCellStyle(style); cell.setCellValue(colTitles[i]); } //填充数据 for(int k=0;k<list.size();k++){ WorkOrder wo = list.get(k); Row r =sheet.createRow(k+1); for(int z=0;z<colTitles.length;z++){ Cell c = r.createCell(z); c.setCellStyle(style); if(methodNames[z].equals("getSubmitDatetime")||methodNames[z].equals("getRequestDatetime")){ //处理时间字段 Date d = (Date)ReflectUtil.invokeMethodName(methodNames[z], wo, null); if(d!=null){ c.setCellValue(DateUtils.date2Str(d, "yyyy.MM.dd HH:mm:ss")); } }else{ Object obj = ReflectUtil.invokeMethodName(methodNames[z], wo, null); if(obj!=null){ c.setCellValue(obj.toString()); } } } } //自适应单元格宽度 for(int i=0;i<colTitles.length&&list.size()>0;i++){ if(i!=3&&i!=5){ sheet.autoSizeColumn(i); } } //判断文件夹路径是否存在 File file =new File(fp); //如果文件夹不存在则创建 if (!file .exists() && !file .isDirectory()) { file .mkdirs(); } FileOutputStream out = new FileOutputStream(excelPath); wbk.write(out); out.close(); } catch (Exception e) { e.printStackTrace(); rpt.put("sucFlag", "失败"); } rpt.put("fname", path); return rpt; } /** * 一般样式 */ public CellStyle getStyle(SXSSFWorkbook xwb){ CellStyle style = xwb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中 return style; } } <file_sep>/src/main/java/com/complaint/model/Tolerante.java package com.complaint.model; public class Tolerante { private Integer tolerid; private String serialno; private Integer areaId; private Integer userId; public Integer getTolerid() { return tolerid; } public void setTolerid(Integer tolerid) { this.tolerid = tolerid; } public String getSerialno() { return serialno; } public void setSerialno(String serialno) { this.serialno = serialno; } public Integer getAreaId() { return areaId; } public void setAreaId(Integer areaId) { this.areaId = areaId; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } } <file_sep>/src/main/webapp/js/circleEle_bak.js function MyCircle(data,count,isshow,name,scale,step,id,type,isclick,paper,r,left,top){ var circle = new Object; circle.data = data; circle.count = count; circle.isshow = isshow; circle.name = name; circle.scale = scale; circle.step = step; circle.set = paper.set(); circle.id = id; circle.type = type; circle.left = left; circle.top = top; for(var i = 0;i<circle.data.length;i++){ var cir = paper.circle(circle.data[i].x * circle.scale+100+left, circle.data[i].y+100+top+(circle.count*10) * circle.scale, r).attr({fill:circle.data[i].color,title:name+':'+circle.data[i].va}).data("id", circle.data[i].id).data("type",circle.data[i].type).mousedown( function () { this.animate({r: r * 2}, 1); if(isclick){ $.ajax({ type:"post", url:contextPath+"/report/wcdmaOrGsm", data:({id :this.data("id"),type:this.data("type")}), success:function(data){ $('#div_page').html(data.content); $('#div_page_max').html(data.contentMax); } }); } }).mouseup(function(){ this.animate({r: r}, 1000); }); circle.set.push(cir); if(isclick){ if( circle.data[i].id == circle.id && circle.data[i].type == circle.type){ cir.attr("stroke", "#fe9a10"); } } } var onstart = function (event) { circle.set.forEach(function(_me){ _me.ox = _me.attr('cx'); _me.oy = _me.attr('cy'); }); }; var onmove = function (dx, dy) { circle.set.forEach(function(_me){ _me.attr({cx : parseInt(_me.ox + dx),cy : parseInt(_me.oy + dy)}); }); }; var onend = function () { circle.set.forEach(function(_me){ _me.ox = _me.attr('cx'); _me.oy = _me.attr('cy'); _me.animate({r: r}, 1); }); }; circle.set.drag(onmove,onstart,onend); if(isshow){ circle.set.show(); }else{ circle.set.hide(); } circle.hidden = function(){ circle.set.hide(); }; circle.getName = function(){ return circle.name; }; circle.show = function(){ circle.set.show(); }; circle.setIsShow = function(sh){ circle.isshow = sh; }; circle.setOxy = function(){ circle.set.forEach(function(_me){ _me.ox = _me.attr('cx'); _me.oy = _me.attr('cy'); }); }; circle.setR = function(r){ circle.set.attr({'r':r}); }; circle.setCxy = function(){ circle.set.forEach(function(_me){ _me.ox = _me.attr('cx'); _me.oy = _me.attr('cy'); _me.attr({cx : parseInt(_me.ox),cy : parseInt(_me.oy)}); }); }; circle.setOCxy = function(){ circle.setCxy(); circle.setOxy(); }; circle.changeCxy = function(left,ow,nw,islarge){ circle.set.forEach(function(_me){ _me.ox = _me.attr('cx'); _me.oy = _me.attr('cy'); _me.attr({cx : parseInt((_me.ox-Math.abs(left))*nw/ow+Math.abs(left)),cy : parseInt(_me.oy)}); _me.ox = _me.attr('cx'); _me.oy = _me.attr('cy'); }); } circle.cxyExpand = function(scale,step){ circle.scale = scale; circle.step = step; circle.set.forEach(function(_me){ if(_me.ox == undefined && _me.oy == undefined){ _me.ox = _me.attr('cx'); _me.oy = _me.attr('cy'); } if(_me.ox == _me.attr('cx') && _me.oy == _me.attr('cy')){ _me.ox = _me.ox/(circle.scale - circle.step); _me.oy = _me.oy/(circle.scale - circle.step); } _me.attr({cx: parseInt(_me.ox * circle.scale),cy: parseInt(_me.oy * circle.scale)}); }); }; circle.cxyNarrow = function(scale,step){ circle.scale = scale; circle.step = step; circle.set.forEach(function(_me){ if(_me.ox == undefined && _me.oy == undefined){ _me.ox = _me.attr('cx'); _me.oy = _me.attr('cy'); } if(_me.ox == _me.attr('cx') && _me.oy == _me.attr('cy')){ _me.ox = _me.ox/(circle.scale + circle.step); _me.oy = _me.oy/(circle.scale + circle.step); } _me.attr({cx: parseInt((_me.attr('cx') * circle.scale)/(circle.scale + circle.step)),cy: parseInt((_me.attr('cy') * circle.scale)/(circle.scale + circle.step))}); }); }; return circle; } <file_sep>/src/main/webapp/js/teamgroup/teamgroup.js //保存点击的名称 var _clicktype = null; $(function(){ //var optInit = {callback:function(page_index,jq){ $.ajax({ type:"post", url: contextPath + "/teamgroup/teamgroup/template", data:({name: $("#hiddenval").val()}), success: function(data){ $("#content").html(data); } }); //} //}; //$("#pager").pagination(pageTotal, optInit);//回调 /** *模糊查询 */ $("#search").click(function(){ var nameval = $.trim($("#name").val()); $("#hiddenval").val(nameval); $("#name").val(nameval); $("#searchForm").submit(); }); //点击编辑按钮 $(".editgroup").click(function(){ $("#managerdlg").dialog({ href : contextPath + "/teamgroup/teammanager?type=4", height : 478, width : 668, title : "编辑", modal : true, closed : false, onClose:function(){ window.location.href = window.location.href; } }); $('#managerdlg').dialog('open'); $.parser.parse('#managerdlg'); }); var saveCount = 0; // 编辑页面确定单击事件 $('.btn_save').die().live('click',function(){ if(saveCount == 0){ saveCount ++; var _val = $('.con-tk-left-now').attr('val'); var type = -1; if(_val == 'bigs_smalls'){ type = 4; }else if(_val == 'smalls_personnels'){ type = 5; }else if(_val == 'personnels_areas'){ type = 6; }else if(_val == 'big_leader'){ type = 7; }else if(_val == 'small_leader'){ type = 8; } if(type != -1){ var groups = new Array(); _clicktype.find('.select').each(function(){ var obj = {}; obj['id'] = $(this).attr('val'); obj['list'] = []; $(this).find('li').each(function(){ obj['list'].push($(this).attr('val')); }); groups.push(obj); }); $.ajax({ type:'post', url:contextPath + '/teamgroup/updatelist', data:{groups : JSON.stringify(groups),type:type}, dataType:"json", success:function(data){ if(data.msg == 1){ $.messager.alert('提示','操作成功','success',function(){ $('#managerdlg').dialog('refresh',contextPath + '/teamgroup/teammanager?type='+type); }); }else{ $.messager.alert('提示','操作失败!','error'); } saveCount = 0; } }); }else{ $('#managerdlg').dialog('close'); window.location.href = window.location.href; } } }); //名称点击事件 $('#typename').find('li').die().live('click',function(){ $('.con-tk-left-now').removeClass('con-tk-left-now'); $(this).addClass('con-tk-left-now'); $('.configure').hide(); _clicktype = $('.' +$(this).attr('val')); _clicktype.show(); }); // 类别点击事件 $('.configure-family').find('li').die().live('click', function() { if (!$(this).hasClass('now')) { _clicktype.find(".right_btn").find('img').attr('src', '../images/configure-01b.png'); _clicktype.find(".right_btn").attr('val', 0); _clicktype.find(".left_btn").find('img').attr('src', '../images/configureb.png'); _clicktype.find(".left_btn").attr('val', 0); _clicktype.find('.select').find('li').removeClass('areanow'); _clicktype.find('.unselect').find('li').removeClass('areanow'); _clicktype.find('.configure-family').find('li').removeClass('now'); $(this).addClass('now'); // 隐藏已归属的区域 _clicktype.find('.select').hide(); var id = $(this).attr('val'); // 显示当前已归属的区域 _clicktype.find('#select_' + id).show(); //小组、大组组长配置处理 var _val = $('.con-tk-left-now').attr('val'); if(_val == 'big_leader' || _val == 'small_leader'){ _clicktype.find('.unselect').hide(); _clicktype.find('#unselect_' + id).show(); } } }); var rightFn = null; var leftFn = null; // 已归属区域点击事件 $('.select').find('li').die().live('click', function() { // 取消上次延时未执行的方法 clearTimeout(rightFn); var _this = $(this); rightFn = setTimeout(function() { _clicktype.find(".right_btn").find('img').attr('src', '../images/configure-01.png'); _clicktype.find(".right_btn").attr('val', 1); _clicktype.find('.select').find('li').removeClass('areanow'); _this.addClass('areanow'); }, 300); }); // 已归属区域双击击事件 $('.select').find('li').live('dblclick', function() { // 取消上次延时未执行的方法 clearTimeout(rightFn); _clicktype.find(".right_btn").find('img').attr('src', '../images/configure-01b.png'); _clicktype.find(".right_btn").attr('val', 0); _clicktype.find('.select').find('li').removeClass('areanow'); _clicktype.find('.unselect').append($(this)); }); // 未归属区域点击事件 $('.unselect').find('li').live('click', function() { // 取消上次延时未执行的方法 clearTimeout(leftFn); var _this = $(this); leftFn = setTimeout(function() { var groupid = _clicktype.find(".now").attr('val'); var len = _clicktype.find('#select_' + groupid).find('li').length; var val = $('.con-tk-left-now').attr('val'); if((val != 'big_leader' && val != 'small_leader') || ((val == 'big_leader' || val == 'small_leader') && len == 0)){ _clicktype.find(".left_btn").find('img').attr('src', '../images/configure.png'); _clicktype.find(".left_btn").attr('val', 1); //$('#areas_' + groupid).append($(this)); _clicktype.find('.unselect').find('li').removeClass('areanow'); _this.addClass('areanow'); } }, 300); }); // 未归属区域双击击事件 $('.unselect').find('li').live('dblclick', function() { // 取消上次延时未执行的方法 clearTimeout(leftFn); var groupid = _clicktype.find(".now").attr('val'); var len = _clicktype.find('#select_' + groupid).find('li').length; var val = $('.con-tk-left-now').attr('val'); if((val != 'big_leader' && val != 'small_leader') || ((val == 'big_leader' || val == 'small_leader') && len == 0)){ _clicktype.find('.unselect').find('li').removeClass('areanow'); _clicktype.find(".left_btn").find('img').attr('src', '../images/configureb.png'); _clicktype.find(".left_btn").attr('val', 0); _clicktype.find('#select_' + groupid).append($(this)); } }); // 点击右移 $('.right_btn').die().live('click', function() { if ($(this).attr('val') == '1') { $(this).find('img').attr('src', '../images/configure-01b.png'); // 得到当前选中区域 var _areanow = _clicktype.find('.select').find('.areanow'); _areanow.removeClass('areanow'); _clicktype.find('.unselect').append(_areanow); // _areanow.remove(); $(this).attr('val', 0); } }); // 点击左移 $('.left_btn').die().live('click', function() { var groupid = _clicktype.find(".now").attr('val'); var len = _clicktype.find('#select_' + groupid).find('li').length; var val = $('.con-tk-left-now').attr('val'); if((val != 'big_leader' && val != 'small_leader') || ((val == 'big_leader' || val == 'small_leader') && len == 0)){ if ($(this).attr('val') == '1') { $(this).find('img').attr('src', '../images/configureb.png'); $(this).attr('val', 0); // 得到当前选中区域 var _this = _clicktype.find('.unselect').find('.areanow');; _this.removeClass('areanow'); //var groupid = _clicktype.find(".now").attr('val'); _clicktype.find('#select_' + groupid).append(_this); } } }); //新增 点击事件 $('.addTeam').die().live('click',function(){ var val = $('.con-tk-left-now').attr('val'); var url = ''; var title = ''; var width = 435; var height = 130; if(val == 'bigs'){ url = contextPath + '/teamgroup/addteam?type=1'; title = '添加大组'; }else if(val == 'smalls'){ url = contextPath + '/teamgroup/addteam?type=2'; title = '添加小组'; }else{ url = contextPath + '/teamgroup/addteam?type=3'; title = '添加人员'; height = 160; } $("#adddlg").dialog({ href : url, height : height, width : width, title : title, modal : true, closed : false }); $('#adddlg').dialog('open'); $.parser.parse('#adddlg'); }); var addCount = 0; // 新增的确定事件 $('.addGroup_btn').die().live('click',function(){ if (addCount == 0) { addCount++; $('#addForm').ajaxForm({ url : contextPath + '/teamgroup/add', beforeSubmit : function() { if (!$('#addForm').form('validate')) { addCount = 0; return false; } else { return true; } }, success : function(data) { if (data.msg == 1) { $.messager.alert("提示", "操作成功!", "success", function() { // 刷新 $('#managerdlg').dialog('refresh',contextPath + '/teamgroup/teammanager?type='+data.type); $('#adddlg').dialog('close'); }); }else{ $.messager.alert("提示", "操作失败!", "error"); } addCount = 0; } }); $('#addForm').submit(); } }); // 点击编辑 $('.editTeam').die().live('click',function(){ var _chk = _clicktype.find("input[name='chk']:checked"); var len = _chk.length; if(len > 0){ var content = '<form method="post" id="updateForm"><ul class="form">'; for(var i=0;i<len;i++){ var groupname = $(_chk[i]).attr('groupname'); var groupid = $(_chk[i]).val(); if($('.con-tk-left-now').attr('val') == 'personnels'){ var phone = $(_chk[i]).attr('phone'); content +='<li><span style="text-align:left;"><samp style="color:red">*</samp>'+$('.con-tk-left-now').html()+'名称:</span><p>' + '<input name="groupname" type="text" groupid="'+groupid+'" value="' + groupname + '" class="flpi easyui-validatebox" ' + ' data-options="required:true,validType:[\'ench\',\'lengthb[4,20]\']"/>' + '</p></li>'; content +='<li><span style="text-align:left;"><samp style="color:red">*</samp>电话:</span><p>' + '<input name="phone" type="text" id="phone" value="'+phone+'" class="easyui-validatebox flpi" data-options="required:true,validType:[\'phone\']"/>' + '</p></li>'; }else{ content +='<li><span style="text-align:left;"><samp style="color:red">*</samp>'+$('.con-tk-left-now').html()+'名称:</span><p>' + '<input name="groupname" type="text" groupid="'+groupid+'" value="' + groupname + '" class="flpi easyui-validatebox" ' + ' data-options="required:true,validType:[\'ench\',\'lengthb[4,20]\',\'remote[\\\''+contextPath+'/teamgroup/isExsit\\\',\\\'groupname\\\',\\\''+groupname+'\\\',\\\''+$('.con-tk-left-now').html()+'名称\\\']\']"/>' + '</p></li>'; } } content += '</ul></from>'; var width = 435; var height = 300; if($('.con-tk-left-now').attr('val') == 'personnels'){ if(len >= 3){ height = 300; }else{ height = len * 33 * 2 + 100; } }else{ if(len >= 6){ height = 300; }else{ height = len * 33 + 100; } } $("#editdlg").dialog({ height : height, width : width, content:content, title : "编辑", modal : true, closed : false }); $('#editdlg').dialog('open'); $.parser.parse('#editdlg'); }else{ $.messager.alert("提示","请选择你要编辑的"+$('.con-tk-left-now').html()+"!","warning"); } }); var updateCount = 0; // 编辑的确定单击事件 $(".editGroup_btn").die().live('click',function(){ if (updateCount == 0) { updateCount++; var val = $('.con-tk-left-now').attr('val'); if(val == 'bigs'){ type = 1; }else if(val == 'smalls'){ type = 2; }else{ type = 3; } if (!$('#updateForm').form('validate')) { updateCount = 0; return false; } var groups = new Array(); var _name = $('#updateForm').find('input[name=groupname]'); var _phone = $('#updateForm').find('input[name=phone]'); //判断大组小组是否重复 if(type == 1 || type == 2){ for(var i = 0; i < _name.length; i ++){ var val_i = $( _name[i]).val(); var count = 0; for(var j = 0; j < _name.length; j ++){ var val_j = $(_name[j]).val(); if(val_i == val_j){ count++; if(count >= 2){ $.messager.alert("提示",(type == 1?"大组":"小组") + "名称不能相同!","warning"); updateCount = 0; return; } } } } } //封装数据 for(var i = 0; i < _name.length; i++){ var obj = {}; obj["groupid"] = $(_name[i]).attr('groupid'); obj["groupname"] =$( _name[i]).val(); // 判断是否是修改人员 if( type == 3){ obj["phone"] = $(_phone[i]).val(); } groups.push(obj); } $.ajax({ type:'post', url:contextPath + '/teamgroup/update', data:{groups : JSON.stringify(groups),type:type}, success:function(data){ if(data.msg == 1){ $.messager.alert('提示','操作成功!','success',function(){ $('#editdlg').dialog('close'); $('#managerdlg').dialog('refresh',contextPath + '/teamgroup/teammanager?type='+data.type); }); }else{ $.messager.alert('提示','操作失败!','error'); } updateCount = 0; } }); } }); // 删除 $('.deleteTeam').die().live('click',function(){ var str=""; var val = $('.con-tk-left-now').attr('val'); var type; if(val == 'bigs'){ type = 1; }else if(val == 'smalls'){ type = 2; }else{ type = 3; } _clicktype.find("input[name='chk']:checked").each(function(){ str+=$(this).val()+","; }); if(str != "" && str.length > 1){ str = str.substring(0, str.length-1); deleteTeam(str,type); }else{ $.messager.alert("提示","请选择你要删除的"+$('.con-tk-left-now').html()+"!","warning"); } }); }); function deleteTeam(ids,type){ $.messager.confirm('提示', '是否删除你选择的'+$('.con-tk-left-now').html()+'?', function(r){ if (r){ $.ajax({ type:'post', url:contextPath + '/teamgroup/delete', data:({ids : ids,type:type}), success:function(data){ if(data.msg == 1){ $.messager.alert('提示','删除成功!','success',function(){ $('#managerdlg').dialog('refresh',contextPath + '/teamgroup/teammanager?type='+data.type); }); }else{ $.messager.alert('提示','删除失败!','error'); } } }); } }); } <file_sep>/src/main/java/com/complaint/service/TaskConfigService.java package com.complaint.service; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.complaint.dao.BaseDao; import com.complaint.dao.TaskConfigDao; import com.complaint.model.AreaBean; import com.complaint.model.TaskOrder; import com.complaint.model.User; import com.complaint.page.PageBean; import com.complaint.utils.SecretUtil; @Service("taskConfigService") public class TaskConfigService { @Autowired private TaskConfigDao taskConfigDao; @Autowired private BaseDao baseDao; public PageBean countTask(String val ,Integer isverify ,Integer validstate ,Integer timeType , int pageIndex, int pageSize ,int userid){ Map<String, Object> param = new HashMap<String, Object>(); param.put("val", val); param.put("validstate", validstate); param.put("isverify", isverify); Map<String ,String> map = this.getTime(timeType); param.put("endTime", map.get("endTime")); param.put("startTime", map.get("startTime")); param.put("userid", userid); PageBean pb = new PageBean(); int count = this.taskConfigDao.countTask(param); pb.setPageIndex(pageIndex); pb.setPageSize(pageSize); pb.setTotalPage(count); return pb; } public PageBean getTaskList(String val ,Integer isverify ,Integer validstate ,Integer timeType , int pageIndex, int pageSize ,int userid){ int lbound = (pageIndex - 1) * pageSize; int mbound = pageIndex * pageSize; Map<String, Object> param = new HashMap<String, Object>(); param.put("val", val); param.put("validstate", validstate); param.put("isverify", isverify); Map<String ,String> map = this.getTime(timeType); param.put("endTime", map.get("endTime")); param.put("startTime", map.get("startTime")); param.put("lbound", lbound); param.put("mbound", mbound); param.put("userid", userid); PageBean pb = new PageBean(); List<TaskOrder> list = this.taskConfigDao.queryList(param); pb.setList(list); return pb; } /** * 获取用户对应区域 */ public List<AreaBean> getAreaList(Integer userid){ List<AreaBean> areas = new ArrayList<AreaBean>(); areas = this.taskConfigDao.getAreaList(userid); return areas; } /** * 保存新增工单 * @param areaid * @param net_type * @param break_flag * @param test_address * @throws Exception */ @Transactional(rollbackFor=Exception.class) public void saveAdd(Integer[] areaid, Integer[] nettype,Integer[] breakflag ,String [] testaddress,User user) throws Exception{ List<TaskOrder> list = new ArrayList<TaskOrder>(); TaskOrder to = null; //工单集合防止工单重复 List<String> serialnos = new ArrayList<String>(); for(int i = 0;i<areaid.length;i++){ //获取工单 String sb = nosame(serialnos); serialnos.add(sb); to = new TaskOrder(); to.setAreaid(areaid[i]); to.setBreakflag(breakflag[i]); //to.setCreate_date(); to.setHandler(user.getUserid()); to.setIsverify(0);//默认为0未审核 to.setValidstate(0);//默认为0有效状态 to.setNetworktype(getNetworktype(nettype[i])); //to.setNum(); to.setId(sb.toString()); to.setSerialno(sb.toString()); to.setTest_address(testaddress[i]); list.add(to); } this.baseDao.batchInsert(TaskConfigDao.class, list, 200); } public String getNetworktype(Integer i){ String nwt =""; switch (i) { case 1: nwt = "2g数据"; break; case 2: nwt = "2g语音"; break; case 3: nwt = "3g数据"; break; case 4: nwt = "3g语音"; break; default: nwt = "未知"; break; } return nwt; } /** * 预防重复工单 * @throws NoSuchAlgorithmException */ public String nosame(List<String> serialnos) throws NoSuchAlgorithmException{ boolean flag = false; String sb = null; do{ flag = false; sb = getSerialno(); if(serialnos.size()>0){ for(String serialno:serialnos){ if(sb.equals(serialno)){ flag = true; } } } }while(flag); return sb; } /** * 生成工单 * @return * @throws NoSuchAlgorithmException */ public String getSerialno() throws NoSuchAlgorithmException{ Date date = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); UUID uuid = UUID.randomUUID(); String md = getMD5(uuid.toString()); String str = df.format(date); StringBuilder sb = new StringBuilder(); sb.append(str); sb.append(md.toUpperCase()); /*Random random = new Random(); for(int i=0;i<20-str.length();i++){ sb.append(random.nextInt(10)); }*/ return sb.toString(); } /** * 生成16位MD5 * @param id * @return * @throws NoSuchAlgorithmException */ public String getMD5(String str) throws NoSuchAlgorithmException{ MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte b[] = md.digest(); int i =0; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if(i<0) i+= 256; if(i<16) buf.append("0"); buf.append(Integer.toHexString(i)); } return buf.toString().substring(8,24);//16位的加密 } public TaskOrder getSerialnoInfo(String id){ TaskOrder to = this.taskConfigDao.querySerialno(id); return to; } /** * 修改工单 * @param to */ @Transactional(rollbackFor=Exception.class) public void saveUpdate(TaskOrder to){ this.taskConfigDao.updateSerialno(to); } /** * 根据时间类型获取时间 * @param timeType * @return */ public Map<String ,String> getTime(Integer timeType){ Map<String ,String> map = new HashMap<String ,String>(); SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd 23:59:59"); SimpleDateFormat sf2=new SimpleDateFormat("yyyy-MM-dd 00:00:00"); Date endtime = new Date(); map.put("endTime", sf.format(endtime)); if(timeType==null ||"".equals(timeType)){ map.put("startTime", ""); }else if(timeType == 1){//7天 Calendar calendar=Calendar.getInstance(); calendar.setTime(endtime); calendar.add(Calendar.DATE,-6); Date starttime=calendar.getTime(); map.put("startTime", sf2.format(starttime)); }else if(timeType == 2){//1个月 Calendar calendar=Calendar.getInstance(); calendar.setTime(endtime); calendar.add(Calendar.DATE,-29); Date starttime=calendar.getTime(); map.put("startTime", sf2.format(starttime)); }else if(timeType == 3){//3个月 Calendar calendar=Calendar.getInstance(); calendar.setTime(endtime); calendar.add(Calendar.DATE,-89); Date starttime=calendar.getTime(); map.put("startTime", sf2.format(starttime)); }else if(timeType == -1){ map.put("startTime", ""); }else{ map.put("startTime", ""); } return map; } @Transactional(rollbackFor=Exception.class) public void setValidstate(TaskOrder to)throws Exception{ this.taskConfigDao.setValidstate(to); } } <file_sep>/src/main/webapp/js/reportIndependent/graphicEle.js /** * 图形 * @param data * @param count * @param isshow 是否显示 * @param name * @param scale 比例 1为100% * @param step 每次缩放比例 * @param id * @param type * @param isclick * @param paper * @param r * @returns {___graphic0} */ function MyGraphic(data,count,isshow,name,scale,step,id,type,id_last,type_last,isclick,paper,r,left,top,compare){ var graphic = new Object; graphic.data = data; graphic.count = count; graphic.isshow = isshow; graphic.name = name; graphic.scale = scale; graphic.step = step; graphic.set = paper.set(); graphic.id = id; graphic.type = type; graphic.id_last = id_last; graphic.type_last = type_last; //graphic.offset =70 var startIndex=0,endIndex=0; var startX=0,startY=0,startIntevl=0; var endX=0,endY=0,endIntevl=0; for(var i = 0;i<graphic.data.length;i++){ var x = graphic.data[i].x * graphic.scale+left+(left/40)*(count-1); var y = graphic.data[i].y* graphic.scale +top; var gra = null; if(graphic.data[i].reltype == -1){ //画菱形 var rhopath = [["M", x, y-r], ["L", x+r, y], ["L", x, y+r],["L",x-r,y], ["Z"]]; gra = paper.path(rhopath); gra.attr({fill:'black'}); gra.attr({stroke:'black'}); }else{ if(graphic.data[i].type == 1){ //画三角形 var tripath = [["M", x-r, y-Math.sqrt(3)/2*r],["L", x+r, y-Math.sqrt(3)/2*r] ,["L", x, y+Math.sqrt(3)/2*r] , ["Z"]]; gra = paper.path(tripath); }else{ //画圆 gra = paper.circle(x, y, r); } gra.attr({fill:graphic.data[i].color}); gra.attr({stroke:graphic.data[i].color}); } var intevl=":"+graphic.data[i].va; if(data[i].reltype==-1){ intevl=""; } if(isclick){ if( graphic.data[i].id == graphic.id && graphic.data[i].type == graphic.type){ //给起点加上外圈 gra.attr("stroke", "red"); //获取起点下标 startIndex=i; //获取起点的x和y坐标 startX =x; startY =y; //获取起点的提示值 startIntevl =intevl; } if( graphic.data[i].id == graphic.id_last && graphic.data[i].type == graphic.type_last){ //给终点加上外圈 gra.attr("stroke", "red"); //获取终点的下标 endIndex=i; //获取终点的想x和y坐标 endX =x; endY =y; //获取终点的提示值 endIntevl =intevl; } } if(i == graphic.data.length-1 && compare!=1){ //画起点箭头 var rhopath = [["M", startX-r, startY], ["L", startX - (10+r) * Math.sin(2 * Math.PI / 360 * 60), startY-5], ["L", startX - (10+r) * Math.sin(2 * Math.PI / 360 * 60), startY-1], ["L", startX - (2+r) * Math.sin(2 * Math.PI / 360 * 60)-25,startY-1], ["L", startX - (2+r) * Math.sin(2 * Math.PI / 360 * 60)-25,startY+1], ["L", startX - (10+r) * Math.sin(2 * Math.PI / 360 * 60), startY+1], ["L", startX - (10+r) * Math.sin(2 * Math.PI / 360 * 60), startY+5], ["Z"] ]; var g1= paper.path(rhopath).attr({fill: "red", stroke: "none"}); //帮点start的拖拽事件 g1.attr({title:name+startIntevl}).data("reltype",data[i].reltype).data("odx",0).data("ody",0).data("mx",0).data("my",0).data("cmx",0).data("cmy",0).data("s",1).data("c",0) .data("id", graphic.data[i].id).data("type",graphic.data[i].type) //放大缩小点之间距离设定 .data("index",graphic.data[startIndex].x+":"+graphic.data[startIndex].y).mouseup(function(){ var tran = "t"+this.data("mx")+","+this.data("my"); this.transform(tran+"s1"); this.data("s",1); }); //将生成信息放入点集合中 graphic.set.push(g1); //标出起点提示语 var g2= paper.text(startX-45,startY+2,"Start"); g2.attr({stroke:"red"}); //帮点箭头的拖拽事件 g2.attr({title:name+startIntevl}).data("reltype",data[i].reltype).data("odx",0).data("ody",0).data("mx",0).data("my",0).data("cmx",0).data("cmy",0).data("s",1).data("c",0) .data("id", graphic.data[i].id).data("type",graphic.data[i].type) //放大缩小点之间距离设定 .data("index",graphic.data[startIndex].x+":"+graphic.data[startIndex].y).mouseup(function(){ var tran = "t"+this.data("mx")+","+this.data("my"); this.transform(tran+"s1"); this.data("s",1); }); //将生成图形放入点集合中 graphic.set.push(g2); } if(i == graphic.data.length-1 && compare!=1){ //画终点箭头 var rhopath = [["M", endX-r, endY], ["L", endX - (10+r) * Math.sin(2 * Math.PI / 360 * 60), endY-5], ["L", endX - (10+r) * Math.sin(2 * Math.PI / 360 * 60), endY-1], ["L", endX - (2+r) * Math.sin(2 * Math.PI / 360 * 60)-25,endY-1], ["L", endX - (2+r) * Math.sin(2 * Math.PI / 360 * 60)-25,endY+1], ["L", endX - (10+r) * Math.sin(2 * Math.PI / 360 * 60), endY+1], ["L", endX - (10+r) * Math.sin(2 * Math.PI / 360 * 60), endY+5], ["Z"] ]; var g1= paper.path(rhopath).attr({fill: "red", stroke: "none"}); //绑定终点箭头拖拽事件 g1.attr({title:name+endIntevl}).data("reltype",data[i].reltype).data("odx",0).data("ody",0).data("mx",0).data("my",0).data("cmx",0).data("cmy",0).data("s",1).data("c",0) .data("id", graphic.data[i].id).data("type",graphic.data[i].type) //放大缩小点位置坐标绑定 .data("index",graphic.data[endIndex].x+":"+graphic.data[endIndex].y).mouseup(function(){ var tran = "t"+this.data("mx")+","+this.data("my"); this.transform(tran+"s1"); this.data("s",1); }); //箭头图像放入点集合 graphic.set.push(g1); //终点提示语句 var g2=paper.text(endX-45, endY+2, "End"); g2.attr({stroke: "red"}); //帮点start的拖拽事件 g2.attr({title:name+endIntevl}).data("reltype",data[i].reltype).data("odx",0).data("ody",0).data("mx",0).data("my",0).data("cmx",0).data("cmy",0).data("s",1).data("c",0) .data("id", graphic.data[i].id).data("type",graphic.data[i].type) //放大缩小点位置坐标绑定 .data("index",graphic.data[endIndex].x+":"+graphic.data[endIndex].y).mouseup(function(){ var tran = "t"+this.data("mx")+","+this.data("my"); this.transform(tran+"s1"); this.data("s",1); }); //终点提示语放入点集合 graphic.set.push(g2); } gra.attr({title:name+intevl}).data("reltype",data[i].reltype).data("odx",0).data("ody",0).data("mx",0).data("my",0).data("cmx",0).data("cmy",0).data("s",1).data("c",0).data("id", graphic.data[i].id).data("type",graphic.data[i].type).data("index",graphic.data[i].x+":"+graphic.data[i].y).mousedown( function () { var tran = "t"+this.data("mx")+","+this.data("my"); this.transform(tran+"s1.5"); this.data("s",1.5); if(isclick){ if(this.data("reltype") == -1){ $('#div_page').html("<div class=\"noservice\">No Service<\/div>"); }else{ $.ajax({ type:"post", url:contextPath+"/reportIndependent/wcdmaOrGsm", data:({id :this.data("id"),type:this.data("type")}), success:function(data){ $('#div_page').html(data.content); $('#div_page_max').html(data.contentMax); } }); } } }).mouseup(function(){ var tran = "t"+this.data("mx")+","+this.data("my"); this.transform(tran+"s1"); this.data("s",1); }); graphic.set.push(gra); } var onstart = function (event) { graphic.set.forEach(function(_me){ _me.data('cmx',_me.data("mx")); _me.data('cmy',_me.data("my")); }); }; var onmove = function (dx, dy) { graphic.set.forEach(function(_me){ var cmx = _me.data("mx") + dx; var cmy = _me.data("my") + dy; var tran = "t"+cmx+","+cmy+"s"+(_me.data("s")); _me.data('cmx',cmx); _me.data('cmy',cmy); _me.transform(tran); }); }; var onend = function () { graphic.set.forEach(function(_me){ var tran = "t"+_me.data('cmx')+","+_me.data('cmy')+"s1"; _me.transform(tran); _me.data("mx",_me.data('cmx')); _me.data("my",_me.data('cmy')); }); }; graphic.set.drag(onmove,onstart,onend); if(isshow){ graphic.set.show(); }else{ graphic.set.hide(); } graphic.hidden = function(){ graphic.set.hide(); }; graphic.getName = function(){ return graphic.name; }; graphic.show = function(){ graphic.set.show(); }; graphic.setIsShow = function(sh){ graphic.isshow = sh; }; graphic.changeCxy = function(left,ow,nw,islarge){ graphic.set.forEach(function(_me){ if(islarge){ var tran = "t"+(_me.data("mx")+(nw/ow)*100)+","+(_me.data("my"))+"s"+(_me.data("s")); _me.transform(tran); _me.data("mx",_me.data("mx")+(nw/ow)*100); }else{ var tran = "t"+(_me.data("mx")-((ow/nw)*100))+","+(_me.data("my"))+"s"+(_me.data("s")); _me.transform(tran); _me.data("mx",_me.data("mx")-((ow/nw)*100)); } }); } graphic.cxyExpand = function(scale,step){ graphic.scale = scale; graphic.step = step; graphic.set.forEach(function(_me){ var mx = _me.data("mx"); var my = _me.data("my"); var index = _me.data("index"); var in_x=index.split(":")[0]; var in_y=index.split(":")[1]; var tran = "t"+(mx+(graphic.step*in_x))+","+(my+(graphic.step*in_y))+"s"+(_me.data("s")); _me.transform(tran); _me.data("mx",(mx+(graphic.step*in_x))); _me.data("my",(my+(graphic.step*in_y))); }); }; graphic.cxyNarrow = function(scale,step){ graphic.scale = scale; graphic.step = step; graphic.set.forEach(function(_me){ var mx = _me.data("mx"); var my = _me.data("my"); var index = _me.data("index"); var in_x=index.split(":")[0]; var in_y=index.split(":")[1]; var tran = "t"+(mx-(graphic.step*in_x))+","+(my-(graphic.step*in_y))+"s"+(_me.data("s")); _me.transform(tran); _me.data("mx",(mx-(graphic.step*in_x))); _me.data("my",(my-(graphic.step*in_y))); }); }; return graphic; } <file_sep>/src/main/java/com/complaint/service/ComplainStatisticsService.java package com.complaint.service; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.complaint.dao.ComplainStatisticsDao; import com.complaint.model.ComplainProbability; import com.complaint.utils.PatternUtil; /** * 投诉率与投诉统计 * @author peng * */ @Service("complainStatisticsService") public class ComplainStatisticsService { @Autowired private ComplainStatisticsDao complainStatisticsDao; private static final Logger logger = LoggerFactory.getLogger(ComplainStatisticsService.class); public List<ComplainProbability> getComplain(Map<String, Object> map){ this.complainStatisticsDao.getComplain(map); List<ComplainProbability> st=(List<ComplainProbability>) map.get("depts"); return st; } public void CreateExcel(String path,Map<String, Object> map,String tempPath){ FileInputStream file = null; XSSFWorkbook wb = null; try { file = new FileInputStream(tempPath); wb = new XSSFWorkbook(file); } catch (Exception e) { logger.error("",e); } XSSFSheet sheet = null; if(wb!=null&&wb.getSheet("分析图表")!=null){ sheet = wb.getSheet("分析图表"); }else{ wb = new XSSFWorkbook(); sheet = wb.createSheet("分析图表"); } int day = 0; if(map.get("t_type").equals("1")){ day = getDay((String)map.get("s_time"),(String)map.get("e_time")); }else if(map.get("t_type").equals("2")){ day = getDay((String)map.get("m_time")); } Row dayRow = sheet.getRow(0); Cell dayCell = dayRow.createCell(5); dayCell.setCellValue(day); SXSSFWorkbook swb = new SXSSFWorkbook(wb); List<ComplainProbability> list = getComplain(map);//查出数据 dataComplain(swb,list,"GSMSPEECH");//2G语音投诉量 dataComplain(swb,list,"GSMDATA");//2G数据投诉量 dataComplain(swb,list,"GSM");//2G语音数据投诉量 dataComplain(swb,list,"WCDMASPEECH");//3G语音投诉量 dataComplain(swb,list,"WCDMADATA");//3G数据投诉量 dataComplain(swb,list,"WCDMA");//3G语音数据投诉量 dataComplain(swb,list,"ALL");//全网投诉量 analyzeComplain(swb,list);//分析报表页面 FileOutputStream out =null; try { out = new FileOutputStream(path); swb.write(out); } catch (Exception e) { logger.error(" ",e); } finally{ try { if(out!=null){ out.close(); } } catch (IOException e) { logger.error(" ",e); } } } /** * 分析报表页面 */ public void analyzeComplain(SXSSFWorkbook swb,List<ComplainProbability> list){ CellStyle style = analyzeStyle(swb); CellStyle style2 = analyzeStyle(swb); DataFormat dataFormat= swb.createDataFormat();//设置成百分比形式 style2.setDataFormat(dataFormat.getFormat("0.00%")); Sheet sheet = swb.getSheet("分析图表"); for(int i=0 ;i<list.size();i++){ ComplainProbability comp = list.get(i); Row row = null; if(sheet.getRow(i+2)==null){ row = sheet.createRow(i+2); }else{ row = sheet.getRow(i+2); } Cell cell0 = row.createCell(0); cell0.setCellValue(comp.getAreaname()==null?"":comp.getAreaname());//区域 cell0.setCellStyle(style); Cell cell1 = row.createCell(1); cell1.setCellValue(comp.getGroupname()==null?"":comp.getGroupname());//公司类型名字 cell1.setCellStyle(style); //2,3为本月2G,3G用户,客户自己填 Cell cell2 = row.createCell(2); cell2.setCellValue(""); cell2.setCellStyle(style); Cell cell3 = row.createCell(3); cell3.setCellValue(""); cell3.setCellStyle(style); Cell cell4 = row.createCell(4); cell4.setCellFormula("VLOOKUP(A:A,'2G语音数据投诉量'!A:B,2,0)");//2G投诉量 cell4.setCellStyle(style); Cell cell5 = row.createCell(5); cell5.setCellFormula("VLOOKUP(A:A,'3G语音数据投诉量'!A:B,2,0)");//3G投诉量 cell5.setCellStyle(style); Cell cell6 = row.createCell(6); cell6.setCellFormula("VLOOKUP(A:A,'2G语音投诉量'!A:B,2,0)");//2G语音投诉量 cell6.setCellStyle(style); Cell cell7 = row.createCell(7); cell7.setCellFormula("VLOOKUP(A:A,'3G语音投诉量'!A:B,2,0)");//3G语音投诉量 cell7.setCellStyle(style); Cell cell8 = row.createCell(8); cell8.setCellFormula("IF(ISERROR(E"+(i+3)+"/C"+(i+3)+"/$F$1),0,E"+(i+3)+"/C"+(i+3)+"/$F$1)");//2G日均万人投诉率 cell8.setCellStyle(style2); Cell cell9 = row.createCell(9); cell9.setCellFormula("IF(ISERROR(F"+(i+3)+"/D"+(i+3)+"/$F$1),0,F"+(i+3)+"/D"+(i+3)+"/$F$1)");//3G日均万人投诉率 cell9.setCellStyle(style2); Cell cell10 = row.createCell(10); cell10.setCellFormula("IF(ISERROR((E"+(i+3)+"+F"+(i+3)+")/(C"+(i+3)+"+D"+(i+3)+")/$F$1),0,(E"+(i+3)+"+F"+(i+3)+")/(C"+(i+3)+"+D"+(i+3)+")/$F$1)");//3G日均万人投诉率 cell10.setCellStyle(style2); //11,12为2G语音话务量,3G语音话务量客户自己填 Cell cell11 = row.createCell(11); cell11.setCellValue(""); cell11.setCellStyle(style); Cell cell12 = row.createCell(12); cell12.setCellValue(""); cell12.setCellStyle(style); Cell cell13 = row.createCell(13); cell13.setCellFormula("IF(ISERROR(E"+(i+3)+"/L"+(i+3)+"*10000),0,E"+(i+3)+"/L"+(i+3)+"*10000)");//2G投诉话务(万Erl)比 cell13.setCellStyle(style); Cell cell14 = row.createCell(14); cell14.setCellFormula("IF(ISERROR(F"+(i+3)+"/M"+(i+3)+"*10000),0,F"+(i+3)+"/M"+(i+3)+"*10000)");//3G投诉话务(万Erl)比 cell14.setCellStyle(style); Cell cell15 = row.createCell(15); cell15.setCellFormula("IF(ISERROR((E"+(i+3)+"+F"+(i+3)+")/(L"+(i+3)+"+M"+(i+3)+")*10000),0,(E"+(i+3)+"+F"+(i+3)+")/(L"+(i+3)+"+M"+(i+3)+")*10000)");//3G日均万人投诉率 cell15.setCellStyle(style); Cell cell16 = row.createCell(16); cell16.setCellValue(comp.getGsm_inside_uncovered());//2G室内无覆盖投诉量 cell16.setCellStyle(style); Cell cell17 = row.createCell(17); cell17.setCellValue(comp.getGsm_outside_uncovered());//2G室外无覆盖投诉量 cell17.setCellStyle(style); Cell cell18 = row.createCell(18); cell18.setCellValue(comp.getWcdma_inside_uncovered());//3G室内无覆盖投诉量 cell18.setCellStyle(style); Cell cell19 = row.createCell(19); cell19.setCellValue(comp.getWcdma_outside_uncovered());//3G室外无覆盖投诉量 cell19.setCellStyle(style); Cell cell20 = row.createCell(20); cell20.setCellFormula("IF(ISERROR(Q"+(i+3)+"/(Q"+(i+3)+"+R"+(i+3)+")),0,Q"+(i+3)+"/(Q"+(i+3)+"+R"+(i+3)+"))");//2G室内无覆盖占比 cell20.setCellStyle(style2); Cell cell21 = row.createCell(21); cell21.setCellFormula("IF(ISERROR(R"+(i+3)+"/(Q"+(i+3)+"+R"+(i+3)+")),0,R"+(i+3)+"/(Q"+(i+3)+"+R"+(i+3)+"))");//2G室外无覆盖占比 cell21.setCellStyle(style2); Cell cell22 = row.createCell(22); cell22.setCellFormula("IF(ISERROR(S"+(i+3)+"/(S"+(i+3)+"+T"+(i+3)+")),0,S"+(i+3)+"/(S"+(i+3)+"+T"+(i+3)+"))");//3G室内无覆盖占比 cell22.setCellStyle(style2); Cell cell23 = row.createCell(23); cell23.setCellFormula("IF(ISERROR(T"+(i+3)+"/(S"+(i+3)+"+T"+(i+3)+")),0,T"+(i+3)+"/(S"+(i+3)+"+T"+(i+3)+"))");//3G室内无覆盖占比 cell23.setCellStyle(style2); } sheet.setForceFormulaRecalculation(true); } /** * 2G语音数据投诉量,3G语音数据投诉量,全网投诉量,2G语音投诉量,2G数据投诉量,3G语音投诉量,3G数据投诉量 生成对应sheet */ public void dataComplain(SXSSFWorkbook swb,List<ComplainProbability> list,String type){ CellStyle left = getLeftStyle(swb); CellStyle right = getRightStyle(swb); Sheet sheet = null; if(type.equals("WCDMA")){ sheet = swb.createSheet("3G语音数据投诉量"); }else if(type.equals("GSM")){ sheet = swb.createSheet("2G语音数据投诉量"); }else if(type.equals("ALL")){ sheet = swb.createSheet("全网投诉量"); }else if(type.equals("GSMSPEECH")){ sheet = swb.createSheet("2G语音投诉量"); }else if(type.equals("GSMDATA")){ sheet = swb.createSheet("2G数据投诉量"); }else if(type.equals("WCDMASPEECH")){ sheet = swb.createSheet("3G语音投诉量"); }else if(type.equals("WCDMADATA")){ sheet = swb.createSheet("3G数据投诉量"); } if(sheet!=null){ sheet.setForceFormulaRecalculation(true); } for(int i = 0;i<list.size();i++){ Row row = sheet.createRow(i); Cell cell0 = row.createCell(0);//第一列区域名字 cell0.setCellValue(list.get(i).getAreaname()==null?"":list.get(i).getAreaname()); cell0.setCellStyle(left); Cell cell1 = row.createCell(1);//第二列数据 if(type.equals("WCDMA")){ cell1.setCellFormula("VLOOKUP(A:A,'3G语音投诉量'!A:B,2,0)+VLOOKUP(A:A,'3G数据投诉量'!A:B,2,0)"); }else if(type.equals("GSM")){ cell1.setCellFormula("VLOOKUP(A:A,'2G语音投诉量'!A:B,2,0)+VLOOKUP(A:A,'2G数据投诉量'!A:B,2,0)"); }else if(type.equals("ALL")){ cell1.setCellFormula("VLOOKUP(A:A,'2G语音数据投诉量'!A:B,2,0)+VLOOKUP(A:A,'3G语音数据投诉量'!A:B,2,0)"); }else if(type.equals("GSMSPEECH")){ cell1.setCellValue(list.get(i).getGsm_speech_complaint()); }else if(type.equals("GSMDATA")){ cell1.setCellValue(list.get(i).getGsm_data_complaint()); }else if(type.equals("WCDMASPEECH")){ cell1.setCellValue(list.get(i).getWcdma_speech_complaint()); }else if(type.equals("WCDMADATA")){ cell1.setCellValue(list.get(i).getWcdma_data_complaint()); } cell1.setCellStyle(right); } } /** * 普通单元格加边框左对齐样式 */ public CellStyle getLeftStyle(SXSSFWorkbook swb){ CellStyle style = swb.createCellStyle(); //加边框 style.setBorderTop(XSSFCellStyle.BORDER_THIN); style.setBorderBottom(XSSFCellStyle.BORDER_THIN); style.setBorderLeft(XSSFCellStyle.BORDER_THIN); style.setBorderRight(XSSFCellStyle.BORDER_THIN); style.setAlignment(XSSFCellStyle.ALIGN_LEFT);// 水平居中 style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 垂直居中 return style; } /** * 普通单元格加边框右对齐样式 */ public CellStyle getRightStyle(SXSSFWorkbook swb){ CellStyle style = swb.createCellStyle(); //加边框 style.setBorderTop(XSSFCellStyle.BORDER_THIN); style.setBorderBottom(XSSFCellStyle.BORDER_THIN); style.setBorderLeft(XSSFCellStyle.BORDER_THIN); style.setBorderRight(XSSFCellStyle.BORDER_THIN); style.setAlignment(XSSFCellStyle.ALIGN_RIGHT);// 水平居中 style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 垂直居中 return style; } /** * 分析sheet样式 */ public CellStyle analyzeStyle(SXSSFWorkbook swb){ CellStyle style = swb.createCellStyle(); //加边框 style.setBorderTop(XSSFCellStyle.BORDER_THIN); style.setBorderBottom(XSSFCellStyle.BORDER_THIN); style.setBorderLeft(XSSFCellStyle.BORDER_THIN); style.setBorderRight(XSSFCellStyle.BORDER_THIN); style.setAlignment(XSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中 style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 垂直居中 return style; } /** * 获取时间段天数 */ public int getDay(String s ,String e){ int day =0; try { SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); Date d1 = sd.parse(s); Date d2 = sd.parse(e); long quot =d2.getTime()-d1.getTime(); day = (int) (quot / 1000 / 60 / 60 / 24); } catch (Exception e1) { logger.error("change date time",e1); } return day; } public int getDay(String data){ String[] str1 =data.split("-"); long time=System.currentTimeMillis(); Date dt = new Date(time); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String now=sdf.format(dt); String[] str2 = now.split("-"); int cc =0; if(Integer.parseInt(str1[0])==Integer.parseInt(str2[0]) && Integer.parseInt(str1[1])==Integer.parseInt(str2[1])){ cc = Integer.parseInt(str2[2]); }else if(Integer.parseInt(str1[0])>Integer.parseInt(str2[0])){ cc = 0; }else if(Integer.parseInt(str1[0])==Integer.parseInt(str2[0]) && Integer.parseInt(str1[1])>Integer.parseInt(str2[1])){ cc =0; }else{ Calendar aCalendar = Calendar.getInstance(Locale.CHINA); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM"); Date d = new Date(); try { d = sdf2.parse(data); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } aCalendar.setTime(d); cc=aCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); } return cc; } public List<ComplainProbability> getinfo(Map<String, Object> map){ List<ComplainProbability> list = getComplain(map);//查出数据 for(ComplainProbability cp:list){ //总投诉量计算 cp.setGsm_complaint(cp.getGsm_speech_complaint()+cp.getGsm_data_complaint()); cp.setWcdma_complaint(cp.getWcdma_speech_complaint()+cp.getWcdma_data_complaint()); //计算无覆盖率 if(cp.getGsm_outside_uncovered()+cp.getGsm_inside_uncovered()!=0){ cp.setGsm_inside_ratio( PatternUtil.getSolvRate(cp.getGsm_inside_uncovered() ,(cp.getGsm_outside_uncovered()+cp.getGsm_inside_uncovered()) ) ); cp.setGsm_outside_ratio( PatternUtil.getSolvRate(cp.getGsm_outside_uncovered() ,(cp.getGsm_outside_uncovered()+cp.getGsm_inside_uncovered()) ) ); }else{ cp.setGsm_inside_ratio(0.00); cp.setGsm_outside_ratio(0.00); } if(cp.getWcdma_outside_uncovered()+cp.getWcdma_inside_uncovered()!=0){ cp.setWcdma_inside_ratio( PatternUtil.getSolvRate(cp.getWcdma_inside_uncovered() ,(cp.getWcdma_outside_uncovered()+cp.getWcdma_inside_uncovered()) ) ); cp.setWcdma_outside_ratio( PatternUtil.getSolvRate(cp.getWcdma_outside_uncovered() ,(cp.getWcdma_outside_uncovered()+cp.getWcdma_inside_uncovered()) ) ); }else{ cp.setWcdma_inside_ratio(0.00); cp.setWcdma_outside_ratio(0.00); } } return list; } } <file_sep>/src/main/java/com/complaint/dao/BaseDao.java package com.complaint.dao; import java.util.List; public interface BaseDao { public void batchInsert(Class<?> type,List<?> list,Integer batchNum) throws Exception; } <file_sep>/src/main/webapp/js/workorder/workorder.js $(function() { $.parser.parse('#cc'); $.parser.parse('#ii'); $.parser.parse('#gg'); $.parser.parse('#nettype'); $.parser.parse('#datatype'); $.parser.parse('#jj'); $.parser.parse('#kk'); initeScence(); initeTestType(); initeTestnets(); initeWorkerOrdernets(); var optInit = {callback: function(page_index,jq){ $.ajax({ type:"post", url: contextPath + "/workorder/workorderlist/template", data:({sernos : $("#hiddenval").val(), isDeal:isDeal, startTime:startTime, endTime:endTime, pageIndex: page_index+1, testphone:testphone, inside:inside, senceids:senceids, testtype:testtype, nettype:nettype, datatype:datatype, jobtype:jobtype, testnet:testnet, workerOrderNet:workerOrderNet, workerOrderNetName:workerOrderNetName, areaids:$("#areaids").val(), verify:verify, s_id:s_id}), success:function(data){ $('#content').html(data); $(".compare_test").click(function(){ var snoid = $(this).attr("id"); var areaid = $(this).attr("areaid"); var s_id = $(this).attr("s_id"); var src=contextPath+"/report/findFlowid?serialno="+snoid+"&s_id="+s_id+"&areaid="+areaid; $("#win").dialog({ href:src, height: 400,width: 480,title: "测试流水选择", modal: true,closed:false }); $('#win').dialog('open'); $.parser.parse('#win'); $(".comparetree").click(function(){ var nodes = $('#win').tree('getChecked'); var s = '',str='',s_na=''; for(var i=0; i<nodes.length; i++){ if (s != '') s += ','; s += nodes[i].id; if (s_na != '') s_na += ','; s_na+=nodes[i].text; } // var idstr = s.split(","); // var arr = []; // for ( var i = 0; i < idstr.length; i++) { // if (idstr[i].length > 1) { // if(idstr[i]!="1" && idstr[i] != "2"){ // arr.push(idstr[i]); // } // } // } // for ( var i = 0; i < arr.length; i++) { // str += arr[i]+ ','; // } $('#win').dialog('open'); window.location.href=contextPath+"/report/reportCompare?flowid="+s+"&flowname="+s_na+"&serialno="+snoid+"&s_id="+s_id+"&areaid="+areaid; }); }); } }); return false; } }; $("#pager").pagination(pageTotal, optInit); $("#areas").combobox({ onShowPanel:function(){ $("#areas").combobox("hidePanel"); var src = contextPath + '/workorder/arealist?areaids='+$("#areaids").val()+"&type=0"; $("#areadlg").dialog({ href:src, height: 400,width: 380,title: "选择区域", modal: true,closed:false }); $('#areadlg').dialog('open'); $.parser.parse('#areadlg'); $(".sel_area").unbind('click').click(function(){ var nodes = $('#areadlg').tree('getChecked'); var strtext = ""; var strids = ""; if(nodes.length > 0){ for(var i = 0; i < nodes.length; i++){ strids += nodes[i].id + ","; strtext += nodes[i].text + ","; } if(strids !=null && strids != ""){ strids = strids.substring(0,strids.length-1); $("#areaids").val(strids); } if(strtext !=null && strtext != ""){ strtext = strtext.substring(0,strtext.length-1); $("#areas").combobox("setText",strtext); $("#areatext").val(strtext); } }else{ $("#areaids").val('-1'); $("#areatext").val('全部'); $("#areas").combobox("setText",'全部'); } $('#areadlg').dialog('close'); }); } }); }); function search(){ var sno = $.trim($("#serialno").val()); $("#hiddenval").val(sno); $("#serialno").val(sno); isDeal = $("#cc").combobox('getValue'); testphone = $.trim($("#testphone").val()); $("#testphone").val(testphone); areaids = $("#areaids").val(); startTime = $("#startTime").val(); endTime = $("#endTime").val(); inside = $("#ii").combobox('getValue'); senceids = $("#senceids").val(); testtype = $("#testtype").val(); nettype=$("#nettype").combobox('getValue'); datatype=$("#datatype").combobox('getValue'); jobtype=$("#jj").combobox('getValue'); testnet = $("#testnet").val(); verify = $("#verify").combobox('getValue'); workerOrderNet = $("#workerOrderNet").val(); workerOrderNetName = $("#workerOrderNetName").val(); if (startTime != "" && startTime != null && endTime != "" && endTime != null) { var arr1 = startTime.split("/"); var startDate = new Date(arr1[0],parseInt(arr1[1])-1,arr1[2]); var arr2 = endTime.split("/"); var endDate = new Date(arr2[0],parseInt(arr2[1])-1,arr2[2]); if(startDate > endDate){ $.messager.alert("提示","开始时间应小于结束时间!","warning"); return false; } }else{ $.messager.alert("提示","时间不能为空!","warning"); return false; } $("#searchForm").submit(); } function exportExcel(){ $(".right1").show(); $.ajax({ url:contextPath + '/workorder/workorderlist/export', type:"post", data:({sernos : $("#hiddenval").val(), isDeal:isDeal, startTime:startTime, endTime:endTime, testphone:testphone, inside:inside, senceids:senceids, testtype:testtype, nettype:nettype, datatype:datatype, jobtype:jobtype, testnet:testnet, workerOrderNet:workerOrderNet, workerOrderNetName:workerOrderNetName, areaids:$("#areaids").val(), verify:verify, s_id:s_id}), success:function(data){ $(".right1").hide(); if(data!="-1" && data!=null){ window.location.href=contextPath+"/workorder/downLoadExcel?name="+data; }else{ $.messager.alert('提示','导出失败!',"error"); } }, error:function(){ $(".right1").hide(); } }) } <file_sep>/src/main/java/com/complaint/model/Personnel.java package com.complaint.model; import java.util.ArrayList; import java.util.List; public class Personnel { private Integer id;// 人员ID private String name;// 人员名称 private String phone;// 人员电话 private List<AreaBean> list = new ArrayList<AreaBean>();// 对于的区域 public List<AreaBean> getList() { return list; } public void setList(List<AreaBean> list) { this.list = list; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } } <file_sep>/src/main/java/com/complaint/model/TrackCell.java package com.complaint.model; import java.util.List; /*** * 轨迹(室内外)基站小区图 * @author Administrator *小区角度差变量默认15 */ public class TrackCell { private Double lat;//纬度 private Double lng;//经度 private Double position;//方位角 private Integer psc; private Double min;//比例开始 private Double max;//比例结束 private Integer nettype; private String laccidname;//小区显示 private Integer bcch; private Integer isindoor;//是否室分 private String wmtid;//基站ID private Double latcenter;//入口纬度 private Double lngcenter;//入口经度 public String getLaccidname() { return laccidname; } public void setLaccidname(String laccidname) { this.laccidname = laccidname; } public Integer getBcch() { return bcch; } public void setBcch(Integer bcch) { this.bcch = bcch; } public Integer getIsindoor() { return isindoor; } public void setIsindoor(Integer isindoor) { this.isindoor = isindoor; } public String getWmtid() { return wmtid; } public void setWmtid(String wmtid) { this.wmtid = wmtid; } public Double getLatcenter() { return latcenter; } public void setLatcenter(Double latcenter) { this.latcenter = latcenter; } public Double getLngcenter() { return lngcenter; } public void setLngcenter(Double lngcenter) { this.lngcenter = lngcenter; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } public Double getLng() { return lng; } public void setLng(Double lng) { this.lng = lng; } public Double getPosition() { return position; } public void setPosition(Double position) { this.position = position; } public Integer getPsc() { return psc; } public void setPsc(Integer psc) { this.psc = psc; } public Double getMin() { return min; } public void setMin(Double min) { this.min = min; } public Double getMax() { return max; } public void setMax(Double max) { this.max = max; } public Integer getNettype() { return nettype; } public void setNettype(Integer nettype) { this.nettype = nettype; } } <file_sep>/src/main/java/com/complaint/service/StatAndEvalReportService.java package com.complaint.service; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.context.WebApplicationContext; import com.complaint.model.ComplainEvaluate; import com.complaint.model.ComplainStatistics; import com.complaint.model.QualTopAndLast; import com.complaint.model.MostTestRate; import com.complaint.model.QualtyReport; import com.complaint.utils.Constant; import com.complaint.utils.PatternUtil; import com.complaint.utils.SpringStoredProce; @Service("statAndEvalReportService") public class StatAndEvalReportService { private static final Logger logger = LoggerFactory .getLogger(StatAndEvalReportService.class); @Autowired private SysConfigService sysConfigService; /** * 调用存储过程 需要传入WebApplicationContext,storedProcName,param * WebApplicationContext根据request得到 * storedProcName存储过程的包和类名 * param参数,由1,2,3---日周月 起始时间格式2013-8-15,结束时间格式2013-8-16 * @param ctx * @param param * @return */ public ResultSet getStoreProce(WebApplicationContext ctx ,String storedProcName ,Map<String,Object> params){ // WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext()); DataSource ds = ctx.getBean("dataSource", DataSource.class); // final String storedProcName = "gradekpi_package.gradekpi_proc"; SpringStoredProce ssp = new SpringStoredProce(); ResultSet rs=null; try { rs = ssp.execute(storedProcName, params, ds); } catch (Exception e) { e.printStackTrace(); } return rs; } /** * 处理传入数据,调用准备存储过程 */ public Map getAllStatAndEval(WebApplicationContext ctx ,Map<String,Object> params){ //初始化筛选类 MostTestRate mostTestRate = new MostTestRate(); Map map1 = this.top(ctx, params); Map map2 = this.bottom(ctx, params); ComplainStatistics stat = (ComplainStatistics) map1.get("stat"); ComplainEvaluate eval = (ComplainEvaluate) map2.get("eval"); //查询测试报告累计时间 String reportdate = sysConfigService.getValue(Constant.REPORTDATE); //查询累计网络工单投诉量 Map<String, Object> param = new HashMap<String, Object>(); param.put("systime", reportdate); param.put("endtime", params.get("endtime")+" 23:59:59"); param.put("p_area_id", params.get("queryAreaIds")); List<Map> list3=sysConfigService.getTotalSer(param); //新增改善比例 LinkedList<String> gsmRank = new LinkedList<String>(); LinkedList<String> wcdmaRank = new LinkedList<String>(); for(int i = 0;i<eval.getArea_id().length;i++){ int total = 0; for(int j=0;j<list3.size();j++) { if(eval.getArea_id()[i]== ((BigDecimal)list3.get(j).get("AREA_ID")).intValue()){ total=((BigDecimal)list3.get(j).get("TOTAL_WORKORDER")).intValue(); } } if(total!=0){ double val2g = eval.getComp_impr_value_2g()[i]; double val3g = eval.getComp_impr_value_3g()[i]; gsmRank.add(PatternUtil.getDouble((double)(val2g*100000/total)/1000)); wcdmaRank.add(PatternUtil.getDouble((double)(val3g*100000/total)/1000)); }else{ gsmRank.add("0%"); wcdmaRank.add("0%"); } } wcdmaRank.toArray(eval.getComp_impr_ratio_3g()); gsmRank.toArray(eval.getComp_impr_ratio_2g()); if(stat.getArea_id()!=null&&eval.getArea_id()!=null){ if(eval.getArea_id().length == stat.getArea_id().length){//防止上下两个存储过程长度不一样,导致下方判断最大最下值时下标越界 // 当月实测量最大的区域是xx;累计测试率最高的区域是yy;当月实测量最少的区域是zz;累计实测率最低的区域是mm // 当月实测量最大 List<Integer> currTestMax = this.getMax(stat.getCurr_test()); if(currTestMax.size()>1){ mostTestRate.setCurr_max_test(stat.getArea_name()[this.LastMax(stat.getTotal_test(),currTestMax)]); }else if(currTestMax.size()==1){ mostTestRate.setCurr_max_test(stat.getArea_name()[currTestMax.get(0)]); } // 累计测试率最高 List<Integer> totalTestMax = this.getMax(stat.getTotal_test_rate()); if(totalTestMax.size()>0){ mostTestRate.setTotal_max_test(stat.getArea_name()[totalTestMax.get(0)]); } // 当月测试量最少 List<Integer> currTestMin = this.getMin(stat.getCurr_test()); if(currTestMin.size()>1){ mostTestRate.setCurr_min_test(stat.getArea_name()[this.LastMin(stat.getTotal_test(),currTestMin)]); }else if(currTestMin.size()>0){ mostTestRate.setCurr_min_test(stat.getArea_name()[currTestMin.get(0)]); } // 累积测试率最小 List<Integer> totalTestMin = this.getMin(stat.getTotal_test_rate()); if(totalTestMin.size()>0){ mostTestRate.setTotal_min_test(stat.getArea_name()[totalTestMin.get(0)]); } // 综合评价最好的区域是uu;综合改善最大的区域是tt;综合评价最差的区域是ww;综合改善最低的区域是bb // 评价最好3g List<Integer> comp_eval_3g_max = this.evalMaxValue(eval.getComp_eval_3g_a(),eval.getComp_eval_3g_b(),eval.getComp_eval_3g_c(),eval.getComp_eval_3g_d()); if(comp_eval_3g_max.size()>0){ mostTestRate.setComp_eval_3g_max(stat.getArea_name()[comp_eval_3g_max.get(0)]); } // 评价最好2g List<Integer> comp_eval_2g_max = this.evalMaxValue(eval.getComp_eval_2g_a(),eval.getComp_eval_2g_b(),eval.getComp_eval_2g_c(),eval.getComp_eval_2g_d()); if(comp_eval_2g_max.size()>0){ mostTestRate.setComp_eval_2g_max(stat.getArea_name()[comp_eval_2g_max.get(0)]); } // 评价最差3g List<Integer> comp_eval_3g_min = this.evalMinValue(eval.getComp_eval_3g_a(),eval.getComp_eval_3g_b(),eval.getComp_eval_3g_c(),eval.getComp_eval_3g_d()); if(comp_eval_3g_min.size()>0){ mostTestRate.setComp_eval_3g_min(stat.getArea_name()[comp_eval_3g_min.get(0)]); } // 评价最差2g List<Integer> comp_eval_2g_min = this.evalMinValue(eval.getComp_eval_2g_a(),eval.getComp_eval_2g_b(),eval.getComp_eval_2g_c(),eval.getComp_eval_2g_d()); if(comp_eval_2g_min.size()>0){ mostTestRate.setComp_eval_2g_min(stat.getArea_name()[comp_eval_2g_min.get(0)]); } // 综合改善最好3g List<Integer> comp_impr_3g_max = this.getMax(eval.getComp_impr_value_3g()); if(comp_impr_3g_max.size()>0){ mostTestRate.setComp_impr_3g_max(stat.getArea_name()[comp_impr_3g_max.get(0)]); } // 综合改善最好2g List<Integer> comp_impr_2g_max = this.getMax(eval.getComp_impr_value_2g()); if(comp_impr_2g_max.size()>0){ mostTestRate.setComp_impr_2g_max(stat.getArea_name()[comp_impr_2g_max.get(0)]); } // 综合改善最差3g List<Integer> comp_impr_3g_min = this.getMin(eval.getComp_impr_value_3g()); if(comp_impr_3g_min.size()>0){ mostTestRate.setComp_impr_3g_min(stat.getArea_name()[comp_impr_3g_min.get(0)]); } // 综合改善最差2g List<Integer> comp_impr_2g_min = this.getMin(eval.getComp_impr_value_2g()); if(comp_impr_2g_min.size()>0){ mostTestRate.setComp_impr_2g_min(stat.getArea_name()[comp_impr_2g_min.get(0)]); } // 最好及时率 List<Integer> time_rate_max = this.getMax(eval.getTimely_rate()); if(time_rate_max.size()>0){ mostTestRate.setTimely_rate_max(stat.getArea_name()[time_rate_max.get(0)]); } // 最差及时率 List<Integer> time_rate_min = this.getMin(eval.getTimely_rate()); if(time_rate_min.size()>0){ mostTestRate.setTimely_rate_min(stat.getArea_name()[time_rate_min.get(0)]); } }else{ mostTestRate.setTotal_min_test("无"); mostTestRate.setCurr_min_test("无"); mostTestRate.setTotal_max_test("无"); mostTestRate.setCurr_max_test("无"); mostTestRate.setComp_eval_3g_max("无"); mostTestRate.setComp_eval_2g_max("无"); mostTestRate.setComp_eval_3g_min("无"); mostTestRate.setComp_eval_2g_min("无"); mostTestRate.setComp_impr_3g_max("无"); mostTestRate.setComp_impr_2g_max("无"); mostTestRate.setComp_impr_3g_min("无"); mostTestRate.setComp_impr_2g_min("无"); mostTestRate.setTimely_rate_max("无"); mostTestRate.setTimely_rate_min("无"); } } // 获取所有最大值 // ReportMaxValue reportMaxValue = getAllMaxValue(stat,eval); Map lastMap = new HashMap(); // lastMap.put("reportMaxValue", reportMaxValue); lastMap.put("mostTestRate", mostTestRate); lastMap.put("stat", stat); lastMap.put("eval", eval); return lastMap; } /** * 查出最大值下标 */ public List<Integer> getMax(Integer [] num){ List<Integer> list = new ArrayList<Integer>(); int res =0; int index = 0; for(int i =0;i<num.length;i++){ if(i==0){ res=num[i]; }else{ if(res<num[i]){ res=num[i]; } } } for(int j =0;j<num.length;j++){ if(num[j]==res){ index =j; list.add(index); } } return list; } public List<Integer> getMax(Double [] num){ List<Integer> list = new ArrayList<Integer>(); double res =0; int index = 0; for(int i =0;i<num.length;i++){ if(i==0){ res=num[i]; }else{ if(res<num[i]){ res=num[i]; } } } for(int j =0;j<num.length;j++){ if(num[j]==res){ index =j; list.add(index); } } return list; } /** * String类型查出最大值下标 */ public List<Integer> getMax(String [] num){ List<Integer> list = new ArrayList<Integer>(); double res =0; int index = 0; double curr_num=0; for(int i =0;i<num.length;i++){ if(!(num[i].startsWith("%"))){ curr_num=Double.parseDouble(num[i].substring(0,num[i].length()-1)); }else{ curr_num=0; } if(i==0){ res=curr_num; }else{ if(compare(res,curr_num)==1){ res=curr_num; } } } for(int j =0;j<num.length;j++){ curr_num=0; String tem =num[j]; if(!tem.startsWith("%")){ curr_num = Double.parseDouble(tem.substring(0,tem.length()-1)); }else{ curr_num=0; } if(compare(curr_num,res)==0){ index =j; list.add(index); } } return list; } /** * 在最大值并列的情况下,传入下标和数组,在比较其他项 */ public Integer LastMax(Integer[] num,List<Integer> list){ int index = 0; int currNum =0; for(int i =0;i<list.size();i++){ if(i==0){ index = list.get(i); currNum =num[index]; }else{ if(currNum<num[list.get(i)]){ index = list.get(i); currNum=num[index]; } } } return index; } /** * 查出最小值下标 */ public List<Integer> getMin(Integer [] num){ List<Integer> list = new ArrayList<Integer>(); int res =0; int index =0; for(int i =0;i<num.length;i++){ if(i==0){ res=num[i]; }else{ if(res>num[i]){ res=num[i]; } } } for(int j =0;j<num.length;j++){ if(num[j]==res){ index =j; list.add(index); } } return list; } public List<Integer> getMin(Double [] num){ List<Integer> list = new ArrayList<Integer>(); double res =0; int index =0; for(int i =0;i<num.length;i++){ if(i==0){ res=num[i]; }else{ if(res>num[i]){ res=num[i]; } } } for(int j =0;j<num.length;j++){ if(num[j]==res){ index =j; list.add(index); } } return list; } /** * 查出最小值下标 */ public List<Integer> getMin(String [] num){ List<Integer> list = new ArrayList<Integer>(); double res =0; int index =0; double curr_num=0; for(int i =0;i<num.length;i++){ if(!(num[i].startsWith("%"))){ curr_num=Double.parseDouble(num[i].substring(0,num[i].length()-1)); }else{ curr_num=0; } if(i==0){ res=curr_num; }else{ if(compare(res,curr_num)==2){ res=curr_num; } } } for(int j =0;j<num.length;j++){ curr_num = 0; String tem = num[j]; if(!tem.startsWith("%")){ curr_num=Double.parseDouble(tem.substring(0,tem.length()-1)); }else{ curr_num = 0; } if(compare(curr_num,res)==0){ index =j; list.add(index); } } return list; } /** * 在最小值并列的情况下,传入下标和数组,在比较其他项 */ public Integer LastMin(Integer[] num,List<Integer> list){ int index = 0; int currNum =0; for(int i =0;i<list.size();i++){ if(i==0){ index = list.get(i); currNum = num[index]; }else{ if(currNum>num[list.get(i)]){ index = list.get(i); currNum=num[index]; } } } return index; } /** * 评价值求最大 */ public List<Integer> evalMaxValue(Integer[] a,Integer[] b,Integer[] c,Integer[] d){ List<Integer> max = new ArrayList<Integer>(); List<Integer> list = new ArrayList<Integer>(); int num=0; int maxNum=0; for(int i =0;i<a.length;i++){ num = a[i]*4+b[i]*2+c[i]*1+d[i]*(-4); // 所有最大值集合 list.add(num); // 算出最大值maxNum if(i!=0){ if(num>maxNum){ maxNum = num; } }else{ maxNum = num; } } for(int j =0;j<list.size();j++){ if(maxNum==list.get(j)){ max.add(j); } } return max; } /** * 评价值求最小 */ public List<Integer> evalMinValue(Integer[] a,Integer[] b,Integer[] c,Integer[] d){ List<Integer> min = new ArrayList<Integer>(); List<Integer> list = new ArrayList<Integer>(); int num=0; int minNum=0; for(int i =0;i<a.length;i++){ num = a[i]*4+b[i]*2+c[i]*1+d[i]*(-4); // 所有最小值集合 list.add(num); // 算出最小值maxNum if(i!=0){ if(num<minNum){ minNum = num; } }else{ minNum = num; } } for(int j =0;j<list.size();j++){ if(minNum==list.get(j)){ min.add(j); } } return min; } /** * double类型大小比较a,b比较大小a=b返回0,a<b返回1,a>b返回2 */ public int compare(double a,double b){ BigDecimal val1 = new BigDecimal(a); BigDecimal val2 = new BigDecimal(b); int result =0; if (val1.compareTo(val2) == 0) { // 等于返回0 result = 0; } if (val1.compareTo(val2) < 0) { // 小于返回1 result = 1; } if (val1.compareTo(val2) > 0) { // 大于返回2 result = 2; } return result; } /** * 处理测试率只有%而不是0% */ public String TotalRate(String totalRate){ String currRate=totalRate; if(totalRate.startsWith("%")){ currRate="0%"; } return currRate; } /** * 报表上端 * @param ctx * @param storedProcName * @param params * @return */ public Map top(WebApplicationContext ctx ,Map<String,Object> params){ Map map = new HashMap(); // 查出统计数据 final String storedProcNameStat = "pro_cas_stat"; ResultSet setStat = this.getStoreProce(ctx,storedProcNameStat,params); //ResultSet countStat = setStat; ComplainStatistics stat = new ComplainStatistics(); // 创建list接受结果 LinkedList<String> statQuery_date = new LinkedList<String>(); LinkedList<Integer> statArea_id = new LinkedList<Integer>(); LinkedList<String> statArea_name = new LinkedList<String>(); LinkedList<Integer> statTotal_workorder = new LinkedList<Integer>(); LinkedList<Integer> statCurr_workorder = new LinkedList<Integer>(); LinkedList<Integer> statTotal_test = new LinkedList<Integer>(); LinkedList<Integer> statCurr_test = new LinkedList<Integer>(); LinkedList<String> statTotal_test_rate = new LinkedList<String>(); LinkedList<Integer> statCurr_test_rank = new LinkedList<Integer>(); LinkedList<Integer> statTotal_test_rate_rank = new LinkedList<Integer>(); LinkedList<Integer> statCurr_in_test = new LinkedList<Integer>(); LinkedList<Integer> statCurr_out_test = new LinkedList<Integer>(); // 遍历实例装入对象 try { while(setStat.next()){ statQuery_date.add(setStat.getString("query_date")); statArea_id.add(setStat.getInt("area_id")); statArea_name.add(setStat.getString("areaname")); statTotal_workorder.add(setStat.getInt("total_workorder")); statCurr_workorder.add(setStat.getInt("curr_workorder")); statTotal_test.add(setStat.getInt("total_test")); statCurr_test.add(setStat.getInt("curr_test")); statTotal_test_rate.add(TotalRate(setStat.getString("total_test_rate"))); statCurr_test_rank.add(setStat.getInt("curr_test_rank")); statTotal_test_rate_rank.add(setStat.getInt("total_test_rate_rank")); statCurr_in_test.add(setStat.getInt("curr_in_test")); statCurr_out_test.add(setStat.getInt("curr_out_test")); } // 初始化eval的数组 int statSize = statArea_id.size(); stat.setQuery_date(new String[statSize]); stat.setArea_id(new Integer[statSize]); stat.setArea_name(new String[statSize]); stat.setTotal_workorder(new Integer[statSize]); stat.setCurr_workorder(new Integer[statSize]); stat.setTotal_test(new Integer[statSize]); stat.setCurr_test(new Integer[statSize]); stat.setTotal_test_rate(new String[statSize]); stat.setCurr_test_rank(new Integer[statSize]); stat.setTotal_test_rate_rank(new Integer[statSize]); stat.setCurr_in_test(new Integer[statSize]); stat.setCurr_out_test(new Integer[statSize]); // eval数组中放入数据 statQuery_date.toArray(stat.getQuery_date()); statArea_id.toArray(stat.getArea_id()); statArea_name.toArray(stat.getArea_name()); statTotal_workorder.toArray(stat.getTotal_workorder()); statCurr_workorder.toArray(stat.getCurr_workorder()); statTotal_test.toArray(stat.getTotal_test()); statCurr_test.toArray(stat.getCurr_test()); statTotal_test_rate.toArray(stat.getTotal_test_rate()); statCurr_test_rank.toArray(stat.getCurr_test_rank()); statTotal_test_rate_rank.toArray(stat.getTotal_test_rate_rank()); statCurr_in_test.toArray(stat.getCurr_in_test()); statCurr_out_test.toArray(stat.getCurr_out_test()); } catch (SQLException e) { e.printStackTrace(); } map.put("stat", stat); try { setStat.close(); } catch (SQLException e) { e.printStackTrace(); } return map; } public Map bottom(WebApplicationContext ctx ,Map<String,Object> params){ Map<String, Object> mapParam = new LinkedHashMap<String, Object>(); mapParam.put("type", params.get("type")); mapParam.put("starttime", params.get("starttime")); String reportdate = sysConfigService.getValue(Constant.REPORTDATE); mapParam.put("v_sys_time", reportdate); mapParam.put("endtime", params.get("endtime")); mapParam.put("queryAreaIds", params.get("queryAreaIds")); Map map = new HashMap(); // 查出评价数据 final String storedProcNameEval = "pro_cas_eval"; ResultSet setEval = this.getStoreProce(ctx,storedProcNameEval,mapParam); //ResultSet countEval = setEval; ComplainEvaluate eval = new ComplainEvaluate(); // 创建list对象 LinkedList<Integer> evalArea_id = new LinkedList<Integer>(); LinkedList<Integer> evalRscp_a = new LinkedList<Integer>(); LinkedList<Integer> evalRscp_b = new LinkedList<Integer>(); LinkedList<Integer> evalRscp_c = new LinkedList<Integer>(); LinkedList<Integer> evalRscp_d = new LinkedList<Integer>(); LinkedList<Integer> evalEc_no_a = new LinkedList<Integer>(); LinkedList<Integer> evalEc_no_b = new LinkedList<Integer>(); LinkedList<Integer> evalEc_no_c = new LinkedList<Integer>(); LinkedList<Integer> evalEc_no_d = new LinkedList<Integer>(); LinkedList<Integer> evalTxpower_a = new LinkedList<Integer>(); LinkedList<Integer> evalTxpower_b = new LinkedList<Integer>(); LinkedList<Integer> evalTxpower_c = new LinkedList<Integer>(); LinkedList<Integer> evalTxpower_d = new LinkedList<Integer>(); LinkedList<Integer> evalFtp_up_a = new LinkedList<Integer>(); LinkedList<Integer> evalFtp_up_b = new LinkedList<Integer>(); LinkedList<Integer> evalFtp_up_c = new LinkedList<Integer>(); LinkedList<Integer> evalFtp_up_d = new LinkedList<Integer>(); LinkedList<Integer> evalFtp_down_a = new LinkedList<Integer>(); LinkedList<Integer> evalFtp_down_b = new LinkedList<Integer>(); LinkedList<Integer> evalFtp_down_c = new LinkedList<Integer>(); LinkedList<Integer> evalFtp_down_d = new LinkedList<Integer>(); LinkedList<Integer> evalRxlev_a = new LinkedList<Integer>(); LinkedList<Integer> evalRxlev_b = new LinkedList<Integer>(); LinkedList<Integer> evalRxlev_c = new LinkedList<Integer>(); LinkedList<Integer> evalRxlev_d = new LinkedList<Integer>(); LinkedList<Integer> evalRxqual_a = new LinkedList<Integer>(); LinkedList<Integer> evalRxqual_b = new LinkedList<Integer>(); LinkedList<Integer> evalRxqual_c = new LinkedList<Integer>(); LinkedList<Integer> evalRxqual_d = new LinkedList<Integer>(); LinkedList<Integer> evalCi_a = new LinkedList<Integer>(); LinkedList<Integer> evalCi_b = new LinkedList<Integer>(); LinkedList<Integer> evalCi_c = new LinkedList<Integer>(); LinkedList<Integer> evalCi_d = new LinkedList<Integer>(); LinkedList<Integer> evalComp_eval_3g_a = new LinkedList<Integer>(); LinkedList<Integer> evalComp_eval_3g_b = new LinkedList<Integer>(); LinkedList<Integer> evalComp_eval_3g_c = new LinkedList<Integer>(); LinkedList<Integer> evalComp_eval_3g_d = new LinkedList<Integer>(); LinkedList<Integer> evalComp_eval_2g_a = new LinkedList<Integer>(); LinkedList<Integer> evalComp_eval_2g_b = new LinkedList<Integer>(); LinkedList<Integer> evalComp_eval_2g_c = new LinkedList<Integer>(); LinkedList<Integer> evalComp_eval_2g_d = new LinkedList<Integer>(); LinkedList<Integer> evalComp_impr_a = new LinkedList<Integer>(); LinkedList<Integer> evalComp_impr_b = new LinkedList<Integer>(); LinkedList<Integer> evalComp_impr_c = new LinkedList<Integer>(); LinkedList<Integer> evalComp_impr_d = new LinkedList<Integer>(); LinkedList<Double> evalComp_impr_value_3g = new LinkedList<Double>(); LinkedList<Double> evalComp_impr_value_2g = new LinkedList<Double>(); LinkedList<String> evalTimely_rate = new LinkedList<String>(); LinkedList<Integer> evalTimely_rate_rank = new LinkedList<Integer>(); // 遍历实例装入对象 try { while(setEval.next()){ evalArea_id.add(setEval.getInt("area_id")); evalRscp_a.add(setEval.getInt("rscp_a")); evalRscp_b.add(setEval.getInt("rscp_b")); evalRscp_c.add(setEval.getInt("rscp_c")); evalRscp_d.add(setEval.getInt("rscp_d")); evalEc_no_a.add(setEval.getInt("ec_no_a")); evalEc_no_b.add(setEval.getInt("ec_no_b")); evalEc_no_c.add(setEval.getInt("ec_no_c")); evalEc_no_d.add(setEval.getInt("ec_no_d")); evalTxpower_a.add(setEval.getInt("txpower_a")); evalTxpower_b.add(setEval.getInt("txpower_b")); evalTxpower_c.add(setEval.getInt("txpower_c")); evalTxpower_d.add(setEval.getInt("txpower_d")); evalFtp_up_a.add(setEval.getInt("ftp_up_a")); evalFtp_up_b.add(setEval.getInt("ftp_up_b")); evalFtp_up_c.add(setEval.getInt("ftp_up_c")); evalFtp_up_d.add(setEval.getInt("ftp_up_d")); evalFtp_down_a.add(setEval.getInt("ftp_down_a")); evalFtp_down_b.add(setEval.getInt("ftp_down_b")); evalFtp_down_c.add(setEval.getInt("ftp_down_c")); evalFtp_down_d.add(setEval.getInt("ftp_down_d")); evalRxlev_a.add(setEval.getInt("rxlev_a")); evalRxlev_b.add(setEval.getInt("rxlev_b")); evalRxlev_c.add(setEval.getInt("rxlev_c")); evalRxlev_d.add(setEval.getInt("rxlev_d")); evalRxqual_a.add(setEval.getInt("rxqual_a")); evalRxqual_b.add(setEval.getInt("rxqual_b")); evalRxqual_c.add(setEval.getInt("rxqual_c")); evalRxqual_d.add(setEval.getInt("rxqual_d")); evalCi_a.add(setEval.getInt("c_i_a")); evalCi_b.add(setEval.getInt("c_i_b")); evalCi_c.add(setEval.getInt("c_i_c")); evalCi_d.add(setEval.getInt("c_i_d")); evalComp_eval_3g_a.add(setEval.getInt("comp_eval_3g_a")); evalComp_eval_3g_b.add(setEval.getInt("comp_eval_3g_b")); evalComp_eval_3g_c.add(setEval.getInt("comp_eval_3g_c")); evalComp_eval_3g_d.add(setEval.getInt("comp_eval_3g_d")); evalComp_eval_2g_a.add(setEval.getInt("comp_eval_2g_a")); evalComp_eval_2g_b.add(setEval.getInt("comp_eval_2g_b")); evalComp_eval_2g_c.add(setEval.getInt("comp_eval_2g_c")); evalComp_eval_2g_d.add(setEval.getInt("comp_eval_2g_d")); evalComp_impr_a.add(setEval.getInt("comp_impr_a")); evalComp_impr_b.add(setEval.getInt("comp_impr_b")); evalComp_impr_c.add(setEval.getInt("comp_impr_c")); evalComp_impr_d.add(setEval.getInt("comp_impr_d")); evalComp_impr_value_3g.add(setEval.getDouble("comp_impr_3g_value")); evalComp_impr_value_2g.add(setEval.getDouble("comp_impr_2g_value")); evalTimely_rate.add(setEval.getString("timely_rate")); evalTimely_rate_rank.add(setEval.getInt("timely_rate_rank")); } // 根据areaid长度初始化数组 int evalSize = evalArea_id.size(); eval.setArea_id(new Integer[evalSize]); eval.setRscp_a(new Integer[evalSize]); eval.setRscp_b(new Integer[evalSize]); eval.setRscp_c(new Integer[evalSize]); eval.setRscp_d(new Integer[evalSize]); eval.setEc_no_a(new Integer[evalSize]); eval.setEc_no_b(new Integer[evalSize]); eval.setEc_no_c(new Integer[evalSize]); eval.setEc_no_d(new Integer[evalSize]); eval.setTxpower_a(new Integer[evalSize]); eval.setTxpower_b(new Integer[evalSize]); eval.setTxpower_c(new Integer[evalSize]); eval.setTxpower_d(new Integer[evalSize]); eval.setFtp_up_a(new Integer[evalSize]); eval.setFtp_up_b(new Integer[evalSize]); eval.setFtp_up_c(new Integer[evalSize]); eval.setFtp_up_d(new Integer[evalSize]); eval.setFtp_down_a(new Integer[evalSize]); eval.setFtp_down_b(new Integer[evalSize]); eval.setFtp_down_c(new Integer[evalSize]); eval.setFtp_down_d(new Integer[evalSize]); eval.setRxlev_a(new Integer[evalSize]); eval.setRxlev_b(new Integer[evalSize]); eval.setRxlev_c(new Integer[evalSize]); eval.setRxlev_d(new Integer[evalSize]); eval.setRxqual_a(new Integer[evalSize]); eval.setRxqual_b(new Integer[evalSize]); eval.setRxqual_c(new Integer[evalSize]); eval.setRxqual_d(new Integer[evalSize]); eval.setCi_a(new Integer[evalSize]); eval.setCi_b(new Integer[evalSize]); eval.setCi_c(new Integer[evalSize]); eval.setCi_d(new Integer[evalSize]); eval.setComp_eval_3g_a(new Integer[evalSize]); eval.setComp_eval_3g_b(new Integer[evalSize]); eval.setComp_eval_3g_c(new Integer[evalSize]); eval.setComp_eval_3g_d(new Integer[evalSize]); eval.setComp_eval_2g_a(new Integer[evalSize]); eval.setComp_eval_2g_b(new Integer[evalSize]); eval.setComp_eval_2g_c(new Integer[evalSize]); eval.setComp_eval_2g_d(new Integer[evalSize]); eval.setComp_impr_a(new Integer[evalSize]); eval.setComp_impr_b(new Integer[evalSize]); eval.setComp_impr_c(new Integer[evalSize]); eval.setComp_impr_d(new Integer[evalSize]); eval.setComp_impr_value_3g(new Double[evalSize]); eval.setComp_impr_ratio_2g(new String[evalSize]); eval.setComp_impr_ratio_3g(new String[evalSize]); eval.setComp_impr_value_2g(new Double[evalSize]); eval.setTimely_rate(new String[evalSize]); eval.setTimely_rate_rank(new Integer[evalSize]); // list 对象放入数组 evalArea_id.toArray(eval.getArea_id()); evalRscp_a.toArray(eval.getRscp_a()); evalRscp_b.toArray(eval.getRscp_b()); evalRscp_c.toArray(eval.getRscp_c()); evalRscp_d.toArray(eval.getRscp_d()); evalEc_no_a.toArray(eval.getEc_no_a()); evalEc_no_b.toArray(eval.getEc_no_b()); evalEc_no_c.toArray(eval.getEc_no_c()); evalEc_no_d.toArray(eval.getEc_no_d()); evalTxpower_a.toArray(eval.getTxpower_a()); evalTxpower_b.toArray(eval.getTxpower_b()); evalTxpower_c.toArray(eval.getTxpower_c()); evalTxpower_d.toArray(eval.getTxpower_d()); evalFtp_up_a.toArray(eval.getFtp_up_a()); evalFtp_up_b.toArray(eval.getFtp_up_b()); evalFtp_up_c.toArray(eval.getFtp_up_c()); evalFtp_up_d.toArray(eval.getFtp_up_d()); evalFtp_down_a.toArray(eval.getFtp_down_a()); evalFtp_down_b.toArray(eval.getFtp_down_b()); evalFtp_down_c.toArray(eval.getFtp_down_c()); evalFtp_down_d.toArray(eval.getFtp_down_d()); evalRxlev_a.toArray(eval.getRxlev_a()); evalRxlev_b.toArray(eval.getRxlev_b()); evalRxlev_c.toArray(eval.getRxlev_c()); evalRxlev_d.toArray(eval.getRxlev_d()); evalRxqual_a.toArray(eval.getRxqual_a()); evalRxqual_b.toArray(eval.getRxqual_b()); evalRxqual_c.toArray(eval.getRxqual_c()); evalRxqual_d.toArray(eval.getRxqual_d()); evalCi_a.toArray(eval.getCi_a()); evalCi_b.toArray(eval.getCi_b()); evalCi_c.toArray(eval.getCi_c()); evalCi_d.toArray(eval.getCi_d()); evalComp_eval_3g_a.toArray(eval.getComp_eval_3g_a()); evalComp_eval_3g_b.toArray(eval.getComp_eval_3g_b()); evalComp_eval_3g_c.toArray(eval.getComp_eval_3g_c()); evalComp_eval_3g_d.toArray(eval.getComp_eval_3g_d()); evalComp_eval_2g_a.toArray(eval.getComp_eval_2g_a()); evalComp_eval_2g_b.toArray(eval.getComp_eval_2g_b()); evalComp_eval_2g_c.toArray(eval.getComp_eval_2g_c()); evalComp_eval_2g_d.toArray(eval.getComp_eval_2g_d()); evalComp_impr_a.toArray(eval.getComp_impr_a()); evalComp_impr_b.toArray(eval.getComp_impr_b()); evalComp_impr_c.toArray(eval.getComp_impr_c()); evalComp_impr_d.toArray(eval.getComp_impr_d()); evalComp_impr_value_3g.toArray(eval.getComp_impr_value_3g()); evalComp_impr_value_2g.toArray(eval.getComp_impr_value_2g()); evalTimely_rate.toArray(eval.getTimely_rate()); evalTimely_rate_rank.toArray(eval.getTimely_rate_rank()); } catch (SQLException e) { e.printStackTrace(); }finally{ try { if(null != setEval){ setEval.close(); } } catch (SQLException e) { e.printStackTrace(); } } map.put("eval", eval); return map; } /** * 获取质量报表数据 * @param ctx * @param params * @return */ public QualtyReport getQualityReportData(WebApplicationContext ctx, Map<String, Object> params) { // 调用存储过程名称 final String storedProcName = "pr_wo_qual"; params.put("pistop", 0); QualtyReport qr = new QualtyReport(); ResultSet qual = this.getStoreProce(ctx, storedProcName, params); LinkedList<Integer> areaid = new LinkedList<Integer>(); LinkedList<String> areaname = new LinkedList<String>(); LinkedList<String> comp_score = new LinkedList<String>(); LinkedList<Integer> comp_score_rank = new LinkedList<Integer>(); // 投诉处理质量综合排名 LinkedList<String> assess_score = new LinkedList<String>(); // 移动网络服务考核得分 LinkedList<Integer> total_workorder = new LinkedList<Integer>(); // 累计需实测工单量 LinkedList<Integer> curr_workorder = new LinkedList<Integer>(); // 月需实测工单量 LinkedList<Integer> total_test = new LinkedList<Integer>(); // 累计实测量 LinkedList<Integer> curr_test = new LinkedList<Integer>(); // 月实测量 LinkedList<String> total_test_rate = new LinkedList<String>(); // 累计实测率 LinkedList<String> curr_test_timely = new LinkedList<String>(); // 月测试及时率 LinkedList<Integer> total_serialno = new LinkedList<Integer>(); // 累计网络投诉工单量 LinkedList<Integer> total_solve = new LinkedList<Integer>(); // 累计真正解决工单量 LinkedList<String> total_solve_rate = new LinkedList<String>(); // 累计真正解决率 LinkedList<Integer> curr_serialno = new LinkedList<Integer>();// 月网络投诉工单量 LinkedList<Integer> curr_solve = new LinkedList<Integer>();// 月真正解决工单量 LinkedList<Integer> total_major_solve = new LinkedList<Integer>(); // 累计优化真正解决量 LinkedList<String> total_major_solve_rate = new LinkedList<String>(); // 累计优化真正解决比 LinkedList<Integer> curr_major_solve = new LinkedList<Integer>(); // 月优化真正解决量 LinkedList<String> curr_major_solve_rate = new LinkedList<String>();// 月优化真正解决比 LinkedList<Integer> total_build_solve = new LinkedList<Integer>(); // 累计建设真正解决量 LinkedList<String> total_build_solve_rate = new LinkedList<String>(); // 累计建设真正解决比 LinkedList<Integer> curr_build_solve = new LinkedList<Integer>(); // 月建设真正解决量 LinkedList<String> curr_build_solve_rate = new LinkedList<String>();// 月建设真正解决比 LinkedList<Integer> total_maintain_solve = new LinkedList<Integer>(); // 累计维护真正解决量 LinkedList<String> total_maintain_solve_rate = new LinkedList<String>(); // 累计维护真正解决比 LinkedList<Integer> curr_maintain_solve = new LinkedList<Integer>(); // 月维护真正解决量 LinkedList<String> curr_maintain_solve_rate = new LinkedList<String>();// 月维护真正解决比 LinkedList<Integer> total_other_solve = new LinkedList<Integer>(); // 累计其它真正解决量 LinkedList<String> total_other_solve_rate = new LinkedList<String>(); ; // 累计其它真正解决比 LinkedList<Integer> curr_other_solve = new LinkedList<Integer>(); ; // 月其它真正解决量 LinkedList<String> curr_other_solve_rate = new LinkedList<String>(); ;// 月其它真正解决比 LinkedList<Integer> total_delay = new LinkedList<Integer>(); // 累计工单滞留量 LinkedList<String> total_delay_rate = new LinkedList<String>(); // 累计工单滞留率 LinkedList<Integer> total_major_delay = new LinkedList<Integer>(); // 累计优化工单滞留量 LinkedList<String> total_major_delay_rate = new LinkedList<String>();// 累计优化工单滞留比 LinkedList<Integer> total_build_delay = new LinkedList<Integer>(); // 累计建设工单滞留量 LinkedList<String> total_build_delay_rate = new LinkedList<String>();// 累计建设工单滞留比 LinkedList<Integer> total_maintain_delay = new LinkedList<Integer>(); // 累计维护工单滞留量 LinkedList<String> total_maintain_delay_rate = new LinkedList<String>();// 累计维护工单滞留比 LinkedList<Integer> total_reject = new LinkedList<Integer>(); // 累计工单驳回量 LinkedList<Integer> curr_reject = new LinkedList<Integer>(); // 月工单驳回量 LinkedList<String> total_reject_rate = new LinkedList<String>();// 累计工单驳回率 // LinkedList<String> curr_reject_rate = new LinkedList<String>(); // 月工单驳回率 LinkedList<Integer> total_major_reject = new LinkedList<Integer>(); // 累计优化工单驳回量 LinkedList<String> total_major_reject_rate = new LinkedList<String>();// 累计优化工单驳回比 LinkedList<Integer> curr_major_reject = new LinkedList<Integer>(); // 月优化工单驳回量 LinkedList<String> curr_major_reject_rate = new LinkedList<String>();// 月优化工单驳回比 LinkedList<Integer> total_build_reject = new LinkedList<Integer>(); // 累计建设工单驳回量 LinkedList<String> total_build_reject_rate = new LinkedList<String>();// 累计建设工单驳回比 LinkedList<Integer> curr_build_reject = new LinkedList<Integer>(); // 月建设工单驳回量 LinkedList<String> curr_build_reject_rate = new LinkedList<String>();// 月建设工单驳回比 LinkedList<Integer> total_maintain_reject = new LinkedList<Integer>(); // 累计维护工单驳回量 LinkedList<String> total_maintain_reject_rate = new LinkedList<String>();// 累计维护工单驳回比 LinkedList<Integer> curr_maintain_reject = new LinkedList<Integer>(); // 月维护工单驳回量 LinkedList<String> curr_maintain_reject_rate = new LinkedList<String>();// 月维护工单驳回比 LinkedList<Integer> total_over = new LinkedList<Integer>(); // 累计工单超时量 LinkedList<Integer> curr_over = new LinkedList<Integer>(); // 月工单超时量 LinkedList<String> total_over_rate = new LinkedList<String>(); // 累计工单超时率 LinkedList<Integer> total_send = new LinkedList<Integer>(); // 累计工单重复量 LinkedList<Integer> curr_send = new LinkedList<Integer>(); // 月工单重复量 LinkedList<String> total_send_rate = new LinkedList<String>(); // 累计工单重派率 LinkedList<Integer> total_upgrade = new LinkedList<Integer>(); // 累计工单升级量 LinkedList<Integer> curr_upgrade = new LinkedList<Integer>(); // 月工单升级量 LinkedList<String> total_upgrade_rate = new LinkedList<String>(); // 累计重复投诉率 LinkedList<Integer> total_complaint = new LinkedList<Integer>(); // 累计工单重复投诉量 LinkedList<Integer> curr_complaint = new LinkedList<Integer>(); // 月工单重复投诉量 LinkedList<String> total_complaint_rate = new LinkedList<String>(); // 累计工单升级率 LinkedList<Double> curr_wcdma_impr = new LinkedList<Double>(); // 月3G综合改善评分 LinkedList<Double> curr_gsm_impr = new LinkedList<Double>(); // 月2G综合改善评分 LinkedList<String> ratio_wcdma_impr = new LinkedList<String>(); // 月3G综合改善评分 LinkedList<String> ratio_gsm_impr = new LinkedList<String>(); // 月2G综合改善评分 // 遍历实例装入对象 try { while (qual.next()) { areaid.add(qual.getInt("area_id"));// 区域ID areaname.add(qual.getString("area_name"));// 区域名称 comp_score.add(qual.getString("comp_score")); // 投诉处理质量综合评分 comp_score_rank.add(qual.getString("comp_score_rank")==null?null:Integer.parseInt(qual.getString("comp_score_rank"))); // 投诉处理质量综合排名 assess_score.add(qual.getString("assess_score")); // 移动网络服务考核得分 total_workorder.add(qual.getInt("total_workorder")); // 累计需实测工单量 curr_workorder.add(qual.getInt("curr_workorder")); // 月需实测工单量 total_test.add(qual.getInt("total_test")); // 累计实测量 curr_test.add(qual.getInt("curr_test")); // 月实测量 total_test_rate.add(qual.getString("total_test_rate")); // 累计实测率 curr_test_timely.add(qual.getString("curr_test_timely")); // 月测试及时率 total_serialno.add(qual.getInt("total_serialno")); // 累计网络投诉工单量 total_solve.add(qual.getInt("total_solve")); // 累计真正解决工单量 total_solve_rate.add(qual.getString("total_solve_rate")); // 累计真正解决率 curr_serialno.add(qual.getInt("curr_serialno"));// 月网络投诉工单量 curr_solve.add(qual.getInt("curr_solve")); // 月真正解决工单量 total_major_solve.add(qual.getInt("total_major_solve")); // 累计优化真正解决量 total_major_solve_rate.add(qual.getString("total_major_solve_rate")); // 累计优化真正解决比 curr_major_solve.add(qual.getInt("curr_major_solve")); // 月优化真正解决量 curr_major_solve_rate.add(qual .getString("curr_major_solve_rate"));// 月优化真正解决比 total_build_solve.add(qual.getInt("total_build_solve")); // 累计建设真正解决量 total_build_solve_rate.add(qual .getString("total_build_solve_rate")); // 累计建设真正解决比 curr_build_solve.add(qual.getInt("curr_build_solve")); // 月建设真正解决量 curr_build_solve_rate.add(qual .getString("curr_build_solve_rate"));// 月建设真正解决比 total_maintain_solve.add(qual.getInt("total_maintain_solve")); // 累计维护真正解决量 total_maintain_solve_rate.add(qual .getString("total_maintain_solve_rate")); // 累计维护真正解决比 curr_maintain_solve.add(qual.getInt("curr_maintain_solve")); // 月维护真正解决量 curr_maintain_solve_rate.add(qual .getString("curr_maintain_solve_rate"));// 月维护真正解决比 total_other_solve.add(qual.getInt("total_other_solve")); // 累计其它真正解决量 total_other_solve_rate.add(qual.getString("total_other_solve_rate")); // 累计其它真正解决比 curr_other_solve.add(qual.getInt("curr_other_solve")); // 月其它真正解决量 curr_other_solve_rate.add(qual.getString("curr_other_solve_rate"));// 月其它真正解决比 total_delay.add(qual.getInt("total_delay")); // 累计工单滞留量 total_delay_rate.add(qual.getString("total_delay_rate")); // 累计工单滞留率 total_major_delay.add(qual.getInt("total_major_delay")); // 累计优化工单滞留量 total_major_delay_rate.add(qual .getString("total_major_delay_rate"));// 累计优化工单滞留比 total_build_delay.add(qual.getInt("total_build_delay")); // 累计建设工单滞留量 total_build_delay_rate.add(qual .getString("total_build_delay_rate"));// 累计建设工单滞留比 total_maintain_delay.add(qual.getInt("total_maintain_delay")); // 累计维护工单滞留量 total_maintain_delay_rate.add(qual .getString("total_maintain_delay_rate"));// 累计维护工单滞留比 total_reject.add(qual.getInt("total_reject")); // 累计工单驳回量 curr_reject.add(qual.getInt("curr_reject")); // 月工单驳回量 total_reject_rate.add(qual.getString("total_reject_rate"));// 累计工单驳回率 // curr_reject_rate.add(qual.getString("curr_reject_rate")); // 月工单驳回率 total_major_reject.add(qual.getInt("total_major_reject")); // 累计优化工单驳回量 total_major_reject_rate.add(qual .getString("total_major_reject_rate"));// 累计优化工单驳回比 curr_major_reject.add(qual.getInt("curr_major_reject")); // 月优化工单驳回量 curr_major_reject_rate.add(qual .getString("curr_major_reject_rate"));// 月优化工单驳回比 total_build_reject.add(qual.getInt("total_build_reject")); // 累计建设工单驳回量 total_build_reject_rate.add(qual .getString("total_build_reject_rate"));// 累计建设工单驳回比 curr_build_reject.add(qual.getInt("curr_build_reject")); // 月建设工单驳回量 curr_build_reject_rate.add(qual .getString("curr_build_reject_rate"));// 月建设工单驳回比 total_maintain_reject.add(qual.getInt("total_maintain_reject")); // 累计维护工单驳回量 total_maintain_reject_rate.add(qual .getString("total_maintain_reject_rate"));// 累计维护工单驳回比 curr_maintain_reject.add(qual.getInt("curr_maintain_reject")); // 月维护工单驳回量 curr_maintain_reject_rate.add(qual .getString("curr_maintain_reject_rate"));// 月维护工单驳回比 total_over.add(qual.getInt("total_over")); // 累计工单超时量 curr_over.add(qual.getInt("curr_over")); // 月工单超时量 total_over_rate.add(qual.getString("total_over_rate")); // 累计工单超时率 total_send.add(qual.getInt("total_send")); // 累计工单重复量 curr_send.add(qual.getInt("curr_send")); // 月工单重复量 total_send_rate.add(qual.getString("total_send_rate")); // 累计工单重派率 total_upgrade.add(qual.getInt("total_upgrade")); // 累计工单升级量 curr_upgrade.add(qual.getInt("curr_upgrade")); // 月工单升级量 total_upgrade_rate.add(qual.getString("total_upgrade_rate")); // 累计重复投诉率 total_complaint.add(qual.getInt("total_complaint")); // 累计工单重复投诉量 curr_complaint.add(qual.getInt("curr_complaint")); // 月工单重复投诉量 total_complaint_rate .add(qual.getString("total_complaint_rate")); // 累计工单升级率 curr_wcdma_impr.add(qual.getDouble("curr_wcdma_impr")); // 月3G综合改善评分 curr_gsm_impr.add(qual.getDouble("curr_gsm_impr")); // 月2G综合改善评分 if(qual.getInt("total_serialno")>0){ double val3g = qual.getDouble("curr_wcdma_impr"); double val2g = qual.getDouble("curr_gsm_impr"); ratio_wcdma_impr.add(PatternUtil.getDouble((double)((val3g*100000/qual.getInt("total_serialno"))/1000))); ratio_gsm_impr.add(PatternUtil.getDouble((double)((val2g*100000/qual.getInt("total_serialno"))/1000))); }else{ ratio_wcdma_impr.add("0%"); ratio_gsm_impr.add("0%"); } } // 根据areaid长度初始化数组 int size = areaid.size(); qr.setAreaid(new Integer[size]); qr.setAreaname(new String[size]);// 区域名称 qr.setComp_score(new String[size]); // 投诉处理质量综合评分 qr.setComp_score_rank(new Integer[size]); // 投诉处理质量综合排名 qr.setAssess_score(new String[size]); // 移动网络服务考核得分 qr.setTotal_workorder(new Integer[size]); // 累计需实测工单量 qr.setCurr_workorder(new Integer[size]); // 月需实测工单量 qr.setTotal_test(new Integer[size]); // 累计实测量 qr.setCurr_test(new Integer[size]); // 月实测量 qr.setTotal_test_rate(new String[size]); // 累计实测率 qr.setCurr_test_timely(new String[size]); // 月测试及时率 qr.setTotal_serialno(new Integer[size]); // 累计网络投诉工单量 qr.setTotal_solve(new Integer[size]); // 累计真正解决工单量 qr.setTotal_solve_rate(new String[size]); // 累计真正解决率 qr.setCurr_serialno(new Integer[size]);// 月网络投诉工单量 qr.setCurr_solve(new Integer[size]); // 月真正解决工单量 qr.setTotal_major_solve(new Integer[size]); // 累计优化真正解决量 qr.setTotal_major_solve_rate(new String[size]); // 累计优化真正解决比 qr.setCurr_major_solve(new Integer[size]); // 月优化真正解决量 qr.setCurr_major_solve_rate(new String[size]);// 月优化真正解决比 qr.setTotal_build_solve(new Integer[size]); // 累计建设真正解决量 qr.setTotal_build_solve_rate(new String[size]); // 累计建设真正解决比 qr.setCurr_build_solve(new Integer[size]); // 月建设真正解决量 qr.setCurr_build_solve_rate(new String[size]);// 月建设真正解决比 qr.setTotal_maintain_solve(new Integer[size]); // 累计维护真正解决量 qr.setTotal_maintain_solve_rate(new String[size]); // 累计维护真正解决比 qr.setCurr_maintain_solve(new Integer[size]); // 月维护真正解决量 qr.setCurr_maintain_solve_rate(new String[size]);// 月维护真正解决比 qr.setTotal_other_solve(new Integer[size]); // 累计其它真正解决量 qr.setTotal_other_solve_rate(new String[size]); // 累计其它真正解决比 qr.setCurr_other_solve(new Integer[size]);// 月其它真正解决量 qr.setCurr_other_solve_rate(new String[size]);// 月其它真正解决比 qr.setTotal_delay(new Integer[size]); // 累计工单滞留量 qr.setTotal_delay_rate(new String[size]); // 累计工单滞留率 qr.setTotal_major_delay(new Integer[size]); // 累计优化工单滞留量 qr.setTotal_major_delay_rate(new String[size]);// 累计优化工单滞留比 qr.setTotal_build_delay(new Integer[size]); // 累计建设工单滞留量 qr.setTotal_build_delay_rate(new String[size]);// 累计建设工单滞留比 qr.setTotal_maintain_delay(new Integer[size]); // 累计维护工单滞留量 qr.setTotal_maintain_delay_rate(new String[size]);// 累计维护工单滞留比 qr.setTotal_reject(new Integer[size]); // 累计工单驳回量 qr.setCurr_reject(new Integer[size]); // 月工单驳回量 qr.setTotal_reject_rate(new String[size]);// 累计工单驳回率 qr.setCurr_reject_rate(new String[size]); // 月工单驳回率 qr.setTotal_major_reject(new Integer[size]); // 累计优化工单驳回量 qr.setTotal_major_reject_rate(new String[size]);// 累计优化工单驳回比 qr.setCurr_major_reject(new Integer[size]); // 月优化工单驳回量 qr.setCurr_major_reject_rate(new String[size]);// 月优化工单驳回比 qr.setTotal_build_reject(new Integer[size]); // 累计建设工单驳回量 qr.setTotal_build_reject_rate(new String[size]);// 累计建设工单驳回比 qr.setCurr_build_reject(new Integer[size]); // 月建设工单驳回量 qr.setCurr_build_reject_rate(new String[size]);// 月建设工单驳回比 qr.setTotal_maintain_reject(new Integer[size]); // 累计维护工单驳回量 qr.setTotal_maintain_reject_rate(new String[size]);// 累计维护工单驳回比 qr.setCurr_maintain_reject(new Integer[size]); // 月维护工单驳回量 qr.setCurr_maintain_reject_rate(new String[size]);// 月维护工单驳回比 qr.setTotal_over(new Integer[size]); // 累计工单超时量 qr.setCurr_over(new Integer[size]); // 月工单超时量 qr.setTotal_over_rate(new String[size]); // 累计工单超时率 qr.setTotal_send(new Integer[size]); // 累计工单重复量 qr.setCurr_send(new Integer[size]); // 月工单重复量 qr.setTotal_send_rate(new String[size]); // 累计工单重派率 qr.setTotal_upgrade(new Integer[size]); // 累计工单升级量 qr.setCurr_upgrade(new Integer[size]); // 月工单升级量 qr.setTotal_upgrade_rate(new String[size]); // 累计重复投诉率 qr.setTotal_complaint(new Integer[size]); // 累计工单重复投诉量 qr.setCurr_complaint(new Integer[size]); // 月工单重复投诉量 qr.setTotal_complaint_rate(new String[size]); // 累计工单升级率 qr.setCurr_wcdma_impr(new Double[size]); // 月3G综合改善评分 qr.setCurr_gsm_impr(new Double[size]); // 月2G综合改善评分 qr.setRatio_wcdma_impr(new String[size]); // 月3G综合改善比例 qr.setRatio_gsm_impr(new String[size]); // 月2G综合改善比例 // 数据转换 areaid.toArray(qr.getAreaid());// 区域id areaname.toArray(qr.getAreaname());// 区域名称 comp_score.toArray(qr.getComp_score()); // 投诉处理质量综合评分 comp_score_rank.toArray(qr.getComp_score_rank()); // 投诉处理质量综合排名 assess_score.toArray(qr.getAssess_score()); // 移动网络服务考核得分 total_workorder.toArray(qr.getTotal_workorder()); // 累计需实测工单量 curr_workorder.toArray(qr.getCurr_workorder()); // 月需实测工单量 total_test.toArray(qr.getTotal_test()); // 累计实测量 curr_test.toArray(qr.getCurr_test()); // 月实测量 total_test_rate.toArray(qr.getTotal_test_rate()); // 累计实测率 curr_test_timely.toArray(qr.getCurr_test_timely()); // 月测试及时率 total_serialno.toArray(qr.getTotal_serialno()); // 累计网络投诉工单量 total_solve.toArray(qr.getTotal_solve()); // 累计真正解决工单量 total_solve_rate.toArray(qr.getTotal_solve_rate()); // 累计真正解决率 curr_serialno.toArray(qr.getCurr_serialno());// 月网络投诉工单量 curr_solve.toArray(qr.getCurr_solve()); // 月真正解决工单量 total_major_solve.toArray(qr.getTotal_major_solve()); // 累计优化真正解决量 total_major_solve_rate.toArray(qr.getTotal_major_solve_rate()); // 累计优化真正解决比 curr_major_solve.toArray(qr.getCurr_major_solve()); // 月优化真正解决量 curr_major_solve_rate.toArray(qr.getCurr_major_solve_rate());// 月优化真正解决比 total_build_solve.toArray(qr.getTotal_build_solve()); // 累计建设真正解决量 total_build_solve_rate.toArray(qr.getTotal_build_solve_rate()); // 累计建设真正解决比 curr_build_solve.toArray(qr.getCurr_build_solve()); // 月建设真正解决量 curr_build_solve_rate.toArray(qr.getCurr_build_solve_rate());// 月建设真正解决比 total_maintain_solve.toArray(qr.getTotal_maintain_solve()); // 累计维护真正解决量 total_maintain_solve_rate .toArray(qr.getTotal_maintain_solve_rate()); // 累计维护真正解决比 curr_maintain_solve.toArray(qr.getCurr_maintain_solve()); // 月维护真正解决量 curr_maintain_solve_rate.toArray(qr.getCurr_maintain_solve_rate());// 月维护真正解决比 total_other_solve.toArray(qr.getTotal_other_solve());// 累计其它真正解决量 total_other_solve_rate.toArray(qr.getTotal_other_solve_rate());// 累计其它真正解决比 curr_other_solve.toArray(qr.getCurr_other_solve()); // 月其它真正解决量 curr_other_solve_rate.toArray(qr.getCurr_other_solve_rate());// 月其它真正解决比 total_delay.toArray(qr.getTotal_delay()); // 累计工单滞留量 total_delay_rate.toArray(qr.getTotal_delay_rate()); // 累计工单滞留率 total_major_delay.toArray(qr.getTotal_major_delay()); // 累计优化工单滞留量 total_major_delay_rate.toArray(qr.getTotal_major_delay_rate());// 累计优化工单滞留比 total_build_delay.toArray(qr.getTotal_build_delay()); // 累计建设工单滞留量 total_build_delay_rate.toArray(qr.getTotal_build_delay_rate());// 累计建设工单滞留比 total_maintain_delay.toArray(qr.getTotal_maintain_delay()); // 累计维护工单滞留量 total_maintain_delay_rate.toArray(qr.getTotal_maintain_delay_rate());// 累计维护工单滞留比 total_reject.toArray(qr.getTotal_reject()); // 累计工单驳回量 curr_reject.toArray(qr.getCurr_reject()); // 月工单驳回量 total_reject_rate.toArray(qr.getTotal_reject_rate());// 累计工单驳回率 // curr_reject_rate.toArray(qr.getCurr_reject_rate()); // 月工单驳回率 total_major_reject.toArray(qr.getTotal_major_reject()); // 累计优化工单驳回量 total_major_reject_rate.toArray(qr.getTotal_major_reject_rate());// 累计优化工单驳回比 curr_major_reject.toArray(qr.getCurr_major_reject()); // 月优化工单驳回量 curr_major_reject_rate.toArray(qr.getCurr_major_reject_rate());// 月优化工单驳回比 total_build_reject.toArray(qr.getTotal_build_reject()); // 累计建设工单驳回量 total_build_reject_rate.toArray(qr.getTotal_build_reject_rate());// 累计建设工单驳回比 curr_build_reject.toArray(qr.getCurr_build_reject()); // 月建设工单驳回量 curr_build_reject_rate.toArray(qr.getCurr_build_reject_rate());// 月建设工单驳回比 total_maintain_reject.toArray(qr.getTotal_maintain_reject()); // 累计维护工单驳回量 total_maintain_reject_rate.toArray(qr .getTotal_maintain_reject_rate());// 累计维护工单驳回比 curr_maintain_reject.toArray(qr.getCurr_maintain_reject()); // 月维护工单驳回量 curr_maintain_reject_rate .toArray(qr.getCurr_maintain_reject_rate());// 月维护工单驳回比 total_over.toArray(qr.getTotal_over()); // 累计工单超时量 curr_over.toArray(qr.getCurr_over()); // 月工单超时量 total_over_rate.toArray(qr.getTotal_over_rate()); // 累计工单超时率 total_send.toArray(qr.getTotal_send()); // 累计工单重复量 curr_send.toArray(qr.getCurr_send()); // 月工单重复量 total_send_rate.toArray(qr.getTotal_send_rate()); // 累计工单重派率 total_upgrade.toArray(qr.getTotal_upgrade()); // 累计工单升级量 curr_upgrade.toArray(qr.getCurr_upgrade()); // 月工单升级量 total_upgrade_rate.toArray(qr.getTotal_upgrade_rate()); // 累计重复投诉率 total_complaint.toArray(qr.getTotal_complaint()); // 累计工单重复投诉量 curr_complaint.toArray(qr.getCurr_complaint()); // 月工单重复投诉量 total_complaint_rate.toArray(qr.getTotal_complaint_rate()); // 累计工单升级率 curr_wcdma_impr.toArray(qr.getCurr_wcdma_impr()); // 月3G综合改善评分 curr_gsm_impr.toArray(qr.getCurr_gsm_impr()); // 月2G综合改善评分 ratio_wcdma_impr.toArray(qr.getRatio_wcdma_impr()); // 月3G综合改善比例 ratio_gsm_impr.toArray(qr.getRatio_gsm_impr()); // 月2G综合改善比例 } catch (SQLException e) { e.printStackTrace(); logger.error("", e); }finally{ try { if(null != qual){ qual.close(); } } catch (SQLException e) { e.printStackTrace(); logger.error("", e); } } return qr; } /** * 查询top last * @param ctx * @param params * @return */ public Map<String,QualTopAndLast> getTopAndLast(WebApplicationContext ctx, Map<String, Object> params){ QualTopAndLast top5 = new QualTopAndLast(); QualTopAndLast top1 = new QualTopAndLast(); final String storedProcName = "pr_wo_qual_top"; ResultSet rs = this.getStoreProce(ctx, storedProcName, params); int tid = 0; try { while (rs.next()) { tid = rs.getInt("tid"); switch (tid) { case 0: // comp_score_max top5.setComp_score_max(rs.getString("top5"));//投诉处理质量综合评分top5 top5.setComp_score_min(rs.getString("last5"));//投诉处理质量综合评分top5 top1.setComp_score_max(rs.getString("top1"));//投诉处理质量综合评分top1 top1.setComp_score_min(rs.getString("last1"));//投诉处理质量综合评分top1 break; case 1: top5.setTotal_max_rate(rs.getString("top5"));//累计实测率top5 top5.setTotal_min_rate(rs.getString("last5"));//累计实测率top5 top1.setTotal_max_rate(rs.getString("top1"));//累计实测率top1 top1.setTotal_min_rate(rs.getString("last1"));//累计实测率top1 break; case 2: top5.setCurr_test_timely_max(rs.getString("top5"));//测试及时率top5 top5.setCurr_test_timely_min(rs.getString("last5"));//测试及时率top5 top1.setCurr_test_timely_max(rs.getString("top1"));//测试及时率top1 top1.setCurr_test_timely_min(rs.getString("last1"));//测试及时率top1 break; case 3: top5.setTotal_solve_rate_max(rs.getString("top5"));//累计解决率top5 top5.setTotal_solve_rate_min(rs.getString("last5"));//累计解决率top5 top1.setTotal_solve_rate_max(rs.getString("top1"));//累计解决率top1 top1.setTotal_solve_rate_min(rs.getString("last1"));//累计解决率top1 break; case 4: top5.setTotal_delay_rate_max(rs.getString("top5"));//累计工单滞留率top5 top5.setTotal_delay_rate_min(rs.getString("last5"));//累计工单滞留率top5 top1.setTotal_delay_rate_max(rs.getString("top1"));//累计工单滞留率top1 top1.setTotal_delay_rate_min(rs.getString("last1"));//累计工单滞留率top1 break; case 5: top5.setTotal_reject_rate_max(rs.getString("top5"));//累计工单驳回率top5 top5.setTotal_reject_rate_min(rs.getString("last5"));//累计工单驳回率top5 top1.setTotal_reject_rate_max(rs.getString("top1"));//累计工单驳回率top1 top1.setTotal_reject_rate_min(rs.getString("last1"));//累计工单驳回率top1 break; case 6: top5.setTotal_over_rate_max(rs.getString("top5"));//累计工单超时率top5 top5.setTotal_over_rate_min(rs.getString("last5"));//累计工单超时率top5 top1.setTotal_over_rate_max(rs.getString("top1"));//累计工单超时率top1 top1.setTotal_over_rate_min(rs.getString("last1"));//累计工单超时率top1 break; case 7: top5.setTotal_send_rate_max(rs.getString("top5"));//累计工单重派率top5 top5.setTotal_send_rate_min(rs.getString("last5"));//累计工单重派率top5 top1.setTotal_send_rate_max(rs.getString("top1"));//累计工单重派率top1 top1.setTotal_send_rate_min(rs.getString("last1"));//累计工单重派率top1 break; case 8: top5.setTotal_complaint_rate_max(rs.getString("top5"));//累计重复投诉率top5 top5.setTotal_complaint_rate_min(rs.getString("last5"));//累计重复投诉率top5 top1.setTotal_complaint_rate_max(rs.getString("top1"));//累计重复投诉率top1 top1.setTotal_complaint_rate_min(rs.getString("last1"));//累计重复投诉率top1 break; case 9: top5.setTotal_upgrade_rate_max(rs.getString("top5"));//累计工单升级率top5 top5.setTotal_upgrade_rate_min(rs.getString("last5"));//累计工单升级率top5 top1.setTotal_upgrade_rate_max(rs.getString("top1"));//累计工单升级率top1 top1.setTotal_upgrade_rate_min(rs.getString("last1"));//累计工单升级率top1 break; default: break; } } } catch (Exception e) { logger.error("", e); }finally{ try { if(rs != null){ rs.close(); } } catch (Exception e) { logger.error("", e); } } Map<String,QualTopAndLast> map = new HashMap<String, QualTopAndLast>(); map.put("top5", top5); map.put("top1", top1); return map; } } <file_sep>/src/main/webapp/js/epinfo/epinfomore.js function epinfomore(){ var selectoption = ""; for(var i = 0;i<areaopid.length;i++){ selectoption +="<option value="+areaopid[i]+">"+areaopname[i]+"</option>"; } var more = "<ul style='float:left;'>"+ "<li class=\"fl\"><span class=\"fls\"><samp style=\"color:red\">*</samp>区域选择:</span>"+ "<p class=\"flp flp-ts\">"+ "<select name = \"areaid\" class=\"easyui-combobox\" style=\"border:1px solid #D3D3D3;height:20px;width:80px;\" data-options=\"editable:false,float:'left'\">"+ selectoption+ "</select>"+ "</p>"+ "</li>"+ "<li class=\"fl\"><span class=\"fls\"><samp style=\"color:red\">*</samp>UUID:</span>"+ "<p class=\"flp\">"+ "<input name=\"uuid\" type=\"text\" uuid=\"uuid\" class=\"chkent qer easyui-validatebox\" style=\"width:130px;height:20px;border:1px solid #D3D3D3;\" data-options=\"required:true,validType:['uuid','remote[\\'"+contextPath+"/epinfo/uuidIsExsit\\',\\'uuid\\',\\'\\',\\'UUID\\']','equalsArray[\\'uuid\\',\\'uuid\\',\\'UUID\\']']\" maxlength=\"15\"/>"+ "</p>"+ "</li>"+ "<li class=\"fl\"><span class=\"fls\"><samp style=\"color:red\">*</samp>联系人:</span>"+ "<p class=\"flp\">"+ "<input name=\"functionary\" type=\"text\" class=\"chkenter easyui-validatebox\" style=\"width:60px;height:20px;border:1px solid #D3D3D3;\" data-options=\"required:true,validType:['functionary']\" maxlength=\"12\"/>"+ "</p>"+ "</li>"+ "<li class=\"fl\"><span class=\"fls\"><samp style=\"color:red\">*</samp>联系电话:</span>"+ "<p class=\"flp\">"+ "<input name=\"teltphone\" type=\"text\" class=\"chkenter easyui-validatebox\" style=\"width:100px;height:20px;border:1px solid #D3D3D3;\" data-options=\"required:true,validType:['teltphone']\" maxlength=\"12\" />"+ "</p>"+ "</li>"+ "<li class=\"fl\">"+ "<a name=\"add\" class=\"change\"><img src=\""+contextPath+"/images/add.png\" title=\"点击可以连续添加\"/></a>"+ "<a name=\"del\" class=\"change\"><img src=\""+contextPath+"/images/del.png\" title=\"删除当前行\"/></a>"+ "</li>"+ "</ul>"; return more }<file_sep>/src/main/java/com/complaint/model/GwCasCell.java package com.complaint.model; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; public class GwCasCell { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.CID * * @mbggenerated */ private BigDecimal cid; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.LAC * * @mbggenerated */ private BigDecimal lac; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.CITY_NAME * * @mbggenerated */ private String cityName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.ADMIN_REGION * * @mbggenerated */ private String adminRegion; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.AREA_ID * * @mbggenerated */ private BigDecimal areaId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.BID * * @mbggenerated */ private String bid; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.BASE_NAME * * @mbggenerated */ private String baseName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.CELL_NAME * * @mbggenerated */ private String cellName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.LONGITUDE * * @mbggenerated */ private BigDecimal longitude; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.LATITUDE * * @mbggenerated */ private BigDecimal latitude; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.LONGITUDE_MODIFY * * @mbggenerated */ private BigDecimal longitudeModify; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.LATITUDE_MODIFY * * @mbggenerated */ private BigDecimal latitudeModify; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.PSC * * @mbggenerated */ private BigDecimal psc; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SELF_AZIMUTH * * @mbggenerated */ private BigDecimal selfAzimuth; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.MODE_TYPE * * @mbggenerated */ private int modeType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.INDOOR * * @mbggenerated */ private Short indoor; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.ANT_TYPE * * @mbggenerated */ private String antType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.ANT_AZIMUTH * * @mbggenerated */ private BigDecimal antAzimuth; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.ANT_HIGH * * @mbggenerated */ private BigDecimal antHigh; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.ANT_ELECT_ANGLE * * @mbggenerated */ private BigDecimal antElectAngle; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.ANT_MACH_ANGLE * * @mbggenerated */ private BigDecimal antMachAngle; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SHARED_ANT * * @mbggenerated */ private String sharedAnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.BASE_ADDRESS * * @mbggenerated */ private String baseAddress; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.ALTITUDE * * @mbggenerated */ private BigDecimal altitude; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.DEV_VENDOR * * @mbggenerated */ private String devVendor; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.TOWER_MAST_TYPE * * @mbggenerated */ private String towerMastType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.DEV_TYPE * * @mbggenerated */ private String devType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.BASE_CONF * * @mbggenerated */ private String baseConf; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.PROGRESS * * @mbggenerated */ private String progress; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.COVER_RANGE * * @mbggenerated */ private String coverRange; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.COVER_TYPE * * @mbggenerated */ private String coverType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.RRU_CELL_BOOL * * @mbggenerated */ private String rruCellBool; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.CELL_ID * * @mbggenerated */ private BigDecimal cellId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.REPEATER_CNT * * @mbggenerated */ private BigDecimal repeaterCnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SHARED_ANT_CELL * * @mbggenerated */ private String sharedAntCell; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SHARED_ANT_CELL_BAK * * @mbggenerated */ private String sharedAntCellBak; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SHARED_ANT_PROP * * @mbggenerated */ private String sharedAntProp; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SHARED_BASE_NAME * * @mbggenerated */ private String sharedBaseName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SHARED_BASE_PROP * * @mbggenerated */ private String sharedBaseProp; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.NETMAN_STAT * * @mbggenerated */ private String netmanStat; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.ADMIN_REGION_TYPE * * @mbggenerated */ private String adminRegionType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.UP_FREQ * * @mbggenerated */ private Integer upFreq; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.DOWN_FREQ * * @mbggenerated */ private Integer downFreq; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.RNC_NAME * * @mbggenerated */ private String rncName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.NE_TYPE * * @mbggenerated */ private String neType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.ANT_POWER * * @mbggenerated */ private BigDecimal antPower; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.TILT * * @mbggenerated */ private BigDecimal tilt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.ESC_BOOL * * @mbggenerated */ private String escBool; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.BASE_TYPE * * @mbggenerated */ private String baseType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.RRU_CNT * * @mbggenerated */ private BigDecimal rruCnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.LOGIC_CELL_LEVEL * * @mbggenerated */ private String logicCellLevel; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SECTOR_WIFI_CAPAC * * @mbggenerated */ private BigDecimal sectorWifiCapac; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.E1_CNT * * @mbggenerated */ private BigDecimal e1Cnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.FE_CNT * * @mbggenerated */ private BigDecimal feCnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.TRANSMISSION * * @mbggenerated */ private String transmission; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.CQ_AREA_COVER * * @mbggenerated */ private String cqAreaCover; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WIFI_CAPAC * * @mbggenerated */ private BigDecimal wifiCapac; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.BASE_MAX_POWER * * @mbggenerated */ private BigDecimal baseMaxPower; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.INNER_TILT * * @mbggenerated */ private BigDecimal innerTilt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.OFF_SERVICE_TIME * * @mbggenerated */ private Date offServiceTime; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.DOWN_MAX_POWER * * @mbggenerated */ private BigDecimal downMaxPower; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SCENE_A * * @mbggenerated */ private String sceneA; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SCENE_B * * @mbggenerated */ private String sceneB; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.TOWN_BOOL * * @mbggenerated */ private String townBool; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.HSDPA_BOOL * * @mbggenerated */ private String hsdpaBool; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.HSDPA_STAT * * @mbggenerated */ private String hsdpaStat; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.HS_PDSCH_CODE * * @mbggenerated */ private String hsPdschCode; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.BROADCAST_CHANN_POWER * * @mbggenerated */ private BigDecimal broadcastChannPower; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.HSUPA_BOOL * * @mbggenerated */ private String hsupaBool; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.HSUPA_STAT * * @mbggenerated */ private String hsupaStat; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.MBMS_BOOL * * @mbggenerated */ private String mbmsBool; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.MBMS_STAT * * @mbggenerated */ private String mbmsStat; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.MICH_CHANN_CNT * * @mbggenerated */ private BigDecimal michChannCnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SF16_CODE_CNT * * @mbggenerated */ private BigDecimal sf16CodeCnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SF128_CODE_CNT * * @mbggenerated */ private BigDecimal sf128CodeCnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.E_AGCH_CHANN_CNT * * @mbggenerated */ private BigDecimal eAgchChannCnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.E_RGCH_E_HICH_CHANN_CNT * * @mbggenerated */ private BigDecimal eRgchEHichChannCnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.PCPICH_CHANN_MAX_POWER * * @mbggenerated */ private BigDecimal pcpichChannMaxPower; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.PCPICH_CHANN_MIN_POWER * * @mbggenerated */ private BigDecimal pcpichChannMinPower; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.DOMIN_FREQ_CHANN_POWER * * @mbggenerated */ private BigDecimal dominFreqChannPower; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SYNC_CHANN_DOWN_POWER * * @mbggenerated */ private BigDecimal syncChannDownPower; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SINGLE_CARR_FREQ_MAX_USER * * @mbggenerated */ private BigDecimal singleCarrFreqMaxUser; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.CARR_FREQ_POWER * * @mbggenerated */ private BigDecimal carrFreqPower; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.UP_CE_CAPAC * * @mbggenerated */ private BigDecimal upCeCapac; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.DOWN_CE_CAPAC * * @mbggenerated */ private BigDecimal downCeCapac; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.IUB_ATM_BANDWIDTH * * @mbggenerated */ private BigDecimal iubAtmBandwidth; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.IUB_IP_BANDWIDTH * * @mbggenerated */ private BigDecimal iubIpBandwidth; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.IU_ATM_BANDWIDTH * * @mbggenerated */ private BigDecimal iuAtmBandwidth; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.IU_IP_BANDWIDTH * * @mbggenerated */ private BigDecimal iuIpBandwidth; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.IUR_ATM_BANDWIDTH * * @mbggenerated */ private BigDecimal iurAtmBandwidth; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.IUR_IP_BANDWIDTH * * @mbggenerated */ private BigDecimal iurIpBandwidth; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.REMARK * * @mbggenerated */ private String remark; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.LAST_UPDATE_TIME * * @mbggenerated */ private Date lastUpdateTime; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.RAC * * @mbggenerated */ private BigDecimal rac; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SAC * * @mbggenerated */ private BigDecimal sac; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.RNC_ID * * @mbggenerated */ private BigDecimal rncId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.BASE_ID * * @mbggenerated */ private BigDecimal baseId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.URA_ID * * @mbggenerated */ private BigDecimal uraId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.TOWER_AMPLI_BOOL * * @mbggenerated */ private String towerAmpliBool; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SECTOR_ID * * @mbggenerated */ private BigDecimal sectorId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.NETWORK_TIME * * @mbggenerated */ private Date networkTime; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.VIP_BASE * * @mbggenerated */ private String vipBase; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.INSIDE * * @mbggenerated */ private String inside; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.BSC_NAME * * @mbggenerated */ private String bscName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.PROVINCE * * @mbggenerated */ private String province; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.DEV_MODEL * * @mbggenerated */ private String devModel; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.CABINET_TYPE * * @mbggenerated */ private String cabinetType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.CARRIER_TYPE * * @mbggenerated */ private String carrierType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SHARED_FEEDER * * @mbggenerated */ private String sharedFeeder; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SHARED_PLATFORM * * @mbggenerated */ private String sharedPlatform; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.CELL_BAND * * @mbggenerated */ private Integer cellBand; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.CELL_MARK * * @mbggenerated */ private String cellMark; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.BSIC * * @mbggenerated */ private BigDecimal bsic; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.TCH_FREQ * * @mbggenerated */ private String tchFreq; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.CARR_FREQ_CNT * * @mbggenerated */ private BigDecimal carrFreqCnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.CARR_FREQ_AVAIL_CNT * * @mbggenerated */ private BigDecimal carrFreqAvailCnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.CARR_FREQ_MAX_POWER * * @mbggenerated */ private BigDecimal carrFreqMaxPower; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.CTRL_CHANN_CNT * * @mbggenerated */ private BigDecimal ctrlChannCnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.BUSI_CHANN_CNT * * @mbggenerated */ private BigDecimal busiChannCnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.SDCCH_AVAIL_CNT * * @mbggenerated */ private BigDecimal sdcchAvailCnt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.ANT_ELEV_ANGLE * * @mbggenerated */ private BigDecimal antElevAngle; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.HOPPING_PATTERN * * @mbggenerated */ private String hoppingPattern; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.HALF_RATE_BOOL * * @mbggenerated */ private String halfRateBool; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GPRS_BOOL * * @mbggenerated */ private String gprsBool; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.EDGE_BOOL * * @mbggenerated */ private String edgeBool; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.ENFULL_RATE_BOOL * * @mbggenerated */ private String enfullRateBool; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL1 * * @mbggenerated */ private String wcdmaNearCell1; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL2 * * @mbggenerated */ private String wcdmaNearCell2; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL3 * * @mbggenerated */ private String wcdmaNearCell3; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL4 * * @mbggenerated */ private String wcdmaNearCell4; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL5 * * @mbggenerated */ private String wcdmaNearCell5; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL6 * * @mbggenerated */ private String wcdmaNearCell6; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL7 * * @mbggenerated */ private String wcdmaNearCell7; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL8 * * @mbggenerated */ private String wcdmaNearCell8; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL9 * * @mbggenerated */ private String wcdmaNearCell9; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL10 * * @mbggenerated */ private String wcdmaNearCell10; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL11 * * @mbggenerated */ private String wcdmaNearCell11; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL12 * * @mbggenerated */ private String wcdmaNearCell12; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL13 * * @mbggenerated */ private String wcdmaNearCell13; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL14 * * @mbggenerated */ private String wcdmaNearCell14; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL15 * * @mbggenerated */ private String wcdmaNearCell15; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL16 * * @mbggenerated */ private String wcdmaNearCell16; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL17 * * @mbggenerated */ private String wcdmaNearCell17; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL18 * * @mbggenerated */ private String wcdmaNearCell18; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL19 * * @mbggenerated */ private String wcdmaNearCell19; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL20 * * @mbggenerated */ private String wcdmaNearCell20; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL21 * * @mbggenerated */ private String wcdmaNearCell21; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL22 * * @mbggenerated */ private String wcdmaNearCell22; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL23 * * @mbggenerated */ private String wcdmaNearCell23; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL24 * * @mbggenerated */ private String wcdmaNearCell24; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL25 * * @mbggenerated */ private String wcdmaNearCell25; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL26 * * @mbggenerated */ private String wcdmaNearCell26; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL27 * * @mbggenerated */ private String wcdmaNearCell27; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL28 * * @mbggenerated */ private String wcdmaNearCell28; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL29 * * @mbggenerated */ private String wcdmaNearCell29; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL30 * * @mbggenerated */ private String wcdmaNearCell30; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL31 * * @mbggenerated */ private String wcdmaNearCell31; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL32 * * @mbggenerated */ private String wcdmaNearCell32; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL33 * * @mbggenerated */ private String wcdmaNearCell33; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL34 * * @mbggenerated */ private String wcdmaNearCell34; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL35 * * @mbggenerated */ private String wcdmaNearCell35; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL36 * * @mbggenerated */ private String wcdmaNearCell36; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL37 * * @mbggenerated */ private String wcdmaNearCell37; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL38 * * @mbggenerated */ private String wcdmaNearCell38; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL39 * * @mbggenerated */ private String wcdmaNearCell39; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL40 * * @mbggenerated */ private String wcdmaNearCell40; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL41 * * @mbggenerated */ private String wcdmaNearCell41; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL42 * * @mbggenerated */ private String wcdmaNearCell42; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL43 * * @mbggenerated */ private String wcdmaNearCell43; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL44 * * @mbggenerated */ private String wcdmaNearCell44; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL45 * * @mbggenerated */ private String wcdmaNearCell45; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL46 * * @mbggenerated */ private String wcdmaNearCell46; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL47 * * @mbggenerated */ private String wcdmaNearCell47; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL48 * * @mbggenerated */ private String wcdmaNearCell48; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL49 * * @mbggenerated */ private String wcdmaNearCell49; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL50 * * @mbggenerated */ private String wcdmaNearCell50; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL51 * * @mbggenerated */ private String wcdmaNearCell51; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL52 * * @mbggenerated */ private String wcdmaNearCell52; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL53 * * @mbggenerated */ private String wcdmaNearCell53; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL54 * * @mbggenerated */ private String wcdmaNearCell54; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL55 * * @mbggenerated */ private String wcdmaNearCell55; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL56 * * @mbggenerated */ private String wcdmaNearCell56; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL57 * * @mbggenerated */ private String wcdmaNearCell57; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL58 * * @mbggenerated */ private String wcdmaNearCell58; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL59 * * @mbggenerated */ private String wcdmaNearCell59; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL60 * * @mbggenerated */ private String wcdmaNearCell60; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL61 * * @mbggenerated */ private String wcdmaNearCell61; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL62 * * @mbggenerated */ private String wcdmaNearCell62; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL63 * * @mbggenerated */ private String wcdmaNearCell63; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.WCDMA_NEAR_CELL64 * * @mbggenerated */ private String wcdmaNearCell64; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL1 * * @mbggenerated */ private String gsmNearCell1; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL2 * * @mbggenerated */ private String gsmNearCell2; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL3 * * @mbggenerated */ private String gsmNearCell3; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL4 * * @mbggenerated */ private String gsmNearCell4; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL5 * * @mbggenerated */ private String gsmNearCell5; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL6 * * @mbggenerated */ private String gsmNearCell6; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL7 * * @mbggenerated */ private String gsmNearCell7; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL8 * * @mbggenerated */ private String gsmNearCell8; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL9 * * @mbggenerated */ private String gsmNearCell9; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL10 * * @mbggenerated */ private String gsmNearCell10; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL11 * * @mbggenerated */ private String gsmNearCell11; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL12 * * @mbggenerated */ private String gsmNearCell12; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL13 * * @mbggenerated */ private String gsmNearCell13; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL14 * * @mbggenerated */ private String gsmNearCell14; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL15 * * @mbggenerated */ private String gsmNearCell15; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL16 * * @mbggenerated */ private String gsmNearCell16; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL17 * * @mbggenerated */ private String gsmNearCell17; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL18 * * @mbggenerated */ private String gsmNearCell18; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL19 * * @mbggenerated */ private String gsmNearCell19; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL20 * * @mbggenerated */ private String gsmNearCell20; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL21 * * @mbggenerated */ private String gsmNearCell21; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL22 * * @mbggenerated */ private String gsmNearCell22; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL23 * * @mbggenerated */ private String gsmNearCell23; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL24 * * @mbggenerated */ private String gsmNearCell24; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL25 * * @mbggenerated */ private String gsmNearCell25; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL26 * * @mbggenerated */ private String gsmNearCell26; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL27 * * @mbggenerated */ private String gsmNearCell27; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL28 * * @mbggenerated */ private String gsmNearCell28; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL29 * * @mbggenerated */ private String gsmNearCell29; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL30 * * @mbggenerated */ private String gsmNearCell30; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL31 * * @mbggenerated */ private String gsmNearCell31; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column T_CAS_CELL.GSM_NEAR_CELL32 * * @mbggenerated */ private String gsmNearCell32; private int nearrel;//邻区类型 1、同频2、异频3、异网络 private String color_type;//是否填充颜色0 是 1 否 private String color;//颜色 #FFFFFF private List<GwCasCell> list = new ArrayList<GwCasCell>();//保存邻区关系 private String lac_cid; public String getLac_cid() { return lac_cid; } public void setLac_cid(String lac_cid) { this.lac_cid = lac_cid; } public List<GwCasCell> getList() { return list; } public void setList(List<GwCasCell> list) { this.list = list; } public int getNearrel() { return nearrel; } public void setNearrel(int nearrel) { this.nearrel = nearrel; } public String getColor_type() { return color_type; } public void setColor_type(String color_type) { this.color_type = color_type; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.CITY_NAME * * @return the value of T_CAS_CELL.CITY_NAME * * @mbggenerated */ public String getCityName() { return cityName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.CITY_NAME * * @param cityName the value for T_CAS_CELL.CITY_NAME * * @mbggenerated */ public void setCityName(String cityName) { this.cityName = cityName == null ? null : cityName.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.ADMIN_REGION * * @return the value of T_CAS_CELL.ADMIN_REGION * * @mbggenerated */ public String getAdminRegion() { return adminRegion; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.ADMIN_REGION * * @param adminRegion the value for T_CAS_CELL.ADMIN_REGION * * @mbggenerated */ public void setAdminRegion(String adminRegion) { this.adminRegion = adminRegion == null ? null : adminRegion.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.AREA_ID * * @return the value of T_CAS_CELL.AREA_ID * * @mbggenerated */ public BigDecimal getAreaId() { return areaId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.AREA_ID * * @param areaId the value for T_CAS_CELL.AREA_ID * * @mbggenerated */ public void setAreaId(BigDecimal areaId) { this.areaId = areaId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.BID * * @return the value of T_CAS_CELL.BID * * @mbggenerated */ public String getBid() { return bid; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.BID * * @param bid the value for T_CAS_CELL.BID * * @mbggenerated */ public void setBid(String bid) { this.bid = bid == null ? null : bid.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.BASE_NAME * * @return the value of T_CAS_CELL.BASE_NAME * * @mbggenerated */ public String getBaseName() { return baseName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.BASE_NAME * * @param baseName the value for T_CAS_CELL.BASE_NAME * * @mbggenerated */ public void setBaseName(String baseName) { this.baseName = baseName == null ? null : baseName.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.CELL_NAME * * @return the value of T_CAS_CELL.CELL_NAME * * @mbggenerated */ public String getCellName() { return cellName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.CELL_NAME * * @param cellName the value for T_CAS_CELL.CELL_NAME * * @mbggenerated */ public void setCellName(String cellName) { this.cellName = cellName == null ? null : cellName.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.LONGITUDE * * @return the value of T_CAS_CELL.LONGITUDE * * @mbggenerated */ public BigDecimal getLongitude() { return longitude; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.LONGITUDE * * @param longitude the value for T_CAS_CELL.LONGITUDE * * @mbggenerated */ public void setLongitude(BigDecimal longitude) { this.longitude = longitude; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.LATITUDE * * @return the value of T_CAS_CELL.LATITUDE * * @mbggenerated */ public BigDecimal getLatitude() { return latitude; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.LATITUDE * * @param latitude the value for T_CAS_CELL.LATITUDE * * @mbggenerated */ public void setLatitude(BigDecimal latitude) { this.latitude = latitude; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.LONGITUDE_MODIFY * * @return the value of T_CAS_CELL.LONGITUDE_MODIFY * * @mbggenerated */ public BigDecimal getLongitudeModify() { return longitudeModify; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.LONGITUDE_MODIFY * * @param longitudeModify the value for T_CAS_CELL.LONGITUDE_MODIFY * * @mbggenerated */ public void setLongitudeModify(BigDecimal longitudeModify) { this.longitudeModify = longitudeModify; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.LATITUDE_MODIFY * * @return the value of T_CAS_CELL.LATITUDE_MODIFY * * @mbggenerated */ public BigDecimal getLatitudeModify() { return latitudeModify; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.LATITUDE_MODIFY * * @param latitudeModify the value for T_CAS_CELL.LATITUDE_MODIFY * * @mbggenerated */ public void setLatitudeModify(BigDecimal latitudeModify) { this.latitudeModify = latitudeModify; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.PSC * * @return the value of T_CAS_CELL.PSC * * @mbggenerated */ public BigDecimal getPsc() { return psc; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.PSC * * @param psc the value for T_CAS_CELL.PSC * * @mbggenerated */ public void setPsc(BigDecimal psc) { this.psc = psc; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SELF_AZIMUTH * * @return the value of T_CAS_CELL.SELF_AZIMUTH * * @mbggenerated */ public BigDecimal getSelfAzimuth() { return selfAzimuth; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SELF_AZIMUTH * * @param selfAzimuth the value for T_CAS_CELL.SELF_AZIMUTH * * @mbggenerated */ public void setSelfAzimuth(BigDecimal selfAzimuth) { this.selfAzimuth = selfAzimuth; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.MODE_TYPE * * @return the value of T_CAS_CELL.MODE_TYPE * * @mbggenerated */ public int getModeType() { return modeType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.MODE_TYPE * * @param modeType the value for T_CAS_CELL.MODE_TYPE * * @mbggenerated */ public void setModeType(int modeType) { this.modeType = modeType; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.INDOOR * * @return the value of T_CAS_CELL.INDOOR * * @mbggenerated */ public Short getIndoor() { return indoor; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.INDOOR * * @param indoor the value for T_CAS_CELL.INDOOR * * @mbggenerated */ public void setIndoor(Short indoor) { this.indoor = indoor; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.ANT_TYPE * * @return the value of T_CAS_CELL.ANT_TYPE * * @mbggenerated */ public String getAntType() { return antType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.ANT_TYPE * * @param antType the value for T_CAS_CELL.ANT_TYPE * * @mbggenerated */ public void setAntType(String antType) { this.antType = antType == null ? null : antType.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.ANT_AZIMUTH * * @return the value of T_CAS_CELL.ANT_AZIMUTH * * @mbggenerated */ public BigDecimal getAntAzimuth() { return antAzimuth; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.ANT_AZIMUTH * * @param antAzimuth the value for T_CAS_CELL.ANT_AZIMUTH * * @mbggenerated */ public void setAntAzimuth(BigDecimal antAzimuth) { this.antAzimuth = antAzimuth; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.ANT_HIGH * * @return the value of T_CAS_CELL.ANT_HIGH * * @mbggenerated */ public BigDecimal getAntHigh() { return antHigh; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.ANT_HIGH * * @param antHigh the value for T_CAS_CELL.ANT_HIGH * * @mbggenerated */ public void setAntHigh(BigDecimal antHigh) { this.antHigh = antHigh; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.ANT_ELECT_ANGLE * * @return the value of T_CAS_CELL.ANT_ELECT_ANGLE * * @mbggenerated */ public BigDecimal getAntElectAngle() { return antElectAngle; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.ANT_ELECT_ANGLE * * @param antElectAngle the value for T_CAS_CELL.ANT_ELECT_ANGLE * * @mbggenerated */ public void setAntElectAngle(BigDecimal antElectAngle) { this.antElectAngle = antElectAngle; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.ANT_MACH_ANGLE * * @return the value of T_CAS_CELL.ANT_MACH_ANGLE * * @mbggenerated */ public BigDecimal getAntMachAngle() { return antMachAngle; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.ANT_MACH_ANGLE * * @param antMachAngle the value for T_CAS_CELL.ANT_MACH_ANGLE * * @mbggenerated */ public void setAntMachAngle(BigDecimal antMachAngle) { this.antMachAngle = antMachAngle; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SHARED_ANT * * @return the value of T_CAS_CELL.SHARED_ANT * * @mbggenerated */ public String getSharedAnt() { return sharedAnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SHARED_ANT * * @param sharedAnt the value for T_CAS_CELL.SHARED_ANT * * @mbggenerated */ public void setSharedAnt(String sharedAnt) { this.sharedAnt = sharedAnt == null ? null : sharedAnt.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.BASE_ADDRESS * * @return the value of T_CAS_CELL.BASE_ADDRESS * * @mbggenerated */ public String getBaseAddress() { return baseAddress; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.BASE_ADDRESS * * @param baseAddress the value for T_CAS_CELL.BASE_ADDRESS * * @mbggenerated */ public void setBaseAddress(String baseAddress) { this.baseAddress = baseAddress == null ? null : baseAddress.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.ALTITUDE * * @return the value of T_CAS_CELL.ALTITUDE * * @mbggenerated */ public BigDecimal getAltitude() { return altitude; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.ALTITUDE * * @param altitude the value for T_CAS_CELL.ALTITUDE * * @mbggenerated */ public void setAltitude(BigDecimal altitude) { this.altitude = altitude; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.DEV_VENDOR * * @return the value of T_CAS_CELL.DEV_VENDOR * * @mbggenerated */ public String getDevVendor() { return devVendor; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.DEV_VENDOR * * @param devVendor the value for T_CAS_CELL.DEV_VENDOR * * @mbggenerated */ public void setDevVendor(String devVendor) { this.devVendor = devVendor == null ? null : devVendor.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.TOWER_MAST_TYPE * * @return the value of T_CAS_CELL.TOWER_MAST_TYPE * * @mbggenerated */ public String getTowerMastType() { return towerMastType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.TOWER_MAST_TYPE * * @param towerMastType the value for T_CAS_CELL.TOWER_MAST_TYPE * * @mbggenerated */ public void setTowerMastType(String towerMastType) { this.towerMastType = towerMastType == null ? null : towerMastType.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.DEV_TYPE * * @return the value of T_CAS_CELL.DEV_TYPE * * @mbggenerated */ public String getDevType() { return devType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.DEV_TYPE * * @param devType the value for T_CAS_CELL.DEV_TYPE * * @mbggenerated */ public void setDevType(String devType) { this.devType = devType == null ? null : devType.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.BASE_CONF * * @return the value of T_CAS_CELL.BASE_CONF * * @mbggenerated */ public String getBaseConf() { return baseConf; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.BASE_CONF * * @param baseConf the value for T_CAS_CELL.BASE_CONF * * @mbggenerated */ public void setBaseConf(String baseConf) { this.baseConf = baseConf == null ? null : baseConf.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.PROGRESS * * @return the value of T_CAS_CELL.PROGRESS * * @mbggenerated */ public String getProgress() { return progress; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.PROGRESS * * @param progress the value for T_CAS_CELL.PROGRESS * * @mbggenerated */ public void setProgress(String progress) { this.progress = progress == null ? null : progress.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.COVER_RANGE * * @return the value of T_CAS_CELL.COVER_RANGE * * @mbggenerated */ public String getCoverRange() { return coverRange; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.COVER_RANGE * * @param coverRange the value for T_CAS_CELL.COVER_RANGE * * @mbggenerated */ public void setCoverRange(String coverRange) { this.coverRange = coverRange == null ? null : coverRange.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.COVER_TYPE * * @return the value of T_CAS_CELL.COVER_TYPE * * @mbggenerated */ public String getCoverType() { return coverType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.COVER_TYPE * * @param coverType the value for T_CAS_CELL.COVER_TYPE * * @mbggenerated */ public void setCoverType(String coverType) { this.coverType = coverType == null ? null : coverType.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.RRU_CELL_BOOL * * @return the value of T_CAS_CELL.RRU_CELL_BOOL * * @mbggenerated */ public String getRruCellBool() { return rruCellBool; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.RRU_CELL_BOOL * * @param rruCellBool the value for T_CAS_CELL.RRU_CELL_BOOL * * @mbggenerated */ public void setRruCellBool(String rruCellBool) { this.rruCellBool = rruCellBool == null ? null : rruCellBool.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.CELL_ID * * @return the value of T_CAS_CELL.CELL_ID * * @mbggenerated */ public BigDecimal getCellId() { return cellId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.CELL_ID * * @param cellId the value for T_CAS_CELL.CELL_ID * * @mbggenerated */ public void setCellId(BigDecimal cellId) { this.cellId = cellId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.REPEATER_CNT * * @return the value of T_CAS_CELL.REPEATER_CNT * * @mbggenerated */ public BigDecimal getRepeaterCnt() { return repeaterCnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.REPEATER_CNT * * @param repeaterCnt the value for T_CAS_CELL.REPEATER_CNT * * @mbggenerated */ public void setRepeaterCnt(BigDecimal repeaterCnt) { this.repeaterCnt = repeaterCnt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SHARED_ANT_CELL * * @return the value of T_CAS_CELL.SHARED_ANT_CELL * * @mbggenerated */ public String getSharedAntCell() { return sharedAntCell; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SHARED_ANT_CELL * * @param sharedAntCell the value for T_CAS_CELL.SHARED_ANT_CELL * * @mbggenerated */ public void setSharedAntCell(String sharedAntCell) { this.sharedAntCell = sharedAntCell == null ? null : sharedAntCell.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SHARED_ANT_CELL_BAK * * @return the value of T_CAS_CELL.SHARED_ANT_CELL_BAK * * @mbggenerated */ public String getSharedAntCellBak() { return sharedAntCellBak; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SHARED_ANT_CELL_BAK * * @param sharedAntCellBak the value for T_CAS_CELL.SHARED_ANT_CELL_BAK * * @mbggenerated */ public void setSharedAntCellBak(String sharedAntCellBak) { this.sharedAntCellBak = sharedAntCellBak == null ? null : sharedAntCellBak.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SHARED_ANT_PROP * * @return the value of T_CAS_CELL.SHARED_ANT_PROP * * @mbggenerated */ public String getSharedAntProp() { return sharedAntProp; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SHARED_ANT_PROP * * @param sharedAntProp the value for T_CAS_CELL.SHARED_ANT_PROP * * @mbggenerated */ public void setSharedAntProp(String sharedAntProp) { this.sharedAntProp = sharedAntProp == null ? null : sharedAntProp.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SHARED_BASE_NAME * * @return the value of T_CAS_CELL.SHARED_BASE_NAME * * @mbggenerated */ public String getSharedBaseName() { return sharedBaseName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SHARED_BASE_NAME * * @param sharedBaseName the value for T_CAS_CELL.SHARED_BASE_NAME * * @mbggenerated */ public void setSharedBaseName(String sharedBaseName) { this.sharedBaseName = sharedBaseName == null ? null : sharedBaseName.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SHARED_BASE_PROP * * @return the value of T_CAS_CELL.SHARED_BASE_PROP * * @mbggenerated */ public String getSharedBaseProp() { return sharedBaseProp; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SHARED_BASE_PROP * * @param sharedBaseProp the value for T_CAS_CELL.SHARED_BASE_PROP * * @mbggenerated */ public void setSharedBaseProp(String sharedBaseProp) { this.sharedBaseProp = sharedBaseProp == null ? null : sharedBaseProp.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.NETMAN_STAT * * @return the value of T_CAS_CELL.NETMAN_STAT * * @mbggenerated */ public String getNetmanStat() { return netmanStat; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.NETMAN_STAT * * @param netmanStat the value for T_CAS_CELL.NETMAN_STAT * * @mbggenerated */ public void setNetmanStat(String netmanStat) { this.netmanStat = netmanStat == null ? null : netmanStat.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.ADMIN_REGION_TYPE * * @return the value of T_CAS_CELL.ADMIN_REGION_TYPE * * @mbggenerated */ public String getAdminRegionType() { return adminRegionType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.ADMIN_REGION_TYPE * * @param adminRegionType the value for T_CAS_CELL.ADMIN_REGION_TYPE * * @mbggenerated */ public void setAdminRegionType(String adminRegionType) { this.adminRegionType = adminRegionType == null ? null : adminRegionType.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.UP_FREQ * * @return the value of T_CAS_CELL.UP_FREQ * * @mbggenerated */ public Integer getUpFreq() { return upFreq; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.UP_FREQ * * @param upFreq the value for T_CAS_CELL.UP_FREQ * * @mbggenerated */ public void setUpFreq(Integer upFreq) { this.upFreq = upFreq; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.DOWN_FREQ * * @return the value of T_CAS_CELL.DOWN_FREQ * * @mbggenerated */ public Integer getDownFreq() { return downFreq; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.DOWN_FREQ * * @param downFreq the value for T_CAS_CELL.DOWN_FREQ * * @mbggenerated */ public void setDownFreq(Integer downFreq) { this.downFreq = downFreq; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.RNC_NAME * * @return the value of T_CAS_CELL.RNC_NAME * * @mbggenerated */ public String getRncName() { return rncName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.RNC_NAME * * @param rncName the value for T_CAS_CELL.RNC_NAME * * @mbggenerated */ public void setRncName(String rncName) { this.rncName = rncName == null ? null : rncName.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.NE_TYPE * * @return the value of T_CAS_CELL.NE_TYPE * * @mbggenerated */ public String getNeType() { return neType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.NE_TYPE * * @param neType the value for T_CAS_CELL.NE_TYPE * * @mbggenerated */ public void setNeType(String neType) { this.neType = neType == null ? null : neType.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.ANT_POWER * * @return the value of T_CAS_CELL.ANT_POWER * * @mbggenerated */ public BigDecimal getAntPower() { return antPower; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.ANT_POWER * * @param antPower the value for T_CAS_CELL.ANT_POWER * * @mbggenerated */ public void setAntPower(BigDecimal antPower) { this.antPower = antPower; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.TILT * * @return the value of T_CAS_CELL.TILT * * @mbggenerated */ public BigDecimal getTilt() { return tilt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.TILT * * @param tilt the value for T_CAS_CELL.TILT * * @mbggenerated */ public void setTilt(BigDecimal tilt) { this.tilt = tilt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.ESC_BOOL * * @return the value of T_CAS_CELL.ESC_BOOL * * @mbggenerated */ public String getEscBool() { return escBool; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.ESC_BOOL * * @param escBool the value for T_CAS_CELL.ESC_BOOL * * @mbggenerated */ public void setEscBool(String escBool) { this.escBool = escBool == null ? null : escBool.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.BASE_TYPE * * @return the value of T_CAS_CELL.BASE_TYPE * * @mbggenerated */ public String getBaseType() { return baseType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.BASE_TYPE * * @param baseType the value for T_CAS_CELL.BASE_TYPE * * @mbggenerated */ public void setBaseType(String baseType) { this.baseType = baseType == null ? null : baseType.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.RRU_CNT * * @return the value of T_CAS_CELL.RRU_CNT * * @mbggenerated */ public BigDecimal getRruCnt() { return rruCnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.RRU_CNT * * @param rruCnt the value for T_CAS_CELL.RRU_CNT * * @mbggenerated */ public void setRruCnt(BigDecimal rruCnt) { this.rruCnt = rruCnt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.LOGIC_CELL_LEVEL * * @return the value of T_CAS_CELL.LOGIC_CELL_LEVEL * * @mbggenerated */ public String getLogicCellLevel() { return logicCellLevel; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.LOGIC_CELL_LEVEL * * @param logicCellLevel the value for T_CAS_CELL.LOGIC_CELL_LEVEL * * @mbggenerated */ public void setLogicCellLevel(String logicCellLevel) { this.logicCellLevel = logicCellLevel == null ? null : logicCellLevel.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SECTOR_WIFI_CAPAC * * @return the value of T_CAS_CELL.SECTOR_WIFI_CAPAC * * @mbggenerated */ public BigDecimal getSectorWifiCapac() { return sectorWifiCapac; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SECTOR_WIFI_CAPAC * * @param sectorWifiCapac the value for T_CAS_CELL.SECTOR_WIFI_CAPAC * * @mbggenerated */ public void setSectorWifiCapac(BigDecimal sectorWifiCapac) { this.sectorWifiCapac = sectorWifiCapac; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.E1_CNT * * @return the value of T_CAS_CELL.E1_CNT * * @mbggenerated */ public BigDecimal getE1Cnt() { return e1Cnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.E1_CNT * * @param e1Cnt the value for T_CAS_CELL.E1_CNT * * @mbggenerated */ public void setE1Cnt(BigDecimal e1Cnt) { this.e1Cnt = e1Cnt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.FE_CNT * * @return the value of T_CAS_CELL.FE_CNT * * @mbggenerated */ public BigDecimal getFeCnt() { return feCnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.FE_CNT * * @param feCnt the value for T_CAS_CELL.FE_CNT * * @mbggenerated */ public void setFeCnt(BigDecimal feCnt) { this.feCnt = feCnt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.TRANSMISSION * * @return the value of T_CAS_CELL.TRANSMISSION * * @mbggenerated */ public String getTransmission() { return transmission; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.TRANSMISSION * * @param transmission the value for T_CAS_CELL.TRANSMISSION * * @mbggenerated */ public void setTransmission(String transmission) { this.transmission = transmission == null ? null : transmission.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.CQ_AREA_COVER * * @return the value of T_CAS_CELL.CQ_AREA_COVER * * @mbggenerated */ public String getCqAreaCover() { return cqAreaCover; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.CQ_AREA_COVER * * @param cqAreaCover the value for T_CAS_CELL.CQ_AREA_COVER * * @mbggenerated */ public void setCqAreaCover(String cqAreaCover) { this.cqAreaCover = cqAreaCover == null ? null : cqAreaCover.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WIFI_CAPAC * * @return the value of T_CAS_CELL.WIFI_CAPAC * * @mbggenerated */ public BigDecimal getWifiCapac() { return wifiCapac; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WIFI_CAPAC * * @param wifiCapac the value for T_CAS_CELL.WIFI_CAPAC * * @mbggenerated */ public void setWifiCapac(BigDecimal wifiCapac) { this.wifiCapac = wifiCapac; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.BASE_MAX_POWER * * @return the value of T_CAS_CELL.BASE_MAX_POWER * * @mbggenerated */ public BigDecimal getBaseMaxPower() { return baseMaxPower; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.BASE_MAX_POWER * * @param baseMaxPower the value for T_CAS_CELL.BASE_MAX_POWER * * @mbggenerated */ public void setBaseMaxPower(BigDecimal baseMaxPower) { this.baseMaxPower = baseMaxPower; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.INNER_TILT * * @return the value of T_CAS_CELL.INNER_TILT * * @mbggenerated */ public BigDecimal getInnerTilt() { return innerTilt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.INNER_TILT * * @param innerTilt the value for T_CAS_CELL.INNER_TILT * * @mbggenerated */ public void setInnerTilt(BigDecimal innerTilt) { this.innerTilt = innerTilt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.OFF_SERVICE_TIME * * @return the value of T_CAS_CELL.OFF_SERVICE_TIME * * @mbggenerated */ public Date getOffServiceTime() { return offServiceTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.OFF_SERVICE_TIME * * @param offServiceTime the value for T_CAS_CELL.OFF_SERVICE_TIME * * @mbggenerated */ public void setOffServiceTime(Date offServiceTime) { this.offServiceTime = offServiceTime; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.DOWN_MAX_POWER * * @return the value of T_CAS_CELL.DOWN_MAX_POWER * * @mbggenerated */ public BigDecimal getDownMaxPower() { return downMaxPower; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.DOWN_MAX_POWER * * @param downMaxPower the value for T_CAS_CELL.DOWN_MAX_POWER * * @mbggenerated */ public void setDownMaxPower(BigDecimal downMaxPower) { this.downMaxPower = downMaxPower; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SCENE_A * * @return the value of T_CAS_CELL.SCENE_A * * @mbggenerated */ public String getSceneA() { return sceneA; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SCENE_A * * @param sceneA the value for T_CAS_CELL.SCENE_A * * @mbggenerated */ public void setSceneA(String sceneA) { this.sceneA = sceneA == null ? null : sceneA.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SCENE_B * * @return the value of T_CAS_CELL.SCENE_B * * @mbggenerated */ public String getSceneB() { return sceneB; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SCENE_B * * @param sceneB the value for T_CAS_CELL.SCENE_B * * @mbggenerated */ public void setSceneB(String sceneB) { this.sceneB = sceneB == null ? null : sceneB.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.TOWN_BOOL * * @return the value of T_CAS_CELL.TOWN_BOOL * * @mbggenerated */ public String getTownBool() { return townBool; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.TOWN_BOOL * * @param townBool the value for T_CAS_CELL.TOWN_BOOL * * @mbggenerated */ public void setTownBool(String townBool) { this.townBool = townBool == null ? null : townBool.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.HSDPA_BOOL * * @return the value of T_CAS_CELL.HSDPA_BOOL * * @mbggenerated */ public String getHsdpaBool() { return hsdpaBool; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.HSDPA_BOOL * * @param hsdpaBool the value for T_CAS_CELL.HSDPA_BOOL * * @mbggenerated */ public void setHsdpaBool(String hsdpaBool) { this.hsdpaBool = hsdpaBool == null ? null : hsdpaBool.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.HSDPA_STAT * * @return the value of T_CAS_CELL.HSDPA_STAT * * @mbggenerated */ public String getHsdpaStat() { return hsdpaStat; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.HSDPA_STAT * * @param hsdpaStat the value for T_CAS_CELL.HSDPA_STAT * * @mbggenerated */ public void setHsdpaStat(String hsdpaStat) { this.hsdpaStat = hsdpaStat == null ? null : hsdpaStat.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.HS_PDSCH_CODE * * @return the value of T_CAS_CELL.HS_PDSCH_CODE * * @mbggenerated */ public String getHsPdschCode() { return hsPdschCode; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.HS_PDSCH_CODE * * @param hsPdschCode the value for T_CAS_CELL.HS_PDSCH_CODE * * @mbggenerated */ public void setHsPdschCode(String hsPdschCode) { this.hsPdschCode = hsPdschCode == null ? null : hsPdschCode.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.BROADCAST_CHANN_POWER * * @return the value of T_CAS_CELL.BROADCAST_CHANN_POWER * * @mbggenerated */ public BigDecimal getBroadcastChannPower() { return broadcastChannPower; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.BROADCAST_CHANN_POWER * * @param broadcastChannPower the value for T_CAS_CELL.BROADCAST_CHANN_POWER * * @mbggenerated */ public void setBroadcastChannPower(BigDecimal broadcastChannPower) { this.broadcastChannPower = broadcastChannPower; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.HSUPA_BOOL * * @return the value of T_CAS_CELL.HSUPA_BOOL * * @mbggenerated */ public String getHsupaBool() { return hsupaBool; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.HSUPA_BOOL * * @param hsupaBool the value for T_CAS_CELL.HSUPA_BOOL * * @mbggenerated */ public void setHsupaBool(String hsupaBool) { this.hsupaBool = hsupaBool == null ? null : hsupaBool.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.HSUPA_STAT * * @return the value of T_CAS_CELL.HSUPA_STAT * * @mbggenerated */ public String getHsupaStat() { return hsupaStat; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.HSUPA_STAT * * @param hsupaStat the value for T_CAS_CELL.HSUPA_STAT * * @mbggenerated */ public void setHsupaStat(String hsupaStat) { this.hsupaStat = hsupaStat == null ? null : hsupaStat.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.MBMS_BOOL * * @return the value of T_CAS_CELL.MBMS_BOOL * * @mbggenerated */ public String getMbmsBool() { return mbmsBool; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.MBMS_BOOL * * @param mbmsBool the value for T_CAS_CELL.MBMS_BOOL * * @mbggenerated */ public void setMbmsBool(String mbmsBool) { this.mbmsBool = mbmsBool == null ? null : mbmsBool.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.MBMS_STAT * * @return the value of T_CAS_CELL.MBMS_STAT * * @mbggenerated */ public String getMbmsStat() { return mbmsStat; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.MBMS_STAT * * @param mbmsStat the value for T_CAS_CELL.MBMS_STAT * * @mbggenerated */ public void setMbmsStat(String mbmsStat) { this.mbmsStat = mbmsStat == null ? null : mbmsStat.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.MICH_CHANN_CNT * * @return the value of T_CAS_CELL.MICH_CHANN_CNT * * @mbggenerated */ public BigDecimal getMichChannCnt() { return michChannCnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.MICH_CHANN_CNT * * @param michChannCnt the value for T_CAS_CELL.MICH_CHANN_CNT * * @mbggenerated */ public void setMichChannCnt(BigDecimal michChannCnt) { this.michChannCnt = michChannCnt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SF16_CODE_CNT * * @return the value of T_CAS_CELL.SF16_CODE_CNT * * @mbggenerated */ public BigDecimal getSf16CodeCnt() { return sf16CodeCnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SF16_CODE_CNT * * @param sf16CodeCnt the value for T_CAS_CELL.SF16_CODE_CNT * * @mbggenerated */ public void setSf16CodeCnt(BigDecimal sf16CodeCnt) { this.sf16CodeCnt = sf16CodeCnt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SF128_CODE_CNT * * @return the value of T_CAS_CELL.SF128_CODE_CNT * * @mbggenerated */ public BigDecimal getSf128CodeCnt() { return sf128CodeCnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SF128_CODE_CNT * * @param sf128CodeCnt the value for T_CAS_CELL.SF128_CODE_CNT * * @mbggenerated */ public void setSf128CodeCnt(BigDecimal sf128CodeCnt) { this.sf128CodeCnt = sf128CodeCnt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.E_AGCH_CHANN_CNT * * @return the value of T_CAS_CELL.E_AGCH_CHANN_CNT * * @mbggenerated */ public BigDecimal geteAgchChannCnt() { return eAgchChannCnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.E_AGCH_CHANN_CNT * * @param eAgchChannCnt the value for T_CAS_CELL.E_AGCH_CHANN_CNT * * @mbggenerated */ public void seteAgchChannCnt(BigDecimal eAgchChannCnt) { this.eAgchChannCnt = eAgchChannCnt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.E_RGCH_E_HICH_CHANN_CNT * * @return the value of T_CAS_CELL.E_RGCH_E_HICH_CHANN_CNT * * @mbggenerated */ public BigDecimal geteRgchEHichChannCnt() { return eRgchEHichChannCnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.E_RGCH_E_HICH_CHANN_CNT * * @param eRgchEHichChannCnt the value for T_CAS_CELL.E_RGCH_E_HICH_CHANN_CNT * * @mbggenerated */ public void seteRgchEHichChannCnt(BigDecimal eRgchEHichChannCnt) { this.eRgchEHichChannCnt = eRgchEHichChannCnt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.PCPICH_CHANN_MAX_POWER * * @return the value of T_CAS_CELL.PCPICH_CHANN_MAX_POWER * * @mbggenerated */ public BigDecimal getPcpichChannMaxPower() { return pcpichChannMaxPower; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.PCPICH_CHANN_MAX_POWER * * @param pcpichChannMaxPower the value for T_CAS_CELL.PCPICH_CHANN_MAX_POWER * * @mbggenerated */ public void setPcpichChannMaxPower(BigDecimal pcpichChannMaxPower) { this.pcpichChannMaxPower = pcpichChannMaxPower; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.PCPICH_CHANN_MIN_POWER * * @return the value of T_CAS_CELL.PCPICH_CHANN_MIN_POWER * * @mbggenerated */ public BigDecimal getPcpichChannMinPower() { return pcpichChannMinPower; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.PCPICH_CHANN_MIN_POWER * * @param pcpichChannMinPower the value for T_CAS_CELL.PCPICH_CHANN_MIN_POWER * * @mbggenerated */ public void setPcpichChannMinPower(BigDecimal pcpichChannMinPower) { this.pcpichChannMinPower = pcpichChannMinPower; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.DOMIN_FREQ_CHANN_POWER * * @return the value of T_CAS_CELL.DOMIN_FREQ_CHANN_POWER * * @mbggenerated */ public BigDecimal getDominFreqChannPower() { return dominFreqChannPower; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.DOMIN_FREQ_CHANN_POWER * * @param dominFreqChannPower the value for T_CAS_CELL.DOMIN_FREQ_CHANN_POWER * * @mbggenerated */ public void setDominFreqChannPower(BigDecimal dominFreqChannPower) { this.dominFreqChannPower = dominFreqChannPower; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SYNC_CHANN_DOWN_POWER * * @return the value of T_CAS_CELL.SYNC_CHANN_DOWN_POWER * * @mbggenerated */ public BigDecimal getSyncChannDownPower() { return syncChannDownPower; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SYNC_CHANN_DOWN_POWER * * @param syncChannDownPower the value for T_CAS_CELL.SYNC_CHANN_DOWN_POWER * * @mbggenerated */ public void setSyncChannDownPower(BigDecimal syncChannDownPower) { this.syncChannDownPower = syncChannDownPower; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SINGLE_CARR_FREQ_MAX_USER * * @return the value of T_CAS_CELL.SINGLE_CARR_FREQ_MAX_USER * * @mbggenerated */ public BigDecimal getSingleCarrFreqMaxUser() { return singleCarrFreqMaxUser; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SINGLE_CARR_FREQ_MAX_USER * * @param singleCarrFreqMaxUser the value for T_CAS_CELL.SINGLE_CARR_FREQ_MAX_USER * * @mbggenerated */ public void setSingleCarrFreqMaxUser(BigDecimal singleCarrFreqMaxUser) { this.singleCarrFreqMaxUser = singleCarrFreqMaxUser; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.CARR_FREQ_POWER * * @return the value of T_CAS_CELL.CARR_FREQ_POWER * * @mbggenerated */ public BigDecimal getCarrFreqPower() { return carrFreqPower; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.CARR_FREQ_POWER * * @param carrFreqPower the value for T_CAS_CELL.CARR_FREQ_POWER * * @mbggenerated */ public void setCarrFreqPower(BigDecimal carrFreqPower) { this.carrFreqPower = carrFreqPower; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.UP_CE_CAPAC * * @return the value of T_CAS_CELL.UP_CE_CAPAC * * @mbggenerated */ public BigDecimal getUpCeCapac() { return upCeCapac; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.UP_CE_CAPAC * * @param upCeCapac the value for T_CAS_CELL.UP_CE_CAPAC * * @mbggenerated */ public void setUpCeCapac(BigDecimal upCeCapac) { this.upCeCapac = upCeCapac; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.DOWN_CE_CAPAC * * @return the value of T_CAS_CELL.DOWN_CE_CAPAC * * @mbggenerated */ public BigDecimal getDownCeCapac() { return downCeCapac; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.DOWN_CE_CAPAC * * @param downCeCapac the value for T_CAS_CELL.DOWN_CE_CAPAC * * @mbggenerated */ public void setDownCeCapac(BigDecimal downCeCapac) { this.downCeCapac = downCeCapac; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.IUB_ATM_BANDWIDTH * * @return the value of T_CAS_CELL.IUB_ATM_BANDWIDTH * * @mbggenerated */ public BigDecimal getIubAtmBandwidth() { return iubAtmBandwidth; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.IUB_ATM_BANDWIDTH * * @param iubAtmBandwidth the value for T_CAS_CELL.IUB_ATM_BANDWIDTH * * @mbggenerated */ public void setIubAtmBandwidth(BigDecimal iubAtmBandwidth) { this.iubAtmBandwidth = iubAtmBandwidth; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.IUB_IP_BANDWIDTH * * @return the value of T_CAS_CELL.IUB_IP_BANDWIDTH * * @mbggenerated */ public BigDecimal getIubIpBandwidth() { return iubIpBandwidth; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.IUB_IP_BANDWIDTH * * @param iubIpBandwidth the value for T_CAS_CELL.IUB_IP_BANDWIDTH * * @mbggenerated */ public void setIubIpBandwidth(BigDecimal iubIpBandwidth) { this.iubIpBandwidth = iubIpBandwidth; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.IU_ATM_BANDWIDTH * * @return the value of T_CAS_CELL.IU_ATM_BANDWIDTH * * @mbggenerated */ public BigDecimal getIuAtmBandwidth() { return iuAtmBandwidth; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.IU_ATM_BANDWIDTH * * @param iuAtmBandwidth the value for T_CAS_CELL.IU_ATM_BANDWIDTH * * @mbggenerated */ public void setIuAtmBandwidth(BigDecimal iuAtmBandwidth) { this.iuAtmBandwidth = iuAtmBandwidth; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.IU_IP_BANDWIDTH * * @return the value of T_CAS_CELL.IU_IP_BANDWIDTH * * @mbggenerated */ public BigDecimal getIuIpBandwidth() { return iuIpBandwidth; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.IU_IP_BANDWIDTH * * @param iuIpBandwidth the value for T_CAS_CELL.IU_IP_BANDWIDTH * * @mbggenerated */ public void setIuIpBandwidth(BigDecimal iuIpBandwidth) { this.iuIpBandwidth = iuIpBandwidth; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.IUR_ATM_BANDWIDTH * * @return the value of T_CAS_CELL.IUR_ATM_BANDWIDTH * * @mbggenerated */ public BigDecimal getIurAtmBandwidth() { return iurAtmBandwidth; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.IUR_ATM_BANDWIDTH * * @param iurAtmBandwidth the value for T_CAS_CELL.IUR_ATM_BANDWIDTH * * @mbggenerated */ public void setIurAtmBandwidth(BigDecimal iurAtmBandwidth) { this.iurAtmBandwidth = iurAtmBandwidth; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.IUR_IP_BANDWIDTH * * @return the value of T_CAS_CELL.IUR_IP_BANDWIDTH * * @mbggenerated */ public BigDecimal getIurIpBandwidth() { return iurIpBandwidth; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.IUR_IP_BANDWIDTH * * @param iurIpBandwidth the value for T_CAS_CELL.IUR_IP_BANDWIDTH * * @mbggenerated */ public void setIurIpBandwidth(BigDecimal iurIpBandwidth) { this.iurIpBandwidth = iurIpBandwidth; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.REMARK * * @return the value of T_CAS_CELL.REMARK * * @mbggenerated */ public String getRemark() { return remark; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.REMARK * * @param remark the value for T_CAS_CELL.REMARK * * @mbggenerated */ public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.LAST_UPDATE_TIME * * @return the value of T_CAS_CELL.LAST_UPDATE_TIME * * @mbggenerated */ public Date getLastUpdateTime() { return lastUpdateTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.LAST_UPDATE_TIME * * @param lastUpdateTime the value for T_CAS_CELL.LAST_UPDATE_TIME * * @mbggenerated */ public void setLastUpdateTime(Date lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.RAC * * @return the value of T_CAS_CELL.RAC * * @mbggenerated */ public BigDecimal getRac() { return rac; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.RAC * * @param rac the value for T_CAS_CELL.RAC * * @mbggenerated */ public void setRac(BigDecimal rac) { this.rac = rac; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SAC * * @return the value of T_CAS_CELL.SAC * * @mbggenerated */ public BigDecimal getSac() { return sac; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SAC * * @param sac the value for T_CAS_CELL.SAC * * @mbggenerated */ public void setSac(BigDecimal sac) { this.sac = sac; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.RNC_ID * * @return the value of T_CAS_CELL.RNC_ID * * @mbggenerated */ public BigDecimal getRncId() { return rncId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.RNC_ID * * @param rncId the value for T_CAS_CELL.RNC_ID * * @mbggenerated */ public void setRncId(BigDecimal rncId) { this.rncId = rncId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.BASE_ID * * @return the value of T_CAS_CELL.BASE_ID * * @mbggenerated */ public BigDecimal getBaseId() { return baseId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.BASE_ID * * @param baseId the value for T_CAS_CELL.BASE_ID * * @mbggenerated */ public void setBaseId(BigDecimal baseId) { this.baseId = baseId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.URA_ID * * @return the value of T_CAS_CELL.URA_ID * * @mbggenerated */ public BigDecimal getUraId() { return uraId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.URA_ID * * @param uraId the value for T_CAS_CELL.URA_ID * * @mbggenerated */ public void setUraId(BigDecimal uraId) { this.uraId = uraId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.TOWER_AMPLI_BOOL * * @return the value of T_CAS_CELL.TOWER_AMPLI_BOOL * * @mbggenerated */ public String getTowerAmpliBool() { return towerAmpliBool; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.TOWER_AMPLI_BOOL * * @param towerAmpliBool the value for T_CAS_CELL.TOWER_AMPLI_BOOL * * @mbggenerated */ public void setTowerAmpliBool(String towerAmpliBool) { this.towerAmpliBool = towerAmpliBool == null ? null : towerAmpliBool.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SECTOR_ID * * @return the value of T_CAS_CELL.SECTOR_ID * * @mbggenerated */ public BigDecimal getSectorId() { return sectorId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SECTOR_ID * * @param sectorId the value for T_CAS_CELL.SECTOR_ID * * @mbggenerated */ public void setSectorId(BigDecimal sectorId) { this.sectorId = sectorId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.NETWORK_TIME * * @return the value of T_CAS_CELL.NETWORK_TIME * * @mbggenerated */ public Date getNetworkTime() { return networkTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.NETWORK_TIME * * @param networkTime the value for T_CAS_CELL.NETWORK_TIME * * @mbggenerated */ public void setNetworkTime(Date networkTime) { this.networkTime = networkTime; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.VIP_BASE * * @return the value of T_CAS_CELL.VIP_BASE * * @mbggenerated */ public String getVipBase() { return vipBase; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.VIP_BASE * * @param vipBase the value for T_CAS_CELL.VIP_BASE * * @mbggenerated */ public void setVipBase(String vipBase) { this.vipBase = vipBase == null ? null : vipBase.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.INSIDE * * @return the value of T_CAS_CELL.INSIDE * * @mbggenerated */ public String getInside() { return inside; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.INSIDE * * @param inside the value for T_CAS_CELL.INSIDE * * @mbggenerated */ public void setInside(String inside) { this.inside = inside == null ? null : inside.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.BSC_NAME * * @return the value of T_CAS_CELL.BSC_NAME * * @mbggenerated */ public String getBscName() { return bscName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.BSC_NAME * * @param bscName the value for T_CAS_CELL.BSC_NAME * * @mbggenerated */ public void setBscName(String bscName) { this.bscName = bscName == null ? null : bscName.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.PROVINCE * * @return the value of T_CAS_CELL.PROVINCE * * @mbggenerated */ public String getProvince() { return province; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.PROVINCE * * @param province the value for T_CAS_CELL.PROVINCE * * @mbggenerated */ public void setProvince(String province) { this.province = province == null ? null : province.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.DEV_MODEL * * @return the value of T_CAS_CELL.DEV_MODEL * * @mbggenerated */ public String getDevModel() { return devModel; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.DEV_MODEL * * @param devModel the value for T_CAS_CELL.DEV_MODEL * * @mbggenerated */ public void setDevModel(String devModel) { this.devModel = devModel == null ? null : devModel.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.CABINET_TYPE * * @return the value of T_CAS_CELL.CABINET_TYPE * * @mbggenerated */ public String getCabinetType() { return cabinetType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.CABINET_TYPE * * @param cabinetType the value for T_CAS_CELL.CABINET_TYPE * * @mbggenerated */ public void setCabinetType(String cabinetType) { this.cabinetType = cabinetType == null ? null : cabinetType.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.CARRIER_TYPE * * @return the value of T_CAS_CELL.CARRIER_TYPE * * @mbggenerated */ public String getCarrierType() { return carrierType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.CARRIER_TYPE * * @param carrierType the value for T_CAS_CELL.CARRIER_TYPE * * @mbggenerated */ public void setCarrierType(String carrierType) { this.carrierType = carrierType == null ? null : carrierType.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SHARED_FEEDER * * @return the value of T_CAS_CELL.SHARED_FEEDER * * @mbggenerated */ public String getSharedFeeder() { return sharedFeeder; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SHARED_FEEDER * * @param sharedFeeder the value for T_CAS_CELL.SHARED_FEEDER * * @mbggenerated */ public void setSharedFeeder(String sharedFeeder) { this.sharedFeeder = sharedFeeder == null ? null : sharedFeeder.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SHARED_PLATFORM * * @return the value of T_CAS_CELL.SHARED_PLATFORM * * @mbggenerated */ public String getSharedPlatform() { return sharedPlatform; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SHARED_PLATFORM * * @param sharedPlatform the value for T_CAS_CELL.SHARED_PLATFORM * * @mbggenerated */ public void setSharedPlatform(String sharedPlatform) { this.sharedPlatform = sharedPlatform == null ? null : sharedPlatform.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.CELL_BAND * * @return the value of T_CAS_CELL.CELL_BAND * * @mbggenerated */ public Integer getCellBand() { return cellBand; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.CELL_BAND * * @param cellBand the value for T_CAS_CELL.CELL_BAND * * @mbggenerated */ public void setCellBand(Integer cellBand) { this.cellBand = cellBand; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.CELL_MARK * * @return the value of T_CAS_CELL.CELL_MARK * * @mbggenerated */ public String getCellMark() { return cellMark; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.CELL_MARK * * @param cellMark the value for T_CAS_CELL.CELL_MARK * * @mbggenerated */ public void setCellMark(String cellMark) { this.cellMark = cellMark == null ? null : cellMark.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.BSIC * * @return the value of T_CAS_CELL.BSIC * * @mbggenerated */ public BigDecimal getBsic() { return bsic; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.BSIC * * @param bsic the value for T_CAS_CELL.BSIC * * @mbggenerated */ public void setBsic(BigDecimal bsic) { this.bsic = bsic; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.TCH_FREQ * * @return the value of T_CAS_CELL.TCH_FREQ * * @mbggenerated */ public String getTchFreq() { return tchFreq; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.TCH_FREQ * * @param tchFreq the value for T_CAS_CELL.TCH_FREQ * * @mbggenerated */ public void setTchFreq(String tchFreq) { this.tchFreq = tchFreq == null ? null : tchFreq.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.CARR_FREQ_CNT * * @return the value of T_CAS_CELL.CARR_FREQ_CNT * * @mbggenerated */ public BigDecimal getCarrFreqCnt() { return carrFreqCnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.CARR_FREQ_CNT * * @param carrFreqCnt the value for T_CAS_CELL.CARR_FREQ_CNT * * @mbggenerated */ public void setCarrFreqCnt(BigDecimal carrFreqCnt) { this.carrFreqCnt = carrFreqCnt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.CARR_FREQ_AVAIL_CNT * * @return the value of T_CAS_CELL.CARR_FREQ_AVAIL_CNT * * @mbggenerated */ public BigDecimal getCarrFreqAvailCnt() { return carrFreqAvailCnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.CARR_FREQ_AVAIL_CNT * * @param carrFreqAvailCnt the value for T_CAS_CELL.CARR_FREQ_AVAIL_CNT * * @mbggenerated */ public void setCarrFreqAvailCnt(BigDecimal carrFreqAvailCnt) { this.carrFreqAvailCnt = carrFreqAvailCnt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.CARR_FREQ_MAX_POWER * * @return the value of T_CAS_CELL.CARR_FREQ_MAX_POWER * * @mbggenerated */ public BigDecimal getCarrFreqMaxPower() { return carrFreqMaxPower; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.CARR_FREQ_MAX_POWER * * @param carrFreqMaxPower the value for T_CAS_CELL.CARR_FREQ_MAX_POWER * * @mbggenerated */ public void setCarrFreqMaxPower(BigDecimal carrFreqMaxPower) { this.carrFreqMaxPower = carrFreqMaxPower; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.CTRL_CHANN_CNT * * @return the value of T_CAS_CELL.CTRL_CHANN_CNT * * @mbggenerated */ public BigDecimal getCtrlChannCnt() { return ctrlChannCnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.CTRL_CHANN_CNT * * @param ctrlChannCnt the value for T_CAS_CELL.CTRL_CHANN_CNT * * @mbggenerated */ public void setCtrlChannCnt(BigDecimal ctrlChannCnt) { this.ctrlChannCnt = ctrlChannCnt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.BUSI_CHANN_CNT * * @return the value of T_CAS_CELL.BUSI_CHANN_CNT * * @mbggenerated */ public BigDecimal getBusiChannCnt() { return busiChannCnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.BUSI_CHANN_CNT * * @param busiChannCnt the value for T_CAS_CELL.BUSI_CHANN_CNT * * @mbggenerated */ public void setBusiChannCnt(BigDecimal busiChannCnt) { this.busiChannCnt = busiChannCnt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.SDCCH_AVAIL_CNT * * @return the value of T_CAS_CELL.SDCCH_AVAIL_CNT * * @mbggenerated */ public BigDecimal getSdcchAvailCnt() { return sdcchAvailCnt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.SDCCH_AVAIL_CNT * * @param sdcchAvailCnt the value for T_CAS_CELL.SDCCH_AVAIL_CNT * * @mbggenerated */ public void setSdcchAvailCnt(BigDecimal sdcchAvailCnt) { this.sdcchAvailCnt = sdcchAvailCnt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.ANT_ELEV_ANGLE * * @return the value of T_CAS_CELL.ANT_ELEV_ANGLE * * @mbggenerated */ public BigDecimal getAntElevAngle() { return antElevAngle; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.ANT_ELEV_ANGLE * * @param antElevAngle the value for T_CAS_CELL.ANT_ELEV_ANGLE * * @mbggenerated */ public void setAntElevAngle(BigDecimal antElevAngle) { this.antElevAngle = antElevAngle; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.HOPPING_PATTERN * * @return the value of T_CAS_CELL.HOPPING_PATTERN * * @mbggenerated */ public String getHoppingPattern() { return hoppingPattern; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.HOPPING_PATTERN * * @param hoppingPattern the value for T_CAS_CELL.HOPPING_PATTERN * * @mbggenerated */ public void setHoppingPattern(String hoppingPattern) { this.hoppingPattern = hoppingPattern == null ? null : hoppingPattern.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.HALF_RATE_BOOL * * @return the value of T_CAS_CELL.HALF_RATE_BOOL * * @mbggenerated */ public String getHalfRateBool() { return halfRateBool; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.HALF_RATE_BOOL * * @param halfRateBool the value for T_CAS_CELL.HALF_RATE_BOOL * * @mbggenerated */ public void setHalfRateBool(String halfRateBool) { this.halfRateBool = halfRateBool == null ? null : halfRateBool.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GPRS_BOOL * * @return the value of T_CAS_CELL.GPRS_BOOL * * @mbggenerated */ public String getGprsBool() { return gprsBool; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GPRS_BOOL * * @param gprsBool the value for T_CAS_CELL.GPRS_BOOL * * @mbggenerated */ public void setGprsBool(String gprsBool) { this.gprsBool = gprsBool == null ? null : gprsBool.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.EDGE_BOOL * * @return the value of T_CAS_CELL.EDGE_BOOL * * @mbggenerated */ public String getEdgeBool() { return edgeBool; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.EDGE_BOOL * * @param edgeBool the value for T_CAS_CELL.EDGE_BOOL * * @mbggenerated */ public void setEdgeBool(String edgeBool) { this.edgeBool = edgeBool == null ? null : edgeBool.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.ENFULL_RATE_BOOL * * @return the value of T_CAS_CELL.ENFULL_RATE_BOOL * * @mbggenerated */ public String getEnfullRateBool() { return enfullRateBool; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.ENFULL_RATE_BOOL * * @param enfullRateBool the value for T_CAS_CELL.ENFULL_RATE_BOOL * * @mbggenerated */ public void setEnfullRateBool(String enfullRateBool) { this.enfullRateBool = enfullRateBool == null ? null : enfullRateBool.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL1 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL1 * * @mbggenerated */ public String getWcdmaNearCell1() { return wcdmaNearCell1; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL1 * * @param wcdmaNearCell1 the value for T_CAS_CELL.WCDMA_NEAR_CELL1 * * @mbggenerated */ public void setWcdmaNearCell1(String wcdmaNearCell1) { this.wcdmaNearCell1 = wcdmaNearCell1 == null ? null : wcdmaNearCell1.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL2 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL2 * * @mbggenerated */ public String getWcdmaNearCell2() { return wcdmaNearCell2; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL2 * * @param wcdmaNearCell2 the value for T_CAS_CELL.WCDMA_NEAR_CELL2 * * @mbggenerated */ public void setWcdmaNearCell2(String wcdmaNearCell2) { this.wcdmaNearCell2 = wcdmaNearCell2 == null ? null : wcdmaNearCell2.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL3 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL3 * * @mbggenerated */ public String getWcdmaNearCell3() { return wcdmaNearCell3; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL3 * * @param wcdmaNearCell3 the value for T_CAS_CELL.WCDMA_NEAR_CELL3 * * @mbggenerated */ public void setWcdmaNearCell3(String wcdmaNearCell3) { this.wcdmaNearCell3 = wcdmaNearCell3 == null ? null : wcdmaNearCell3.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL4 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL4 * * @mbggenerated */ public String getWcdmaNearCell4() { return wcdmaNearCell4; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL4 * * @param wcdmaNearCell4 the value for T_CAS_CELL.WCDMA_NEAR_CELL4 * * @mbggenerated */ public void setWcdmaNearCell4(String wcdmaNearCell4) { this.wcdmaNearCell4 = wcdmaNearCell4 == null ? null : wcdmaNearCell4.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL5 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL5 * * @mbggenerated */ public String getWcdmaNearCell5() { return wcdmaNearCell5; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL5 * * @param wcdmaNearCell5 the value for T_CAS_CELL.WCDMA_NEAR_CELL5 * * @mbggenerated */ public void setWcdmaNearCell5(String wcdmaNearCell5) { this.wcdmaNearCell5 = wcdmaNearCell5 == null ? null : wcdmaNearCell5.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL6 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL6 * * @mbggenerated */ public String getWcdmaNearCell6() { return wcdmaNearCell6; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL6 * * @param wcdmaNearCell6 the value for T_CAS_CELL.WCDMA_NEAR_CELL6 * * @mbggenerated */ public void setWcdmaNearCell6(String wcdmaNearCell6) { this.wcdmaNearCell6 = wcdmaNearCell6 == null ? null : wcdmaNearCell6.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL7 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL7 * * @mbggenerated */ public String getWcdmaNearCell7() { return wcdmaNearCell7; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL7 * * @param wcdmaNearCell7 the value for T_CAS_CELL.WCDMA_NEAR_CELL7 * * @mbggenerated */ public void setWcdmaNearCell7(String wcdmaNearCell7) { this.wcdmaNearCell7 = wcdmaNearCell7 == null ? null : wcdmaNearCell7.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL8 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL8 * * @mbggenerated */ public String getWcdmaNearCell8() { return wcdmaNearCell8; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL8 * * @param wcdmaNearCell8 the value for T_CAS_CELL.WCDMA_NEAR_CELL8 * * @mbggenerated */ public void setWcdmaNearCell8(String wcdmaNearCell8) { this.wcdmaNearCell8 = wcdmaNearCell8 == null ? null : wcdmaNearCell8.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL9 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL9 * * @mbggenerated */ public String getWcdmaNearCell9() { return wcdmaNearCell9; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL9 * * @param wcdmaNearCell9 the value for T_CAS_CELL.WCDMA_NEAR_CELL9 * * @mbggenerated */ public void setWcdmaNearCell9(String wcdmaNearCell9) { this.wcdmaNearCell9 = wcdmaNearCell9 == null ? null : wcdmaNearCell9.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL10 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL10 * * @mbggenerated */ public String getWcdmaNearCell10() { return wcdmaNearCell10; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL10 * * @param wcdmaNearCell10 the value for T_CAS_CELL.WCDMA_NEAR_CELL10 * * @mbggenerated */ public void setWcdmaNearCell10(String wcdmaNearCell10) { this.wcdmaNearCell10 = wcdmaNearCell10 == null ? null : wcdmaNearCell10.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL11 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL11 * * @mbggenerated */ public String getWcdmaNearCell11() { return wcdmaNearCell11; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL11 * * @param wcdmaNearCell11 the value for T_CAS_CELL.WCDMA_NEAR_CELL11 * * @mbggenerated */ public void setWcdmaNearCell11(String wcdmaNearCell11) { this.wcdmaNearCell11 = wcdmaNearCell11 == null ? null : wcdmaNearCell11.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL12 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL12 * * @mbggenerated */ public String getWcdmaNearCell12() { return wcdmaNearCell12; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL12 * * @param wcdmaNearCell12 the value for T_CAS_CELL.WCDMA_NEAR_CELL12 * * @mbggenerated */ public void setWcdmaNearCell12(String wcdmaNearCell12) { this.wcdmaNearCell12 = wcdmaNearCell12 == null ? null : wcdmaNearCell12.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL13 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL13 * * @mbggenerated */ public String getWcdmaNearCell13() { return wcdmaNearCell13; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL13 * * @param wcdmaNearCell13 the value for T_CAS_CELL.WCDMA_NEAR_CELL13 * * @mbggenerated */ public void setWcdmaNearCell13(String wcdmaNearCell13) { this.wcdmaNearCell13 = wcdmaNearCell13 == null ? null : wcdmaNearCell13.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL14 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL14 * * @mbggenerated */ public String getWcdmaNearCell14() { return wcdmaNearCell14; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL14 * * @param wcdmaNearCell14 the value for T_CAS_CELL.WCDMA_NEAR_CELL14 * * @mbggenerated */ public void setWcdmaNearCell14(String wcdmaNearCell14) { this.wcdmaNearCell14 = wcdmaNearCell14 == null ? null : wcdmaNearCell14.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL15 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL15 * * @mbggenerated */ public String getWcdmaNearCell15() { return wcdmaNearCell15; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL15 * * @param wcdmaNearCell15 the value for T_CAS_CELL.WCDMA_NEAR_CELL15 * * @mbggenerated */ public void setWcdmaNearCell15(String wcdmaNearCell15) { this.wcdmaNearCell15 = wcdmaNearCell15 == null ? null : wcdmaNearCell15.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL16 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL16 * * @mbggenerated */ public String getWcdmaNearCell16() { return wcdmaNearCell16; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL16 * * @param wcdmaNearCell16 the value for T_CAS_CELL.WCDMA_NEAR_CELL16 * * @mbggenerated */ public void setWcdmaNearCell16(String wcdmaNearCell16) { this.wcdmaNearCell16 = wcdmaNearCell16 == null ? null : wcdmaNearCell16.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL17 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL17 * * @mbggenerated */ public String getWcdmaNearCell17() { return wcdmaNearCell17; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL17 * * @param wcdmaNearCell17 the value for T_CAS_CELL.WCDMA_NEAR_CELL17 * * @mbggenerated */ public void setWcdmaNearCell17(String wcdmaNearCell17) { this.wcdmaNearCell17 = wcdmaNearCell17 == null ? null : wcdmaNearCell17.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL18 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL18 * * @mbggenerated */ public String getWcdmaNearCell18() { return wcdmaNearCell18; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL18 * * @param wcdmaNearCell18 the value for T_CAS_CELL.WCDMA_NEAR_CELL18 * * @mbggenerated */ public void setWcdmaNearCell18(String wcdmaNearCell18) { this.wcdmaNearCell18 = wcdmaNearCell18 == null ? null : wcdmaNearCell18.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL19 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL19 * * @mbggenerated */ public String getWcdmaNearCell19() { return wcdmaNearCell19; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL19 * * @param wcdmaNearCell19 the value for T_CAS_CELL.WCDMA_NEAR_CELL19 * * @mbggenerated */ public void setWcdmaNearCell19(String wcdmaNearCell19) { this.wcdmaNearCell19 = wcdmaNearCell19 == null ? null : wcdmaNearCell19.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL20 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL20 * * @mbggenerated */ public String getWcdmaNearCell20() { return wcdmaNearCell20; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL20 * * @param wcdmaNearCell20 the value for T_CAS_CELL.WCDMA_NEAR_CELL20 * * @mbggenerated */ public void setWcdmaNearCell20(String wcdmaNearCell20) { this.wcdmaNearCell20 = wcdmaNearCell20 == null ? null : wcdmaNearCell20.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL21 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL21 * * @mbggenerated */ public String getWcdmaNearCell21() { return wcdmaNearCell21; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL21 * * @param wcdmaNearCell21 the value for T_CAS_CELL.WCDMA_NEAR_CELL21 * * @mbggenerated */ public void setWcdmaNearCell21(String wcdmaNearCell21) { this.wcdmaNearCell21 = wcdmaNearCell21 == null ? null : wcdmaNearCell21.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL22 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL22 * * @mbggenerated */ public String getWcdmaNearCell22() { return wcdmaNearCell22; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL22 * * @param wcdmaNearCell22 the value for T_CAS_CELL.WCDMA_NEAR_CELL22 * * @mbggenerated */ public void setWcdmaNearCell22(String wcdmaNearCell22) { this.wcdmaNearCell22 = wcdmaNearCell22 == null ? null : wcdmaNearCell22.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL23 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL23 * * @mbggenerated */ public String getWcdmaNearCell23() { return wcdmaNearCell23; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL23 * * @param wcdmaNearCell23 the value for T_CAS_CELL.WCDMA_NEAR_CELL23 * * @mbggenerated */ public void setWcdmaNearCell23(String wcdmaNearCell23) { this.wcdmaNearCell23 = wcdmaNearCell23 == null ? null : wcdmaNearCell23.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL24 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL24 * * @mbggenerated */ public String getWcdmaNearCell24() { return wcdmaNearCell24; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL24 * * @param wcdmaNearCell24 the value for T_CAS_CELL.WCDMA_NEAR_CELL24 * * @mbggenerated */ public void setWcdmaNearCell24(String wcdmaNearCell24) { this.wcdmaNearCell24 = wcdmaNearCell24 == null ? null : wcdmaNearCell24.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL25 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL25 * * @mbggenerated */ public String getWcdmaNearCell25() { return wcdmaNearCell25; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL25 * * @param wcdmaNearCell25 the value for T_CAS_CELL.WCDMA_NEAR_CELL25 * * @mbggenerated */ public void setWcdmaNearCell25(String wcdmaNearCell25) { this.wcdmaNearCell25 = wcdmaNearCell25 == null ? null : wcdmaNearCell25.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL26 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL26 * * @mbggenerated */ public String getWcdmaNearCell26() { return wcdmaNearCell26; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL26 * * @param wcdmaNearCell26 the value for T_CAS_CELL.WCDMA_NEAR_CELL26 * * @mbggenerated */ public void setWcdmaNearCell26(String wcdmaNearCell26) { this.wcdmaNearCell26 = wcdmaNearCell26 == null ? null : wcdmaNearCell26.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL27 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL27 * * @mbggenerated */ public String getWcdmaNearCell27() { return wcdmaNearCell27; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL27 * * @param wcdmaNearCell27 the value for T_CAS_CELL.WCDMA_NEAR_CELL27 * * @mbggenerated */ public void setWcdmaNearCell27(String wcdmaNearCell27) { this.wcdmaNearCell27 = wcdmaNearCell27 == null ? null : wcdmaNearCell27.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL28 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL28 * * @mbggenerated */ public String getWcdmaNearCell28() { return wcdmaNearCell28; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL28 * * @param wcdmaNearCell28 the value for T_CAS_CELL.WCDMA_NEAR_CELL28 * * @mbggenerated */ public void setWcdmaNearCell28(String wcdmaNearCell28) { this.wcdmaNearCell28 = wcdmaNearCell28 == null ? null : wcdmaNearCell28.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL29 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL29 * * @mbggenerated */ public String getWcdmaNearCell29() { return wcdmaNearCell29; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL29 * * @param wcdmaNearCell29 the value for T_CAS_CELL.WCDMA_NEAR_CELL29 * * @mbggenerated */ public void setWcdmaNearCell29(String wcdmaNearCell29) { this.wcdmaNearCell29 = wcdmaNearCell29 == null ? null : wcdmaNearCell29.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL30 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL30 * * @mbggenerated */ public String getWcdmaNearCell30() { return wcdmaNearCell30; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL30 * * @param wcdmaNearCell30 the value for T_CAS_CELL.WCDMA_NEAR_CELL30 * * @mbggenerated */ public void setWcdmaNearCell30(String wcdmaNearCell30) { this.wcdmaNearCell30 = wcdmaNearCell30 == null ? null : wcdmaNearCell30.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL31 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL31 * * @mbggenerated */ public String getWcdmaNearCell31() { return wcdmaNearCell31; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL31 * * @param wcdmaNearCell31 the value for T_CAS_CELL.WCDMA_NEAR_CELL31 * * @mbggenerated */ public void setWcdmaNearCell31(String wcdmaNearCell31) { this.wcdmaNearCell31 = wcdmaNearCell31 == null ? null : wcdmaNearCell31.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL32 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL32 * * @mbggenerated */ public String getWcdmaNearCell32() { return wcdmaNearCell32; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL32 * * @param wcdmaNearCell32 the value for T_CAS_CELL.WCDMA_NEAR_CELL32 * * @mbggenerated */ public void setWcdmaNearCell32(String wcdmaNearCell32) { this.wcdmaNearCell32 = wcdmaNearCell32 == null ? null : wcdmaNearCell32.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL33 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL33 * * @mbggenerated */ public String getWcdmaNearCell33() { return wcdmaNearCell33; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL33 * * @param wcdmaNearCell33 the value for T_CAS_CELL.WCDMA_NEAR_CELL33 * * @mbggenerated */ public void setWcdmaNearCell33(String wcdmaNearCell33) { this.wcdmaNearCell33 = wcdmaNearCell33 == null ? null : wcdmaNearCell33.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL34 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL34 * * @mbggenerated */ public String getWcdmaNearCell34() { return wcdmaNearCell34; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL34 * * @param wcdmaNearCell34 the value for T_CAS_CELL.WCDMA_NEAR_CELL34 * * @mbggenerated */ public void setWcdmaNearCell34(String wcdmaNearCell34) { this.wcdmaNearCell34 = wcdmaNearCell34 == null ? null : wcdmaNearCell34.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL35 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL35 * * @mbggenerated */ public String getWcdmaNearCell35() { return wcdmaNearCell35; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL35 * * @param wcdmaNearCell35 the value for T_CAS_CELL.WCDMA_NEAR_CELL35 * * @mbggenerated */ public void setWcdmaNearCell35(String wcdmaNearCell35) { this.wcdmaNearCell35 = wcdmaNearCell35 == null ? null : wcdmaNearCell35.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL36 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL36 * * @mbggenerated */ public String getWcdmaNearCell36() { return wcdmaNearCell36; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL36 * * @param wcdmaNearCell36 the value for T_CAS_CELL.WCDMA_NEAR_CELL36 * * @mbggenerated */ public void setWcdmaNearCell36(String wcdmaNearCell36) { this.wcdmaNearCell36 = wcdmaNearCell36 == null ? null : wcdmaNearCell36.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL37 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL37 * * @mbggenerated */ public String getWcdmaNearCell37() { return wcdmaNearCell37; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL37 * * @param wcdmaNearCell37 the value for T_CAS_CELL.WCDMA_NEAR_CELL37 * * @mbggenerated */ public void setWcdmaNearCell37(String wcdmaNearCell37) { this.wcdmaNearCell37 = wcdmaNearCell37 == null ? null : wcdmaNearCell37.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL38 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL38 * * @mbggenerated */ public String getWcdmaNearCell38() { return wcdmaNearCell38; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL38 * * @param wcdmaNearCell38 the value for T_CAS_CELL.WCDMA_NEAR_CELL38 * * @mbggenerated */ public void setWcdmaNearCell38(String wcdmaNearCell38) { this.wcdmaNearCell38 = wcdmaNearCell38 == null ? null : wcdmaNearCell38.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL39 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL39 * * @mbggenerated */ public String getWcdmaNearCell39() { return wcdmaNearCell39; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL39 * * @param wcdmaNearCell39 the value for T_CAS_CELL.WCDMA_NEAR_CELL39 * * @mbggenerated */ public void setWcdmaNearCell39(String wcdmaNearCell39) { this.wcdmaNearCell39 = wcdmaNearCell39 == null ? null : wcdmaNearCell39.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL40 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL40 * * @mbggenerated */ public String getWcdmaNearCell40() { return wcdmaNearCell40; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL40 * * @param wcdmaNearCell40 the value for T_CAS_CELL.WCDMA_NEAR_CELL40 * * @mbggenerated */ public void setWcdmaNearCell40(String wcdmaNearCell40) { this.wcdmaNearCell40 = wcdmaNearCell40 == null ? null : wcdmaNearCell40.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL41 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL41 * * @mbggenerated */ public String getWcdmaNearCell41() { return wcdmaNearCell41; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL41 * * @param wcdmaNearCell41 the value for T_CAS_CELL.WCDMA_NEAR_CELL41 * * @mbggenerated */ public void setWcdmaNearCell41(String wcdmaNearCell41) { this.wcdmaNearCell41 = wcdmaNearCell41 == null ? null : wcdmaNearCell41.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL42 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL42 * * @mbggenerated */ public String getWcdmaNearCell42() { return wcdmaNearCell42; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL42 * * @param wcdmaNearCell42 the value for T_CAS_CELL.WCDMA_NEAR_CELL42 * * @mbggenerated */ public void setWcdmaNearCell42(String wcdmaNearCell42) { this.wcdmaNearCell42 = wcdmaNearCell42 == null ? null : wcdmaNearCell42.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL43 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL43 * * @mbggenerated */ public String getWcdmaNearCell43() { return wcdmaNearCell43; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL43 * * @param wcdmaNearCell43 the value for T_CAS_CELL.WCDMA_NEAR_CELL43 * * @mbggenerated */ public void setWcdmaNearCell43(String wcdmaNearCell43) { this.wcdmaNearCell43 = wcdmaNearCell43 == null ? null : wcdmaNearCell43.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL44 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL44 * * @mbggenerated */ public String getWcdmaNearCell44() { return wcdmaNearCell44; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL44 * * @param wcdmaNearCell44 the value for T_CAS_CELL.WCDMA_NEAR_CELL44 * * @mbggenerated */ public void setWcdmaNearCell44(String wcdmaNearCell44) { this.wcdmaNearCell44 = wcdmaNearCell44 == null ? null : wcdmaNearCell44.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL45 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL45 * * @mbggenerated */ public String getWcdmaNearCell45() { return wcdmaNearCell45; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL45 * * @param wcdmaNearCell45 the value for T_CAS_CELL.WCDMA_NEAR_CELL45 * * @mbggenerated */ public void setWcdmaNearCell45(String wcdmaNearCell45) { this.wcdmaNearCell45 = wcdmaNearCell45 == null ? null : wcdmaNearCell45.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL46 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL46 * * @mbggenerated */ public String getWcdmaNearCell46() { return wcdmaNearCell46; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL46 * * @param wcdmaNearCell46 the value for T_CAS_CELL.WCDMA_NEAR_CELL46 * * @mbggenerated */ public void setWcdmaNearCell46(String wcdmaNearCell46) { this.wcdmaNearCell46 = wcdmaNearCell46 == null ? null : wcdmaNearCell46.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL47 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL47 * * @mbggenerated */ public String getWcdmaNearCell47() { return wcdmaNearCell47; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL47 * * @param wcdmaNearCell47 the value for T_CAS_CELL.WCDMA_NEAR_CELL47 * * @mbggenerated */ public void setWcdmaNearCell47(String wcdmaNearCell47) { this.wcdmaNearCell47 = wcdmaNearCell47 == null ? null : wcdmaNearCell47.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL48 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL48 * * @mbggenerated */ public String getWcdmaNearCell48() { return wcdmaNearCell48; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL48 * * @param wcdmaNearCell48 the value for T_CAS_CELL.WCDMA_NEAR_CELL48 * * @mbggenerated */ public void setWcdmaNearCell48(String wcdmaNearCell48) { this.wcdmaNearCell48 = wcdmaNearCell48 == null ? null : wcdmaNearCell48.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL49 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL49 * * @mbggenerated */ public String getWcdmaNearCell49() { return wcdmaNearCell49; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL49 * * @param wcdmaNearCell49 the value for T_CAS_CELL.WCDMA_NEAR_CELL49 * * @mbggenerated */ public void setWcdmaNearCell49(String wcdmaNearCell49) { this.wcdmaNearCell49 = wcdmaNearCell49 == null ? null : wcdmaNearCell49.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL50 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL50 * * @mbggenerated */ public String getWcdmaNearCell50() { return wcdmaNearCell50; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL50 * * @param wcdmaNearCell50 the value for T_CAS_CELL.WCDMA_NEAR_CELL50 * * @mbggenerated */ public void setWcdmaNearCell50(String wcdmaNearCell50) { this.wcdmaNearCell50 = wcdmaNearCell50 == null ? null : wcdmaNearCell50.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL51 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL51 * * @mbggenerated */ public String getWcdmaNearCell51() { return wcdmaNearCell51; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL51 * * @param wcdmaNearCell51 the value for T_CAS_CELL.WCDMA_NEAR_CELL51 * * @mbggenerated */ public void setWcdmaNearCell51(String wcdmaNearCell51) { this.wcdmaNearCell51 = wcdmaNearCell51 == null ? null : wcdmaNearCell51.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL52 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL52 * * @mbggenerated */ public String getWcdmaNearCell52() { return wcdmaNearCell52; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL52 * * @param wcdmaNearCell52 the value for T_CAS_CELL.WCDMA_NEAR_CELL52 * * @mbggenerated */ public void setWcdmaNearCell52(String wcdmaNearCell52) { this.wcdmaNearCell52 = wcdmaNearCell52 == null ? null : wcdmaNearCell52.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL53 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL53 * * @mbggenerated */ public String getWcdmaNearCell53() { return wcdmaNearCell53; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL53 * * @param wcdmaNearCell53 the value for T_CAS_CELL.WCDMA_NEAR_CELL53 * * @mbggenerated */ public void setWcdmaNearCell53(String wcdmaNearCell53) { this.wcdmaNearCell53 = wcdmaNearCell53 == null ? null : wcdmaNearCell53.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL54 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL54 * * @mbggenerated */ public String getWcdmaNearCell54() { return wcdmaNearCell54; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL54 * * @param wcdmaNearCell54 the value for T_CAS_CELL.WCDMA_NEAR_CELL54 * * @mbggenerated */ public void setWcdmaNearCell54(String wcdmaNearCell54) { this.wcdmaNearCell54 = wcdmaNearCell54 == null ? null : wcdmaNearCell54.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL55 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL55 * * @mbggenerated */ public String getWcdmaNearCell55() { return wcdmaNearCell55; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL55 * * @param wcdmaNearCell55 the value for T_CAS_CELL.WCDMA_NEAR_CELL55 * * @mbggenerated */ public void setWcdmaNearCell55(String wcdmaNearCell55) { this.wcdmaNearCell55 = wcdmaNearCell55 == null ? null : wcdmaNearCell55.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL56 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL56 * * @mbggenerated */ public String getWcdmaNearCell56() { return wcdmaNearCell56; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL56 * * @param wcdmaNearCell56 the value for T_CAS_CELL.WCDMA_NEAR_CELL56 * * @mbggenerated */ public void setWcdmaNearCell56(String wcdmaNearCell56) { this.wcdmaNearCell56 = wcdmaNearCell56 == null ? null : wcdmaNearCell56.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL57 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL57 * * @mbggenerated */ public String getWcdmaNearCell57() { return wcdmaNearCell57; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL57 * * @param wcdmaNearCell57 the value for T_CAS_CELL.WCDMA_NEAR_CELL57 * * @mbggenerated */ public void setWcdmaNearCell57(String wcdmaNearCell57) { this.wcdmaNearCell57 = wcdmaNearCell57 == null ? null : wcdmaNearCell57.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL58 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL58 * * @mbggenerated */ public String getWcdmaNearCell58() { return wcdmaNearCell58; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL58 * * @param wcdmaNearCell58 the value for T_CAS_CELL.WCDMA_NEAR_CELL58 * * @mbggenerated */ public void setWcdmaNearCell58(String wcdmaNearCell58) { this.wcdmaNearCell58 = wcdmaNearCell58 == null ? null : wcdmaNearCell58.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL59 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL59 * * @mbggenerated */ public String getWcdmaNearCell59() { return wcdmaNearCell59; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL59 * * @param wcdmaNearCell59 the value for T_CAS_CELL.WCDMA_NEAR_CELL59 * * @mbggenerated */ public void setWcdmaNearCell59(String wcdmaNearCell59) { this.wcdmaNearCell59 = wcdmaNearCell59 == null ? null : wcdmaNearCell59.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL60 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL60 * * @mbggenerated */ public String getWcdmaNearCell60() { return wcdmaNearCell60; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL60 * * @param wcdmaNearCell60 the value for T_CAS_CELL.WCDMA_NEAR_CELL60 * * @mbggenerated */ public void setWcdmaNearCell60(String wcdmaNearCell60) { this.wcdmaNearCell60 = wcdmaNearCell60 == null ? null : wcdmaNearCell60.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL61 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL61 * * @mbggenerated */ public String getWcdmaNearCell61() { return wcdmaNearCell61; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL61 * * @param wcdmaNearCell61 the value for T_CAS_CELL.WCDMA_NEAR_CELL61 * * @mbggenerated */ public void setWcdmaNearCell61(String wcdmaNearCell61) { this.wcdmaNearCell61 = wcdmaNearCell61 == null ? null : wcdmaNearCell61.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL62 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL62 * * @mbggenerated */ public String getWcdmaNearCell62() { return wcdmaNearCell62; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL62 * * @param wcdmaNearCell62 the value for T_CAS_CELL.WCDMA_NEAR_CELL62 * * @mbggenerated */ public void setWcdmaNearCell62(String wcdmaNearCell62) { this.wcdmaNearCell62 = wcdmaNearCell62 == null ? null : wcdmaNearCell62.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL63 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL63 * * @mbggenerated */ public String getWcdmaNearCell63() { return wcdmaNearCell63; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL63 * * @param wcdmaNearCell63 the value for T_CAS_CELL.WCDMA_NEAR_CELL63 * * @mbggenerated */ public void setWcdmaNearCell63(String wcdmaNearCell63) { this.wcdmaNearCell63 = wcdmaNearCell63 == null ? null : wcdmaNearCell63.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL64 * * @return the value of T_CAS_CELL.WCDMA_NEAR_CELL64 * * @mbggenerated */ public String getWcdmaNearCell64() { return wcdmaNearCell64; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.WCDMA_NEAR_CELL64 * * @param wcdmaNearCell64 the value for T_CAS_CELL.WCDMA_NEAR_CELL64 * * @mbggenerated */ public void setWcdmaNearCell64(String wcdmaNearCell64) { this.wcdmaNearCell64 = wcdmaNearCell64 == null ? null : wcdmaNearCell64.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL1 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL1 * * @mbggenerated */ public String getGsmNearCell1() { return gsmNearCell1; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL1 * * @param gsmNearCell1 the value for T_CAS_CELL.GSM_NEAR_CELL1 * * @mbggenerated */ public void setGsmNearCell1(String gsmNearCell1) { this.gsmNearCell1 = gsmNearCell1 == null ? null : gsmNearCell1.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL2 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL2 * * @mbggenerated */ public String getGsmNearCell2() { return gsmNearCell2; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL2 * * @param gsmNearCell2 the value for T_CAS_CELL.GSM_NEAR_CELL2 * * @mbggenerated */ public void setGsmNearCell2(String gsmNearCell2) { this.gsmNearCell2 = gsmNearCell2 == null ? null : gsmNearCell2.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL3 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL3 * * @mbggenerated */ public String getGsmNearCell3() { return gsmNearCell3; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL3 * * @param gsmNearCell3 the value for T_CAS_CELL.GSM_NEAR_CELL3 * * @mbggenerated */ public void setGsmNearCell3(String gsmNearCell3) { this.gsmNearCell3 = gsmNearCell3 == null ? null : gsmNearCell3.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL4 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL4 * * @mbggenerated */ public String getGsmNearCell4() { return gsmNearCell4; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL4 * * @param gsmNearCell4 the value for T_CAS_CELL.GSM_NEAR_CELL4 * * @mbggenerated */ public void setGsmNearCell4(String gsmNearCell4) { this.gsmNearCell4 = gsmNearCell4 == null ? null : gsmNearCell4.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL5 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL5 * * @mbggenerated */ public String getGsmNearCell5() { return gsmNearCell5; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL5 * * @param gsmNearCell5 the value for T_CAS_CELL.GSM_NEAR_CELL5 * * @mbggenerated */ public void setGsmNearCell5(String gsmNearCell5) { this.gsmNearCell5 = gsmNearCell5 == null ? null : gsmNearCell5.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL6 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL6 * * @mbggenerated */ public String getGsmNearCell6() { return gsmNearCell6; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL6 * * @param gsmNearCell6 the value for T_CAS_CELL.GSM_NEAR_CELL6 * * @mbggenerated */ public void setGsmNearCell6(String gsmNearCell6) { this.gsmNearCell6 = gsmNearCell6 == null ? null : gsmNearCell6.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL7 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL7 * * @mbggenerated */ public String getGsmNearCell7() { return gsmNearCell7; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL7 * * @param gsmNearCell7 the value for T_CAS_CELL.GSM_NEAR_CELL7 * * @mbggenerated */ public void setGsmNearCell7(String gsmNearCell7) { this.gsmNearCell7 = gsmNearCell7 == null ? null : gsmNearCell7.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL8 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL8 * * @mbggenerated */ public String getGsmNearCell8() { return gsmNearCell8; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL8 * * @param gsmNearCell8 the value for T_CAS_CELL.GSM_NEAR_CELL8 * * @mbggenerated */ public void setGsmNearCell8(String gsmNearCell8) { this.gsmNearCell8 = gsmNearCell8 == null ? null : gsmNearCell8.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL9 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL9 * * @mbggenerated */ public String getGsmNearCell9() { return gsmNearCell9; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL9 * * @param gsmNearCell9 the value for T_CAS_CELL.GSM_NEAR_CELL9 * * @mbggenerated */ public void setGsmNearCell9(String gsmNearCell9) { this.gsmNearCell9 = gsmNearCell9 == null ? null : gsmNearCell9.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL10 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL10 * * @mbggenerated */ public String getGsmNearCell10() { return gsmNearCell10; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL10 * * @param gsmNearCell10 the value for T_CAS_CELL.GSM_NEAR_CELL10 * * @mbggenerated */ public void setGsmNearCell10(String gsmNearCell10) { this.gsmNearCell10 = gsmNearCell10 == null ? null : gsmNearCell10.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL11 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL11 * * @mbggenerated */ public String getGsmNearCell11() { return gsmNearCell11; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL11 * * @param gsmNearCell11 the value for T_CAS_CELL.GSM_NEAR_CELL11 * * @mbggenerated */ public void setGsmNearCell11(String gsmNearCell11) { this.gsmNearCell11 = gsmNearCell11 == null ? null : gsmNearCell11.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL12 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL12 * * @mbggenerated */ public String getGsmNearCell12() { return gsmNearCell12; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL12 * * @param gsmNearCell12 the value for T_CAS_CELL.GSM_NEAR_CELL12 * * @mbggenerated */ public void setGsmNearCell12(String gsmNearCell12) { this.gsmNearCell12 = gsmNearCell12 == null ? null : gsmNearCell12.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL13 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL13 * * @mbggenerated */ public String getGsmNearCell13() { return gsmNearCell13; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL13 * * @param gsmNearCell13 the value for T_CAS_CELL.GSM_NEAR_CELL13 * * @mbggenerated */ public void setGsmNearCell13(String gsmNearCell13) { this.gsmNearCell13 = gsmNearCell13 == null ? null : gsmNearCell13.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL14 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL14 * * @mbggenerated */ public String getGsmNearCell14() { return gsmNearCell14; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL14 * * @param gsmNearCell14 the value for T_CAS_CELL.GSM_NEAR_CELL14 * * @mbggenerated */ public void setGsmNearCell14(String gsmNearCell14) { this.gsmNearCell14 = gsmNearCell14 == null ? null : gsmNearCell14.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL15 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL15 * * @mbggenerated */ public String getGsmNearCell15() { return gsmNearCell15; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL15 * * @param gsmNearCell15 the value for T_CAS_CELL.GSM_NEAR_CELL15 * * @mbggenerated */ public void setGsmNearCell15(String gsmNearCell15) { this.gsmNearCell15 = gsmNearCell15 == null ? null : gsmNearCell15.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL16 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL16 * * @mbggenerated */ public String getGsmNearCell16() { return gsmNearCell16; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL16 * * @param gsmNearCell16 the value for T_CAS_CELL.GSM_NEAR_CELL16 * * @mbggenerated */ public void setGsmNearCell16(String gsmNearCell16) { this.gsmNearCell16 = gsmNearCell16 == null ? null : gsmNearCell16.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL17 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL17 * * @mbggenerated */ public String getGsmNearCell17() { return gsmNearCell17; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL17 * * @param gsmNearCell17 the value for T_CAS_CELL.GSM_NEAR_CELL17 * * @mbggenerated */ public void setGsmNearCell17(String gsmNearCell17) { this.gsmNearCell17 = gsmNearCell17 == null ? null : gsmNearCell17.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL18 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL18 * * @mbggenerated */ public String getGsmNearCell18() { return gsmNearCell18; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL18 * * @param gsmNearCell18 the value for T_CAS_CELL.GSM_NEAR_CELL18 * * @mbggenerated */ public void setGsmNearCell18(String gsmNearCell18) { this.gsmNearCell18 = gsmNearCell18 == null ? null : gsmNearCell18.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL19 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL19 * * @mbggenerated */ public String getGsmNearCell19() { return gsmNearCell19; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL19 * * @param gsmNearCell19 the value for T_CAS_CELL.GSM_NEAR_CELL19 * * @mbggenerated */ public void setGsmNearCell19(String gsmNearCell19) { this.gsmNearCell19 = gsmNearCell19 == null ? null : gsmNearCell19.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL20 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL20 * * @mbggenerated */ public String getGsmNearCell20() { return gsmNearCell20; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL20 * * @param gsmNearCell20 the value for T_CAS_CELL.GSM_NEAR_CELL20 * * @mbggenerated */ public void setGsmNearCell20(String gsmNearCell20) { this.gsmNearCell20 = gsmNearCell20 == null ? null : gsmNearCell20.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL21 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL21 * * @mbggenerated */ public String getGsmNearCell21() { return gsmNearCell21; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL21 * * @param gsmNearCell21 the value for T_CAS_CELL.GSM_NEAR_CELL21 * * @mbggenerated */ public void setGsmNearCell21(String gsmNearCell21) { this.gsmNearCell21 = gsmNearCell21 == null ? null : gsmNearCell21.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL22 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL22 * * @mbggenerated */ public String getGsmNearCell22() { return gsmNearCell22; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL22 * * @param gsmNearCell22 the value for T_CAS_CELL.GSM_NEAR_CELL22 * * @mbggenerated */ public void setGsmNearCell22(String gsmNearCell22) { this.gsmNearCell22 = gsmNearCell22 == null ? null : gsmNearCell22.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL23 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL23 * * @mbggenerated */ public String getGsmNearCell23() { return gsmNearCell23; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL23 * * @param gsmNearCell23 the value for T_CAS_CELL.GSM_NEAR_CELL23 * * @mbggenerated */ public void setGsmNearCell23(String gsmNearCell23) { this.gsmNearCell23 = gsmNearCell23 == null ? null : gsmNearCell23.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL24 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL24 * * @mbggenerated */ public String getGsmNearCell24() { return gsmNearCell24; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL24 * * @param gsmNearCell24 the value for T_CAS_CELL.GSM_NEAR_CELL24 * * @mbggenerated */ public void setGsmNearCell24(String gsmNearCell24) { this.gsmNearCell24 = gsmNearCell24 == null ? null : gsmNearCell24.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL25 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL25 * * @mbggenerated */ public String getGsmNearCell25() { return gsmNearCell25; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL25 * * @param gsmNearCell25 the value for T_CAS_CELL.GSM_NEAR_CELL25 * * @mbggenerated */ public void setGsmNearCell25(String gsmNearCell25) { this.gsmNearCell25 = gsmNearCell25 == null ? null : gsmNearCell25.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL26 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL26 * * @mbggenerated */ public String getGsmNearCell26() { return gsmNearCell26; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL26 * * @param gsmNearCell26 the value for T_CAS_CELL.GSM_NEAR_CELL26 * * @mbggenerated */ public void setGsmNearCell26(String gsmNearCell26) { this.gsmNearCell26 = gsmNearCell26 == null ? null : gsmNearCell26.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL27 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL27 * * @mbggenerated */ public String getGsmNearCell27() { return gsmNearCell27; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL27 * * @param gsmNearCell27 the value for T_CAS_CELL.GSM_NEAR_CELL27 * * @mbggenerated */ public void setGsmNearCell27(String gsmNearCell27) { this.gsmNearCell27 = gsmNearCell27 == null ? null : gsmNearCell27.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL28 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL28 * * @mbggenerated */ public String getGsmNearCell28() { return gsmNearCell28; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL28 * * @param gsmNearCell28 the value for T_CAS_CELL.GSM_NEAR_CELL28 * * @mbggenerated */ public void setGsmNearCell28(String gsmNearCell28) { this.gsmNearCell28 = gsmNearCell28 == null ? null : gsmNearCell28.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL29 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL29 * * @mbggenerated */ public String getGsmNearCell29() { return gsmNearCell29; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL29 * * @param gsmNearCell29 the value for T_CAS_CELL.GSM_NEAR_CELL29 * * @mbggenerated */ public void setGsmNearCell29(String gsmNearCell29) { this.gsmNearCell29 = gsmNearCell29 == null ? null : gsmNearCell29.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL30 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL30 * * @mbggenerated */ public String getGsmNearCell30() { return gsmNearCell30; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL30 * * @param gsmNearCell30 the value for T_CAS_CELL.GSM_NEAR_CELL30 * * @mbggenerated */ public void setGsmNearCell30(String gsmNearCell30) { this.gsmNearCell30 = gsmNearCell30 == null ? null : gsmNearCell30.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL31 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL31 * * @mbggenerated */ public String getGsmNearCell31() { return gsmNearCell31; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL31 * * @param gsmNearCell31 the value for T_CAS_CELL.GSM_NEAR_CELL31 * * @mbggenerated */ public void setGsmNearCell31(String gsmNearCell31) { this.gsmNearCell31 = gsmNearCell31 == null ? null : gsmNearCell31.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.GSM_NEAR_CELL32 * * @return the value of T_CAS_CELL.GSM_NEAR_CELL32 * * @mbggenerated */ public String getGsmNearCell32() { return gsmNearCell32; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.GSM_NEAR_CELL32 * * @param gsmNearCell32 the value for T_CAS_CELL.GSM_NEAR_CELL32 * * @mbggenerated */ public void setGsmNearCell32(String gsmNearCell32) { this.gsmNearCell32 = gsmNearCell32 == null ? null : gsmNearCell32.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.CID * * @return the value of T_CAS_CELL.CID * * @mbggenerated */ public BigDecimal getCid() { return cid; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.CID * * @param cid the value for T_CAS_CELL.CID * * @mbggenerated */ public void setCid(BigDecimal cid) { this.cid = cid; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column T_CAS_CELL.LAC * * @return the value of T_CAS_CELL.LAC * * @mbggenerated */ public BigDecimal getLac() { return lac; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column T_CAS_CELL.LAC * * @param lac the value for T_CAS_CELL.LAC * * @mbggenerated */ public void setLac(BigDecimal lac) { this.lac = lac; } }<file_sep>/src/main/webapp/js/ftp/update.js $(function(){ $("#parent").attr('checked',false); $("#parent").click(function () { if($("#parent").attr('checked') == undefined){ $('input[name="ids"]').attr('checked',false); }else{ $('input[name="ids"]').attr('checked',true); } }); var count =0; //增加页面打开 $('.add').click(function(){ $("#dlg").dialog({ href:contextPath + '/ftp/addftp', height: 510,width: 435,title: "新增FTP配置", modal: true,closed:false }); $('#dlg').dialog('open'); $.parser.parse('#dlg'); $("#valiSelect").val("0"); }); //修改和新增保存 $('.saveedit').click(function(){ if(count==0){ count++; var operationType = $("#type").val(); if(parseInt(operationType)==0){ //0为新增 $('#dataForm').ajaxForm({ url: contextPath + "/ftp/addftp", beforeSubmit:function(){ if(!$('#dataForm').form('validate')){ count=0; return false; }else{ $(".right1").show(); return true; } },success:function(data) { $(".right1").hide(); count=0; addOrEdit(data.msg,data.statuNull); } }); $("#dataForm").submit(); }else if(parseInt(operationType)==1){ //1为修改 $('#dataForm').ajaxForm({ url: contextPath + "/ftp/editftp", beforeSubmit:function(){ if(!$('#dataForm').form('validate')){ count=0; return false; }else{ $(".right1").show(); return true; } },success:function(data) { $(".right1").hide(); count=0; addOrEdit(data.msg,data.statuNull); } }); $("#dataForm").submit(); } } }); var optInit = {callback:function(page_index,jq){ $.ajax({ type:"post", url: contextPath + "/ftp/updateFtp/template", data:({name: $("#hiddenval").val(),pageIndex: page_index}), success: function(data){ $("#content").html(data); //单个删除 $(".del").click(function(){ var str = $(this).attr("id"); var staid = $("input[name='sta']").val(); var flag = false; if(parseInt(staid)==parseInt(str)){ flag=true } deleteFtp(str,flag,'single'); }); //修改页面打开 $('.edit').click(function(){ var id = $(this).attr("id"); $("#dlg").dialog({ href:contextPath + '/ftp/editftp?id='+id, height: 510,width: 435,title: "修改FTP配置", modal: true,closed:false }); $('#dlg').dialog('open'); $.parser.parse('#dlg'); $("#valiSelect").val("1"); }); //启用该项 $(".staUse").click(function(){ var sta = $(this).attr("name"); var sid = parseInt($("#num"+sta).attr("name")); var id = parseInt(sta); if(sid==0){ $.messager.confirm("提示","确认启用此项配置!",function(r){ if(r){ $.ajax({ type:'post', url: contextPath + "/ftp/staUse", data: ({id:id}), success:function(data) { if(data.msg==1){ $.messager.alert("提示","启用成功!","success",function(){ location.href= contextPath + "/ftp/updateFtp"; }); }else if(data.msg==0){ $.messager.alert("提示","启用失败!","error"); } } }); } }); }else if(sid==1){ $.messager.alert("提示","此项已启动!","error"); } }); //修改该项 $(".staOff").click(function(){ var sta = $(this).attr("name"); var sid = parseInt($("#num"+sta).attr("name")); var id = parseInt(sta); if(sid==1){ $.messager.confirm("提示","确认要禁用这项配置!",function(r){ if(r){ $.ajax({ type:'post', url: contextPath + "/ftp/staOff", data: ({id:id}), success:function(data) { if(data.msg==1){ $.messager.alert("提示","禁用成功!","success",function(){ location.href= contextPath + "/ftp/updateFtp"; }); }else if(data.msg==0){ $.messager.alert("提示","禁用失败!","error"); } } }); } }); }else if(sid==0){ $.messager.alert("提示","此项尚未启动!","error"); } }); } }); } }; $("#pager").pagination(pageTotal, optInit);//回调 /** * 多个删除 */ $("#delall").click(function(){ var str = ""; var staid = $("input[name='sta']").val(); var flag = false; $("input[name='ids']:checked").each(function(){ str +=$(this).val()+","; if($(this).val()==staid){ flag = true; } }); if(str!=""&&str.length>1){ str = str.substring(0, str.length-1); deleteFtp(str,flag,'multiterm'); }else{ $.messager.alert("提示","请选择你要删除的FTP配置!","warning"); } }); }); /** * 执行删除方法 */ function deleteFtp(ids,flag,quantity){ var word ; if(flag){ if(quantity == 'multiterm'){ word = '将要删除的选项中包含启用项,是否要继续删除?'; }else if(quantity == 'single'){ word = '将要删除的为启用项,是否要继续删除?'; } }else{ word = '是否删除你选择的FTP配置?'; } $.messager.confirm('提示', word,function(r){ if(r){ $.ajax({ type:'post', url:contextPath +"/ftp/delftp", data:({ids:ids}), success:function(data){ if(data.msg==1){ $.messager.alert("提示","删除成功!","success",function(){ location.href= contextPath + "/ftp/updateFtp"; }); }else{ $.messager.alert("提示","删除失败!","error"); } } }); } }); } /** *修改和新增返回结果 */ function addOrEdit(result,sta){ var msg = parseInt(result); if(msg == 0){ $.messager.alert("提示","FTP服务器新增成功!","success",function(){ if(parseInt(sta)==0){ $.messager.alert("提示","你还没有任何一项配置被启用!","success",function(){ location.href= contextPath + "/ftp/updateFtp"; }); }else{ location.href= contextPath + "/ftp/updateFtp"; } }); }else if(msg == 1){ $.messager.alert("提示","FTP服务器修改成功!","success",function(){ if(parseInt(sta)==0){ $.messager.alert("提示","你还没有任何一项配置被启用!","success",function(){ location.href= contextPath + "/ftp/updateFtp"; }); }else{ location.href= contextPath + "/ftp/updateFtp"; } }); }else if(msg == 3){ $.messager.alert("提示","IP或端口号错误!","error",function(){ }); }else if(msg == 4){ $.messager.alert("提示","用户或密码错误!","error",function(){ }); }else if(msg == 5){ $.messager.alert("提示","FTP服务器连接失败,请检查!","error",function(){ }); }else if(msg == 6){ $.messager.alert("提示","FTP下行文件的路径不存在!","error",function(){ }); }else if(msg == 8){ $.messager.alert("提示","FTP下行文件不存在!","error",function(){ }); }else if(msg == 9){ $.messager.alert("提示","编号已存在!","error",function(){ }); }else if(msg == 10){ $.messager.alert("提示","编号为10位以内纯数字!","error",function(){ }); }else{ $.messager.alert("提示","FTP服务器修改失败!","error",function(){ }); } } function search(){ var nameval = $.trim($("#name").val()); $("#hiddenval").val(nameval); $("#name").val(nameval); $("#searchForm").submit(); }<file_sep>/src/main/java/com/complaint/model/ConfigColor.java package com.complaint.model; import java.io.Serializable; public class ConfigColor implements Serializable { private String vision; public String getVision() { return vision; } public void setVision(String vision) { this.vision = vision; } } <file_sep>/src/main/java/com/complaint/service/ReportConfigService.java package com.complaint.service; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.complaint.action.ReportConfigController; import com.complaint.dao.ReportConfigDao; import com.complaint.model.AreaBean; import com.complaint.model.Group; import com.complaint.model.Personnel; import com.complaint.model.QualityBasicConfig; import com.complaint.page.PageBean; @Service("reportConfigService") public class ReportConfigService { private static final Logger logger = LoggerFactory .getLogger(ReportConfigService.class); @Autowired private ReportConfigDao reportConfigDao; public int getGroupSeq() { return this.reportConfigDao.queryGroupSeq(); } /** * 添加分公司 * * @param user * @return */ public int addGroup(Integer groupid, String groupname) { Map<String, Object> param = new HashMap<String, Object>(); param.put("groupid", groupid); param.put("groupname", groupname); try { this.reportConfigDao.insertGroup(param); return 1; } catch (Exception e) { logger.error("", e); return 0; } } /** * 删除分公司 * * @param ids * @return */ @Transactional(rollbackFor=Exception.class) public void deleteGroup(String ids) throws Exception { String[] idStrs = ids.split(","); for (String id : idStrs) { this.reportConfigDao.deleteGroup(Integer.parseInt(id)); this.reportConfigDao.deleteGroupRelation(Integer.parseInt(id)); this.reportConfigDao.deleteStepByGroupid(Integer.parseInt(id)); } } /** * 更新分公司归属 * * @param groups * @return */ @Transactional(rollbackFor=Exception.class) public void updateGuishu(String groups) throws Exception { JSONArray arr = JSON.parseArray(groups); Map<String, Object> param = new HashMap<String, Object>(); for (int i = 0; i < arr.size(); i++) { Integer groupid = Integer.parseInt(arr.getJSONObject(i) .get("groupid").toString()); param.put("groupid", groupid); this.reportConfigDao.deleteGroupRelation(groupid); List<String> list = (List<String>) arr.getJSONObject(i) .get("areas"); for (String str : list) { if (!str.equals("")) { param.put("areaid", Integer.parseInt(str)); this.reportConfigDao.insertGroupRelation(param); } } } } /** * 修改分公司 * * @param groups * @return */ @Transactional(rollbackFor=Exception.class) public void editGroup(String groups) throws Exception { JSONArray arr = JSON.parseArray(groups); Map<String, Object> param = new HashMap<String, Object>(); for (int i = 0; i < arr.size(); i++) { Integer groupid = Integer.parseInt(arr.getJSONObject(i) .get("groupid").toString()); String groupname = arr.getJSONObject(i).get("groupname").toString(); param.put("groupid", groupid); param.put("groupname", groupname); this.reportConfigDao.updateGroup(param); } } /** * 查询分公司对应区域信息 * * @param groupid * @return */ public List<Group> getGroupById(Integer groupid) { return this.reportConfigDao.queryGroupById(groupid); } /** * 查询不在分公司的区域 * * @return */ public List<AreaBean> getNotInGroupArea() { return this.reportConfigDao.queryNotInGroupArea(); } /** * 分页查询分公司 * * @param pageIndex * @param pageSize * @return */ public PageBean getGroupsList(int pageIndex, int pageSize) { int lbound = (pageIndex - 1) * pageSize; int mbound = pageIndex * pageSize; Map<String, Object> param = new HashMap<String, Object>(); param.put("lbound", lbound); param.put("mbound", mbound); List<Group> list = reportConfigDao.queryGrouplist(param); PageBean pb = new PageBean(); pb.setList(list); return pb; } /** * 分页查询分公司 * * @param pageIndex * @param pageSize * @return */ public PageBean countGroups(int pageIndex, int pageSize) { int count = this.reportConfigDao.countGroups(); PageBean pb = new PageBean(); pb.setPageIndex(pageIndex); pb.setPageSize(pageSize); pb.setTotalPage(count); return pb; } /** * 查询人员对应区域信息 * * @param id * @return */ public List<Personnel> getPersonnelById(Integer id) { return this.reportConfigDao.queryPersonnelById(id); } public boolean isExsit(String groupname) { int count = this.reportConfigDao.countGroupname(groupname); if (count > 0) { return true; } else { return false; } } /** * 分公司质量报表配置 * * @return */ public List<Group> getGroupAndQualityConfigRelationl() { return this.reportConfigDao.queryGroupAndQualityConfigRelation(); } /** * 查询质量报表基本配置 */ public List<QualityBasicConfig> getQualityBasicConfig() { return this.reportConfigDao.queryQualityBasicConfig(); } /** * 修改步长设置 * * @param json * @throws Exception */ @Transactional(rollbackFor=Exception.class) public void updateStep(String json) throws Exception { JSONArray arr = JSON.parseArray(json); Map<String, Object> param = null; for (int i = 0; i < arr.size(); i++) { param = new HashMap<String, Object>(); Integer id = Integer.parseInt(arr.getJSONObject(i).get("id") .toString()); Integer type = Integer.parseInt(arr.getJSONObject(i).get("type") .toString()); param.put("id", id); // 判断操作类型 1 步长配置 2 基本配置 if (type.equals(1)) { Double svg_step = Double.parseDouble(arr.getJSONObject(i) .get("svg_step").toString()); Double annular_step = Double.parseDouble(arr.getJSONObject(i) .get("annular_step").toString()); param.put("svg_step", svg_step); param.put("annular_step", annular_step); if (id.equals(-1)) { Integer groupid = Integer.parseInt(arr.getJSONObject(i) .get("groupid").toString()); Integer kpi = Integer.parseInt(arr.getJSONObject(i) .get("kpi").toString()); param.put("groupid", groupid); param.put("kpi", kpi); // 添加步长配置 reportConfigDao.insertStep(param); } else { reportConfigDao.updateStep(param); } } else { String val = arr.getJSONObject(i).get("val").toString(); param.put("val", val); // 修改基本配置 reportConfigDao.updateBasics(param); } } } /** * 根据公司id查询对应的区域 * @param groupid * @return */ public List<AreaBean> getAreaByGroupId(Integer groupid){ return this.reportConfigDao.queryAreaByGroupId(groupid); } } <file_sep>/src/main/java/com/complaint/model/Vision.java package com.complaint.model; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Map; import org.json.simple.JSONStreamAware; import org.json.simple.JSONValue; public class Vision implements java.io.Serializable,JSONStreamAware{ public Short isup; public String url; public String declare; public String vision; public Short getIsup() { return isup; } public void setIsup(Short isup) { this.isup = isup; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDeclare() { return declare; } public void setDeclare(String declare) { this.declare = declare; } public String getVision() { return vision; } public void setVision(String vision) { this.vision = vision; } @Override public void writeJSONString(Writer out) throws IOException { // TODO Auto-generated method stub Map<String,Object> obj = new HashMap<String,Object>(); obj.put("isup", this.isup); obj.put("url", this.url); obj.put("de", this.declare); obj.put("vi", this.vision); JSONValue.writeJSONString(obj, out); } } <file_sep>/src/main/java/com/complaint/mina/ByteDecoder.java package com.complaint.mina; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.CumulativeProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.complaint.utils.ByteUtil; import com.complaint.utils.Constant; public class ByteDecoder extends CumulativeProtocolDecoder{ private static final Logger logger = LoggerFactory.getLogger(MinaServerHandler.class); @Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { if(in.remaining() > 0){//判断是否有数据 byte[] sizeBytes = new byte[Constant.headLen]; byte[] headBodyBytes = new byte[Constant.len]; in.mark();//标记当前位置,以便reset in.get(sizeBytes);//读取消息头 this.getHeadBodyBytes(sizeBytes, headBodyBytes); //int转byte[]的一个工具类 int size = ByteUtil.getInt(headBodyBytes, 0); logger.debug("预计接收长度:" + size); //如果消息内容的长度不够则直接返回true if(size > in.remaining()){//如果消息内容不够,则重置,相当于不读取size in.reset(); return false;//接收新数据,以拼凑成完整数据 } else{ byte[] bytes = new byte[size]; in.get(bytes, 0, size); String msg = new String(bytes,"utf-8"); if(this.validRequest(sizeBytes)) session.setAttribute("validRequest", true); else session.setAttribute("validRequest", false); session.setAttribute("commond", this.getCommond(sizeBytes)); out.write(msg); if(in.remaining() > 0){//如果读取内容后还粘了包,就进行下一次解析 return true; } } } return false;//处理成功,让父类进行接收下个包 } private void getHeadBodyBytes(byte[] headBytes,byte[] headBodyBytes){ for(int i=0;i<headBodyBytes.length;i++){ headBodyBytes[i] = headBytes[Constant.offset + i]; } } private boolean validRequest(byte[] sizeBytes){ byte[] needBytes = new byte[]{(byte)0xFF,(byte)0x00,(byte)0xFF}; byte[] actuallyBytes = new byte[]{sizeBytes[0],sizeBytes[1],sizeBytes[2]}; String needStr = new String(needBytes); String actuallyStr = new String(actuallyBytes); if(needStr.equals(actuallyStr)) return true; return false; } private short getCommond(byte[] sizeBytes){ byte[] commondBytes = new byte[]{sizeBytes[3],sizeBytes[4]}; return ByteUtil.getShort(commondBytes, 0); } } <file_sep>/src/main/java/com/complaint/model/Resource.java package com.complaint.model; import java.io.Serializable; public class Resource implements Serializable { private static final long serialVersionUID = -8372064861714036746L; private Integer resourceid; private String resourcename; private String url; private Integer parentid; private String rolename; private String memo; //备注 private Integer type; //0:菜单 1:按钮 private String btntype;//add,update,delete private String css; private Integer nepotismid;//裙带关系,例选了导出或编辑,则查看就该沟选 public Integer getNepotismid() { return nepotismid; } public void setNepotismid(Integer nepotismid) { this.nepotismid = nepotismid; } public String getCss() { return css; } public void setCss(String css) { this.css = css; } public Integer getResourceid() { return resourceid; } public void setResourceid(Integer resourceid) { this.resourceid = resourceid; } public String getResourcename() { return resourcename; } public void setResourcename(String resourcename) { this.resourcename = resourcename; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Integer getParentid() { return parentid; } public void setParentid(Integer parentid) { this.parentid = parentid; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getRolename() { return rolename; } public void setRolename(String rolename) { this.rolename = rolename; } public String getBtntype() { return btntype; } public void setBtntype(String btntype) { this.btntype = btntype; } } <file_sep>/src/main/java/com/complaint/dao/BaseStationDao.java package com.complaint.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.complaint.model.BaseStation; import com.complaint.model.CenterZoom; import com.complaint.model.GwCasCell; import com.complaint.model.TCasCell; import com.complaint.model.ReportCells; public interface BaseStationDao { List<BaseStation> queryBaseStationData(Map<String, Object> map); CenterZoom queryCenter(Map<String, Object> map); BaseStation queryBaseStationById(@Param(value="type") String type,@Param(value="bid") Integer bid); List<TCasCell> queryNearCellOther(Map<String, Object> map); List<TCasCell> queryNearCell(Map<String, Object> map); TCasCell queryCellById(Map<String, Object> map); TCasCell queryCellByIdOriginal(Map<String, Object> map); TCasCell queryCell(Map<String, Object> map); List<Map<String,Object>> queryAreaPosition(Map<String, Object> params); void setAreaCenter(Map<String, Object> params); List<TCasCell> queryCellInfos(); List<GwCasCell> queryRegiondown(Map<String, Object> params); List<GwCasCell> queryReportNearCellOther(Map<String, Object> params); List<GwCasCell> queryReportNearCell(Map<String, Object> map); GwCasCell queryReportCellById(Map<String, Object> map); Integer countRegiondown(Map<String, Object> params); List<ReportCells> queryReportLoadCells(Map<String, Object> map); } <file_sep>/src/main/java/com/complaint/model/SolvingProbability.java package com.complaint.model; import java.io.Serializable; /** * 问题解决率 * @author peng *昨天 */ public class SolvingProbability implements Serializable { private Integer areaid;//区域id private String areaname;//区域名称 private Integer special;//归属专业id private String specialName;//归属专业名称 private long complainl;//投诉量 private long solving;//问题解决量 private long solved;//真正解决量 private double solvingRate;//问题解决率 private double solvedRate;//问题解决率 public double getSolvingRate() { return solvingRate; } public void setSolvingRate(double solvingRate) { this.solvingRate = solvingRate; } public double getSolvedRate() { return solvedRate; } public void setSolvedRate(double solvedRate) { this.solvedRate = solvedRate; } public String getSpecialName() { return specialName; } public void setSpecialName(String specialName) { this.specialName = specialName; } public Integer getAreaid() { return areaid; } public void setAreaid(Integer areaid) { this.areaid = areaid; } public String getAreaname() { return areaname; } public void setAreaname(String areaname) { this.areaname = areaname; } public Integer getSpecial() { return special; } public void setSpecial(Integer special) { this.special = special; } public long getComplainl() { return complainl; } public void setComplainl(long complainl) { this.complainl = complainl; } public long getSolving() { return solving; } public void setSolving(long solving) { this.solving = solving; } public long getSolved() { return solved; } public void setSolved(long solved) { this.solved = solved; } } <file_sep>/src/main/webapp/js/circleEle.js /** * 圆 * @param data * @param count * @param isshow 是否显示 * @param name * @param scale 比例 1为100% * @param step 每次缩放比例 * @param id * @param type * @param isclick * @param paper * @param r * @returns {___circle0} */ function MyCircle(data,count,isshow,name,scale,step,id,type,isclick,paper,r,left,top){ var circle = new Object; circle.data = data; circle.count = count; circle.isshow = isshow; circle.name = name; circle.scale = scale; circle.step = step; circle.set = paper.set(); circle.id = id; circle.type = type; for(var i = 0;i<circle.data.length;i++){ var x = circle.data[i].x * circle.scale+left+100; var y = circle.data[i].y+(circle.count*10) * circle.scale+top+100; var cir = paper.circle(circle.data[i].x * circle.scale+100+left, circle.data[i].y+100+top+(circle.count*10) * circle.scale, r).attr({fill:circle.data[i].color,title:name+':'+circle.data[i].va}).data("odx",0).data("ody",0).data("mx",0).data("my",0).data("cmx",0).data("cmy",0).data("s",1).data("c",0).data("id", circle.data[i].id).data("type",circle.data[i].type).data("index",i).mousedown( function () { var tran = "t"+this.data("mx")+","+this.data("my"); this.transform(tran+"s1.5"); this.data("s",1.5); if(isclick){ $.ajax({ type:"post", url:contextPath+"/report/wcdmaOrGsm", data:({id :this.data("id"),type:this.data("type")}), success:function(data){ $('#div_page').html(data.content); $('#div_page_max').html(data.contentMax); } }); } }).mouseup(function(){ var tran = "t"+this.data("mx")+","+this.data("my"); this.transform(tran+"s1"); this.data("s",1); }); circle.set.push(cir); if(isclick){ if( circle.data[i].id == circle.id && circle.data[i].type == circle.type){ cir.attr("stroke", "#fe9a10"); } } } var onstart = function (event) { circle.set.forEach(function(_me){ _me.data('cmx',_me.data("mx")); _me.data('cmy',_me.data("my")); }); }; var onmove = function (dx, dy) { circle.set.forEach(function(_me){ var cmx = _me.data("mx") + dx; var cmy = _me.data("my") + dy; var tran = "t"+cmx+","+cmy+"s"+(_me.data("s")); _me.data('cmx',cmx); _me.data('cmy',cmy); _me.transform(tran); }); }; var onend = function () { circle.set.forEach(function(_me){ var tran = "t"+_me.data('cmx')+","+_me.data('cmy')+"s1"; _me.transform(tran); _me.data("mx",_me.data('cmx')); _me.data("my",_me.data('cmy')); }); }; circle.set.drag(onmove,onstart,onend); if(isshow){ circle.set.show(); }else{ circle.set.hide(); } circle.hidden = function(){ circle.set.hide(); }; circle.getName = function(){ return circle.name; }; circle.show = function(){ circle.set.show(); }; circle.setIsShow = function(sh){ circle.isshow = sh; }; circle.changeCxy = function(left,ow,nw,islarge){ circle.set.forEach(function(_me){ if(islarge){ var tran = "t"+(_me.data("mx")+(nw/ow)*100)+","+(_me.data("my"))+"s"+(_me.data("s")); _me.transform(tran); _me.data("mx",_me.data("mx")+(nw/ow)*100); }else{ var tran = "t"+(_me.data("mx")-((ow/nw)*100))+","+(_me.data("my"))+"s"+(_me.data("s")); _me.transform(tran); _me.data("mx",_me.data("mx")-((ow/nw)*100)); } }); } circle.cxyExpand = function(scale,step){ circle.scale = scale; circle.step = step; circle.set.forEach(function(_me){ var mx = _me.data("mx"); var my = _me.data("my"); var index = _me.data("index"); var tran = "t"+(mx+ 100 + circle.step*index)+","+(my+ 100 + circle.step*index)+"s"+(_me.data("s")); _me.transform(tran); _me.data("mx",(mx+100 + circle.step*index)); _me.data("my",(my+100 + circle.step*index)); }); }; circle.cxyNarrow = function(scale,step){ circle.scale = scale; circle.step = step; circle.set.forEach(function(_me){ var mx = _me.data("mx"); var my = _me.data("my"); var index = _me.data("index"); var tran = "t"+(mx-100-circle.step*index)+","+(my-100-circle.step*index)+"s"+(_me.data("s")); _me.transform(tran); _me.data("mx",(mx-100-circle.step*index)); _me.data("my",(my-100-circle.step*index)); }); }; return circle; } <file_sep>/src/main/java/com/complaint/action/EpInfoController.java package com.complaint.action; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.mail.internet.MimeUtility; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.FileCopyUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import com.complaint.model.AreaBean; import com.complaint.model.Epinfo; import com.complaint.model.Resource; import com.complaint.page.PageBean; import com.complaint.service.EpinfoExcelService; import com.complaint.service.EpinfoService; import com.complaint.utils.Constant; import com.complaint.utils.RoleResourceLoader; import com.complaint.utils.TokenProcessor; @Controller @RequestMapping("/epinfo") public class EpInfoController { private static final Logger logger = LoggerFactory.getLogger(EpInfoController.class); @Autowired private EpinfoService epinfoService; @Autowired private RoleResourceLoader roleResourceLoader; @Autowired private EpinfoExcelService epinfoExcelService; @RequestMapping(value = "/epinfolist") public ModelAndView epinfolist(String uuid,HttpServletRequest request,String errorname){ ModelAndView mv = new ModelAndView("/epinfo/epinfolist"); PageBean pb = this.epinfoService.countEqinfos(uuid ,1,Constant.PAGESIZE); List<Resource> buttons = this.roleResourceLoader.getButtons(request); String epdown =""; String eplead = ""; for(Resource resource:buttons){ if(resource.getUrl().equals("/epdown")){ epdown = "epdown"; }else if(resource.getUrl().equals("/eplead")){ eplead = "eplead"; } } mv.addObject("errorname",errorname); mv.addObject("epdown",epdown); mv.addObject("eplead",eplead); mv.addObject("buttons", buttons); mv.addObject("uuid", uuid); mv.addObject("pb", pb); return mv; } @RequestMapping(value = "/epinfolist/template") public String epinfolistJson(Model model,String uuid,Integer pageIndex,HttpServletRequest request){ try {PageBean pb = this.epinfoService.getEpinfoList(uuid,pageIndex,Constant.PAGESIZE); List<Epinfo> list = (List<Epinfo>) pb.getList(); List<Resource> buttons = this.roleResourceLoader.getButtons(request); model.addAttribute("buttons", buttons); model.addAttribute("list", list); model.addAttribute("contextPath", request.getContextPath()); } catch (Exception e) { logger.error("get epinfo menu",e); } return "/epinfo/childlist"; } @RequestMapping(value="/addEpinfo", method = RequestMethod.GET) public ModelAndView addEpinfo(HttpServletRequest request){ ModelAndView mv = new ModelAndView("/epinfo/addEpinfo"); TokenProcessor tokenProcessor=TokenProcessor.getInstance(); tokenProcessor.mvAddToken(mv, request); List<AreaBean> list= epinfoExcelService.getAreaBean(); mv.addObject("areas",list); return mv; } @RequestMapping(value="/updateEpinfo", method = RequestMethod.GET) public ModelAndView updateEpinfo(HttpServletRequest request,Integer id){ ModelAndView mv = new ModelAndView("/epinfo/updateEpinfo"); Epinfo epinfo = this.epinfoService.getEpinfoById(id); List<AreaBean> list = epinfoExcelService.getAreaBean(); TokenProcessor tokenProcessor=TokenProcessor.getInstance(); tokenProcessor.mvAddToken(mv, request); mv.addObject("areas",list); mv.addObject("epinfo", epinfo); return mv; } @RequestMapping(value="/updateEpinfo", method = RequestMethod.POST) public @ResponseBody Map<String, Integer> updateRole(@ModelAttribute Epinfo epinfo,HttpServletRequest request){ Map<String, Integer> map = new HashMap<String, Integer>(); TokenProcessor tokenProcessor=TokenProcessor.getInstance(); int msg = 0; if(!tokenProcessor.isTokenValid(request)){ msg = Constant.TOKEN_RESUBMIT; }else{ Epinfo temp = this.epinfoService.getEpinfoById(epinfo.getId()); if(temp.getUuid().equals(epinfo.getUuid())){ try { msg = this.epinfoService.updateEpinfo(epinfo); } catch (Exception e) { logger.error("update EpInfo error.",e); msg = 0; } tokenProcessor.reset(request); }else{ boolean msgbol = this.epinfoService.isExsit(epinfo.getUuid()); if(msgbol){ msg = -1; }else{ try { msg = this.epinfoService.updateEpinfo(epinfo); } catch (Exception e) { logger.error("update EpInfo error.",e); msg = 0; } tokenProcessor.reset(request); } } } map.put("msg", msg); return map; } @RequestMapping(value="/addEpinfo", method = RequestMethod.POST) public @ResponseBody Map<String, Object> addEpinfo(String[] uuid,Integer[] areaid,String[] functionary,String[] teltphone,HttpServletRequest request){ TokenProcessor tokenProcessor=TokenProcessor.getInstance(); Map<String, Object> map = new HashMap<String, Object>(); Integer[] islock = new Integer[uuid.length]; for(int i = 0 ;i<uuid.length;i++){ islock[i] = 0; } if(!tokenProcessor.isTokenValid(request)){ map.put("msg", Constant.TOKEN_RESUBMIT); }else{ try { map = this.epinfoService.addEpinfo(uuid,areaid,functionary,teltphone,islock); } catch (Exception e) { logger.error("batch add EpInfo error.",e); map.put("msg", 0); } if(map.get("msg") != null && (Integer.parseInt(map.get("msg").toString()) != -1 && Integer.parseInt(map.get("msg").toString()) != -2)){ tokenProcessor.reset(request); } } return map; } @RequestMapping(value="/deleteEpinfo", method = RequestMethod.POST) public @ResponseBody Map<String, Integer> deleteEpinfo(String ids){ Map<String, Integer> map = new HashMap<String, Integer>(); int msg =0; try { msg = this.epinfoService.deleteEpinfo(ids); } catch (Exception e) { logger.error("delete EpInfo error.",e); } map.put("msg", msg); return map; } @RequestMapping(value="/isExsit", method = RequestMethod.POST) public @ResponseBody Map<String, String> isExsit(String uuid){ Map<String, String> map = new HashMap<String, String>(); boolean msg = this.epinfoService.isExsit(uuid); String msgstr = "-1"; if(msg){ msgstr = "UUID已经存在!"; } map.put("msg", msgstr); return map; } @RequestMapping(value="/uuidIsExsit", method = RequestMethod.POST) public @ResponseBody boolean uuidIsExsit(String uuid){ boolean msg = this.epinfoService.isExsit(uuid); return !msg; } /** * 下载终端信息报表 * @throws IOException */ @RequestMapping(value="/download") public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException{ //生成文件存放于服务器的路径 String filename = String.valueOf(System.currentTimeMillis())+".xlsx"; String path = request.getSession().getServletContext().getRealPath("/").replace("\\", "/")+Constant.CAS_SYSTEM_TERMINAL_ERROR_PATH; //终端信息导出报表名 String name = "epinfo.xlsx"; File filePath = new File(path); if(!filePath.exists()&&!filePath.isDirectory()) { filePath.mkdirs(); } epinfoExcelService.createExcel(path+filename); HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_OCTET_STREAM); header.setContentDispositionFormData("attachment",encodeFilename(name, request)); File file = new File(path+filename); byte[] bytes = FileCopyUtils.copyToByteArray(file); return new ResponseEntity<byte[]>(bytes, header, HttpStatus.OK); } /** * 下载文件名称 * @param name * @param request * @return */ private String encodeFilename(String name, HttpServletRequest request) { String agent = request.getHeader("USER-AGENT"); try { if ((agent != null) && (-1 != agent.indexOf("MSIE"))) { String fileName = URLEncoder.encode(name, "UTF-8"); fileName = StringUtils.replace(fileName, "+", "%20"); if (fileName.length() > 150) { fileName = new String(name.getBytes("GB2312"), "ISO8859-1"); fileName = StringUtils.replace(fileName, " ", "%20"); } return fileName; } if ((agent != null) && (-1 != agent.indexOf("Mozilla"))) return MimeUtility.encodeText(name, "UTF-8", "B"); return name; } catch (Exception ex) { logger.error("down and lead of util in epinfo",ex); return name; } } /** * 下载批量导入模板 * @param request * @return * @throws IOException */ @RequestMapping(value="/getTemplate") public ResponseEntity<byte[]> getTemplate(HttpServletRequest request) throws IOException{ //生成文件存放于服务器的路径 String filePath = request.getSession().getServletContext().getRealPath("/").replace("\\", "/")+Constant.CAS_TEMPLATE_PATH; //终端信息导出报表名 String name = "epinfoTemplate.xlsx"; HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_OCTET_STREAM); header.setContentDispositionFormData("attachment",encodeFilename(name, request)); File file = new File(filePath+name); byte[] bytes = FileCopyUtils.copyToByteArray(file); return new ResponseEntity<byte[]>(bytes, header, HttpStatus.OK); } /** * 批量导入 * @param request * @param response * @return 0成功 1解析失败 2UUID有重复 ,3表示有错误excel要返回 * @throws IOException */ @RequestMapping(value="leadExcel", method = RequestMethod.POST) public ModelAndView leadExcel(HttpServletRequest request,@RequestParam("excelFile")MultipartFile file) throws IOException{ //生成文件存放于服务器的路径 String filePath = request.getSession().getServletContext().getRealPath("/"); filePath = filePath.replace("\\", "/"); Map<String,Object> result = epinfoExcelService.leadSerice(file,filePath); ModelAndView mv = new ModelAndView("/epinfo/lead"); if((Integer)result.get("result") == 3){//生成错误集合的excel mv.addObject("errorname" ,result.get("errorname")); } mv.addObject("result", result.get("result")); mv.addObject("add", result.get("add")); mv.addObject("update", result.get("update")); mv.addObject("unchange", result.get("unchange")); return mv; } /** * 导出错误文件 * @param request * @return * @throws IOException */ @RequestMapping(value="/getErrorFile") public ResponseEntity<byte[]> getErrorFile(HttpServletRequest request,String errorname) throws IOException{ //生成文件存放于服务器的路径 String filePath = request.getSession().getServletContext().getRealPath("/"); filePath = filePath.replace("\\", "/")+Constant.CAS_SYSTEM_TERMINAL_ERROR_PATH+errorname+".xlsx"; //终端信息导出报表名 String name = errorname+".xlsx"; HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_OCTET_STREAM); header.setContentDispositionFormData("attachment",encodeFilename(name, request)); File file = new File(filePath); byte[] bytes = FileCopyUtils.copyToByteArray(file); return new ResponseEntity<byte[]>(bytes, header, HttpStatus.OK); } } <file_sep>/src/main/webapp/js/taskConfig/taskmore.js function taskmore(){ var areaid = $("#areaid_option").val(); var areaname = $("#areaname_option").val(); var areaids = []; var areanames = []; if(areaid!=null && areaid!=''){ areaids = (areaid.substring(0,areaid.length-1)).split(','); } if(areaname!=null && areaname!=''){ areanames = (areaname.substring(0,areaname.length-1)).split(','); } var option = ""; for(var i=0;i<areanames.length;i++){ option+="<option value="+areaids[i]+">"+areanames[i]+"</option>"; } var more = "<ul style=\"float:left;\">"+ "<li class=\"fl\"><span class=\"fls\"><samp style=\"color:red\">*</samp>区域选择:</span>"+ "<p class=\"flp flp-ts\">"+ "<select name = \"areaid\" class=\"easyui-combobox areaid\" style=\"border:1px solid #D3D3D3;height:20px;width:80px;\" data-options=\"editable:false,required:true\">"+ option+ "</select>"+ "</p>"+ "</li>"+ "<li class=\"fl\"><span class=\"fls\"><samp style=\"color:red\">*</samp>测试网络:</span>"+ "<p class=\"flp flp-ts\">"+ "<select name = \"nettype\" class=\"easyui-combobox\" style=\"border:1px solid #D3D3D3;height:20px;width:80px;\" data-options=\"editable:false,panelHeight: 'auto'\">"+ "<option value=\"1\">2g数据</option>"+ "<option value=\"2\">2g语音</option>"+ "<option value=\"3\">3g数据</option>"+ "<option value=\"4\">3g语音</option>"+ "</select>"+ "</p>"+ "</li>"+ "<li class=\"fl\"><span class=\"fls\"><samp style=\"color:red\">*</samp>测试环节:</span>"+ "<p class=\"flp flp-ts\">"+ "<select name = \"breakflag\" class=\"easyui-combobox\" style=\"border:1px solid #D3D3D3;height:20px;width:80px;\" data-options=\"editable:false,panelHeight: 'auto'\">"+ "<option value=\"1\">优化</option>"+ "<option value=\"2\">建设</option>"+ "<option value=\"3\">维护</option>"+ "<option value=\"4\">其他</option>"+ "</select>"+ "</p>"+ "</li>"+ "<li class=\"fl\"><span class=\"fls\"><samp style=\"color:red\">*</samp>测试地址:</span>"+ "<p class=\"flp\">"+ "<input name=\"testaddress\" type=\"text\" uuid=\"uuid\" class=\"chkent qer easyui-validatebox\" style=\"width:130px;height:20px;border:1px solid #D3D3D3;\" maxlength=\"100\"/>"+ "</p>"+ "</li>"+ "<li class=\"fl\">"+ "<a name=\"add\" class=\"change\"><img src=\""+contextPath+"/images/add.png\" title=\"点击可以连续添加\"/></a>"+ "<a name=\"del\" class=\"change\"><img src=\""+contextPath+"/images/del.png\" title=\"删除当前行\"/></a>"+ "</li>"+ "</ul>"; return more; }<file_sep>/src/main/java/com/complaint/model/CenterZoom.java package com.complaint.model; public class CenterZoom { private Double centerlat; private Double centerlng; private Double distance; private String flowid; private Double max_lat; private Double min_lat; private Double max_lng; private Double min_lng; public Double getCenterlat() { return centerlat; } public void setCenterlat(Double centerlat) { this.centerlat = centerlat; } public Double getCenterlng() { return centerlng; } public void setCenterlng(Double centerlng) { this.centerlng = centerlng; } public Double getDistance() { return distance; } public void setDistance(Double distance) { this.distance = distance; } public String getFlowid() { return flowid; } public void setFlowid(String flowid) { this.flowid = flowid; } public Double getMax_lat() { return max_lat; } public void setMax_lat(Double max_lat) { this.max_lat = max_lat; } public Double getMin_lat() { return min_lat; } public void setMin_lat(Double min_lat) { this.min_lat = min_lat; } public Double getMax_lng() { return max_lng; } public void setMax_lng(Double max_lng) { this.max_lng = max_lng; } public Double getMin_lng() { return min_lng; } public void setMin_lng(Double min_lng) { this.min_lng = min_lng; } } <file_sep>/src/main/java/com/complaint/model/IntegrationThresholdForm.java package com.complaint.model; public class IntegrationThresholdForm { private int [] rank_score; // 按+ , , -分为ABC private int [] evaluate_scoreA; private int [] evaluate_scoreB; private int [] evaluate_scoreC; private int [] revis_left; private int [] revis_right; private int [] revis_level; public int[] getRank_score() { return rank_score; } public void setRank_score(int[] rank_score) { this.rank_score = rank_score; } public int[] getRevis_left() { return revis_left; } public void setRevis_left(int[] revis_left) { this.revis_left = revis_left; } public int[] getRevis_right() { return revis_right; } public void setRevis_right(int[] revis_right) { this.revis_right = revis_right; } public int[] getRevis_level() { return revis_level; } public void setRevis_level(int[] revis_level) { this.revis_level = revis_level; } public int[] getEvaluate_scoreA() { return evaluate_scoreA; } public void setEvaluate_scoreA(int[] evaluate_scoreA) { this.evaluate_scoreA = evaluate_scoreA; } public int[] getEvaluate_scoreB() { return evaluate_scoreB; } public void setEvaluate_scoreB(int[] evaluate_scoreB) { this.evaluate_scoreB = evaluate_scoreB; } public int[] getEvaluate_scoreC() { return evaluate_scoreC; } public void setEvaluate_scoreC(int[] evaluate_scoreC) { this.evaluate_scoreC = evaluate_scoreC; } } <file_sep>/src/main/java/com/complaint/model/GroupScore.java package com.complaint.model; import java.util.List; public class GroupScore { private String groupName; private Integer groupId; private Double score; private List<GroupScore> list; public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } public Integer getGroupId() { return groupId; } public void setGroupId(Integer groupId) { this.groupId = groupId; } public Double getScore() { return score; } public void setScore(Double score) { this.score = score; } public List<GroupScore> getList() { return list; } public void setList(List<GroupScore> list) { this.list = list; } } <file_sep>/src/main/webapp/js/map/map.js $("#save").click(function(){ var type = $("input:radio:checked").val(); $.ajax({ type: "POST", url: contextPath + "/map/update", data:{'mapType':type}, success: function(data) { if(data.msg == 1){ $.messager.alert("提示","操作成功!","success",function(){ window.location.href = window.location.href; }); }else{ $.messager.alert("提示","操作失败!","warning"); } } }); });<file_sep>/src/main/java/com/complaint/dao/SceneDao.java package com.complaint.dao; import com.complaint.model.Scene; import java.util.List; import org.apache.ibatis.annotations.Param; public interface SceneDao { int insert(Scene scene); int insertSelective(Scene scene); List<Scene> queryAll(); } <file_sep>/src/main/java/com/complaint/utils/Constant.java package com.complaint.utils; public class Constant { //新增用户默认密码 public static String defaultPwd = "<PASSWORD>"; public static int PAGESIZE = 10; //读取消息头偏移量 public static final int offset = 7; //读取消息体长度(含在消息头中的) public final static int len = 4; //读取消息头长度 public final static int headLen = 11; //数据库int占位符 public final static int INTPLACEHOLDER = -9999; public final static int TOKEN_RESUBMIT = -100; //GIS导出每次读取行数 public final static int READ_ROW = 500; //GIS报表分页行数 public final static int SHEET_ROW = 300000; //终端管理错误文件存放路径 public final static String CAS_SYSTEM_TERMINAL_ERROR_PATH = "/template/terminal/error/"; //gis模块数据导出存放路径 public final static String CAS_GIS_TEMPLATE_EXPORT_PATH = "/template/gis/export/"; //工单模块数据导出存放路径 public final static String CAS_WORKORDER_TEMPLATE_EXPORT_PATH = "/template/workorder/export/"; //所有模板存放路径 public final static String CAS_TEMPLATE_PATH = "/template/"; //报告模块数据导出文件存放路径 public final static String CAS_REPORT_TEMPLATE_EXPORT_PATH = "/template/report/export/"; //GIS角度配置 public final static String CELL_ANGLE_CONFIG="cell_angle_config"; //中心内部考核报表起始时间设置 public final static String RP_CENTER_CUMULATIVE_START_TIME ="rp_center_cumulative_start_time"; //质量报表累计起始时间 public final static String RP_QUALITY_CUMULATIVE_START_TIME = "rp_quality_cumulative_start_time"; //及时率间隔时间 public final static String TIMELYRATE = "timelyrate"; //累计起始时间 public final static String REPORTDATE = "reportdate"; //引用地图类型修改 public final static String MAPTYPE ="t_map_type"; } <file_sep>/src/main/java/com/complaint/model/RevisRule.java package com.complaint.model; /** * 修正规则 * @author peng * */ public class RevisRule { // 修正模式 1为项目修正 2为自由模式 private int revis_type; private int left_rate; private int right_rate; private int revis_level; // code按优良中差对应1234 private int rank_code; private int net_type; private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getRevis_type() { return revis_type; } public void setRevis_type(int revis_type) { this.revis_type = revis_type; } public int getLeft_rate() { return left_rate; } public void setLeft_rate(int left_rate) { this.left_rate = left_rate; } public int getRight_rate() { return right_rate; } public void setRight_rate(int right_rate) { this.right_rate = right_rate; } public int getRank_code() { return rank_code; } public void setRank_code(int rank_code) { this.rank_code = rank_code; } public int getNet_type() { return net_type; } public void setNet_type(int net_type) { this.net_type = net_type; } public int getRevis_level() { return revis_level; } public void setRevis_level(int revis_level) { this.revis_level = revis_level; } } <file_sep>/src/main/java/com/complaint/service/GisgradService.java package com.complaint.service; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.complaint.action.vo.VoBean; import com.complaint.dao.GisgradMapper; import com.complaint.dao.SysConfigDao; import com.complaint.model.CenterZoom; import com.complaint.model.EvaluateRule; import com.complaint.model.Gisgrad; import com.complaint.model.GradeBean; import com.complaint.model.Rate; import com.complaint.model.RateColor; import com.complaint.model.RevisRule; import com.complaint.model.ScoreRule; import com.complaint.model.Sysconfig; import com.complaint.model.TCasCell; @Service("gisgradService") public class GisgradService { @Autowired private GisgradMapper gisgradMapper; @Autowired private SysConfigDao sysConfigDao; private static final Logger logger = LoggerFactory.getLogger(GisgradService.class); /** * * @Title: showGrad * @Description: 查询出地图等级里的数据 * @param VoBean * @return * @return: Gisgrad */ public Map showGrad(VoBean vo ,String visitType){ Map<String, Object> map = new HashMap<String, Object>(); List<Rate> listr=this.gisgradMapper.showGradKpi(); map=this.setKpi(listr, map, vo); map.put("iscenter", "1"); List<EvaluateRule> er=this.gisgradMapper.queryProject(map); List<ScoreRule> rr=this.gisgradMapper.queryKpi(); List<RevisRule> drop=this.gisgradMapper.queryProDrop(); //室内2G List<GradeBean> li=this.gisgradMapper.noqueryindoor2(map); Map<String,Object> m1 = this.getGisgrad(map, li, rr, 0, er, drop, vo.getKpi(),vo.getGrad()); Map<List<Integer>, List<Gisgrad>> gl=(Map<List<Integer>, List<Gisgrad>>) m1.get("mm"); List<GradeBean> l2=this.gisgradMapper.noqueryoutdoor2(map); Map<String,Object> m2 = this.getGisgrad(map, l2, rr, 0, er, drop, vo.getKpi(),vo.getGrad()); Map<List<Integer>, List<Gisgrad>> g2=(Map<List<Integer>, List<Gisgrad>>) m2.get("mm"); List<GradeBean> l3=this.gisgradMapper.noqueryindoor3(map); Map<String,Object> m3 = this.getGisgrad(map, l3, rr, 0, er, drop, vo.getKpi(),vo.getGrad()); Map<List<Integer>, List<Gisgrad>> g3=(Map<List<Integer>, List<Gisgrad>>) m3.get("mm"); List<GradeBean> l4=this.gisgradMapper.noqueryoutdoor3(map); Map<String,Object> m4 = this.getGisgrad(map, l4, rr, 0, er, drop, vo.getKpi(),vo.getGrad()); Map<List<Integer>, List<Gisgrad>> g4=(Map<List<Integer>, List<Gisgrad>>) m4.get("mm"); List<Gisgrad> neall=new ArrayList<Gisgrad>(); List<Integer> neyy=new ArrayList<Integer>(); List<Integer> yy1=new ArrayList<Integer>(); for(List<Integer> key:gl.keySet()){ yy1=key; neall.addAll(gl.get(key)); } List<Integer> yy2=new ArrayList<Integer>(); for(List<Integer> key:g2.keySet()){ yy2=key; neall.addAll(g2.get(key)); } List<Integer> yy3=new ArrayList<Integer>(); for(List<Integer> key:g3.keySet()){ yy3=key; neall.addAll(g3.get(key)); } List<Integer> yy4=new ArrayList<Integer>(); for(List<Integer> key:g4.keySet()){ yy4=key; neall.addAll(g4.get(key)); } List<Integer> tt=null; if(yy1.size()>0)tt=yy1; if(yy2.size()>0)tt=yy2; if(yy3.size()>0)tt=yy3; if(yy4.size()>0)tt=yy4; for(int k=0;k<tt.size();k++){ int jk=0; if(yy1.size()>0)jk+=yy1.get(k); if(yy2.size()>0)jk+=yy2.get(k); if(yy3.size()>0)jk+=yy3.get(k); if(yy4.size()>0)jk+=yy4.get(k); neyy.add(jk); } Map<List<Integer>, List<Gisgrad>> all=new HashMap<List<Integer>, List<Gisgrad>>(); all.put(neyy, neall); Map<String , Object> mm = new HashMap<String , Object>(); mm.put("all", all);//查询点的数据 if(visitType.equals("search")){ //查出对应点的最大最下坐标 List<Double> latM = new ArrayList<Double>(); List<Double> lngM = new ArrayList<Double>(); Map map1 = (Map) m1.get("lat"); latM.addAll((List) map1.get("latM")); lngM.addAll((List) map1.get("lngM")); Map map2 = (Map) m2.get("lat"); latM.addAll((List) map2.get("latM")); lngM.addAll((List) map2.get("lngM")); Map map3 = (Map) m3.get("lat"); latM.addAll((List) map3.get("latM")); lngM.addAll((List) map3.get("lngM")); Map map4 = (Map) m4.get("lat"); latM.addAll((List) map4.get("latM")); lngM.addAll((List) map4.get("lngM")); Object[] lat = latM.toArray(); Object[] lng = lngM.toArray(); Arrays.sort(lat); Arrays.sort(lng); CenterZoom center = null; if(lat.length>0 && lng.length>0){ center = new CenterZoom(); center.setMax_lat((Double)lat[lat.length-1]); center.setMin_lat((Double)lat[0]); center.setMax_lng((Double)lng[lng.length-1]); center.setMin_lng((Double)lng[0]); } mm.put("center", center);//查询点的最大最小坐标 } return mm; } /** * 设置室内外区间变量VO的参数值 * @Title: setKpi * @Description: TODO * @param list * @param map * @param vo * @return * @return: Map<String,Object> */ public Map<String, Object> setKpi(List<Rate> list,Map<String, Object> map,VoBean vo){ map.put("kpi",vo.getKpi()); map.put("senceids",vo.getSenceids()); map.put("startTime",vo.getStartTime()); map.put("endTime",vo.getEndTime()); map.put("areaids",vo.getAreaids()); map.put("datatype",vo.getDatatype()); map.put("sernos",vo.getSernos()); map.put("testtype",vo.getTesttype()); map.put("nettype",vo.getNettype()); map.put("testnet",vo.getTestnet()); map.put("inside",vo.getInside()); map.put("isfirst", vo.getIsFirst()); map.put("secendSerno", vo.getSecendSerno()); map.put("minlatregion",vo.getMinlat()==0?-1:vo.getMinlat()); map.put("maxlatregion",vo.getMaxlat()==0?-1:vo.getMaxlat()); map.put("minlngregion",vo.getMinlng()==0?-1:vo.getMinlng()); map.put("maxlngregion",vo.getMaxlng()==0?-1:vo.getMaxlng()); if(vo.getSecendSerno()!=null&&!vo.getSecendSerno().trim().equals("")){ String arrss[]=vo.getSecendSerno().replaceAll(",", ",").split(","); map.put("arrss", arrss); } //拆分区域 if(vo.getAreaids()!=null&&vo.getAreaids().indexOf("-1")>=0){ map.put("aatype", "-1"); } //拆分场景 if(vo.getSenceids()!=null&&vo.getSenceids().indexOf("-1")>=0){ map.put("stype", "-1"); } //拆分业务类型 if(vo.getTesttype()!=null&&vo.getTesttype().indexOf("-1")<0) { String str[]=vo.getTesttype().split(","); List strlist=Arrays.asList(str); map.put("bustype", "1"); //测试类型 String tt=null; if(strlist.contains("1")){ tt+=",1"; } if(strlist.contains("2")){ tt+=",2"; } if(strlist.contains("3")){ tt+=",3"; } map.put("tt", tt); //长短呼 String yy=null; if(strlist.contains("4")){ yy=",2"; } if(strlist.contains("5")){ yy+=",1"; } //上下行 map.put("yy", yy); String ff=null; if(strlist.contains("6")){ ff=",1"; } if(strlist.contains("7")){ ff+=",2"; } map.put("ff", ff); }else{ map.put("bustype", "-1"); } for (int i=0;i<list.size();i++){ Rate r=list.get(i); //室外RSCP if(r.getKpi_code()==1&&r.getScene()==0){ switch (r.getRank_code()) { case 1: map.put("rscp_s_1", r.getRank_arithmetic()); map.put("rscp_v_1", r.getRank_value()); map.put("rscp_io_1", r.getRank_ratio()); break; case 2: map.put("rscp_s_2", r.getRank_arithmetic()); map.put("rscp_v_2", r.getRank_value()); map.put("rscp_io_2", r.getRank_ratio()); break; case 4: map.put("rscp_s_4", r.getRank_arithmetic()); map.put("rscp_v_4", r.getRank_value()); map.put("rscp_io_4", r.getRank_ratio()); break; default: break; } } //室内RSCP if(r.getKpi_code()==1&&r.getScene()==1){ switch (r.getRank_code()) { case 1: map.put("rscp_s_1_in", r.getRank_arithmetic()); map.put("rscp_v_1_in", r.getRank_value()); map.put("rscp_io_1_in", r.getRank_ratio()); break; case 2: map.put("rscp_s_2_in", r.getRank_arithmetic()); map.put("rscp_v_2_in", r.getRank_value()); map.put("rscp_io_2_in", r.getRank_ratio()); break; case 4: map.put("rscp_s_4_in", r.getRank_arithmetic()); map.put("rscp_v_4_in", r.getRank_value()); map.put("rscp_io_4_in", r.getRank_ratio()); break; default: break; } } //室外ECNO if(r.getKpi_code()==2&&r.getScene()==0){ switch (r.getRank_code()) { case 1: map.put("ecno_s_1", r.getRank_arithmetic()); map.put("ecno_v_1", r.getRank_value()); map.put("ecno_io_1", r.getRank_ratio()); break; case 2: map.put("ecno_s_2", r.getRank_arithmetic()); map.put("ecno_v_2", r.getRank_value()); map.put("ecno_io_2", r.getRank_ratio()); break; case 4: map.put("ecno_s_4", r.getRank_arithmetic()); map.put("ecno_v_4", r.getRank_value()); map.put("ecno_io_4", r.getRank_ratio()); break; default: break; } } //室内ECNO if(r.getKpi_code()==2&&r.getScene()==1){ switch (r.getRank_code()) { case 1: map.put("ecno_s_1_in", r.getRank_arithmetic()); map.put("ecno_v_1_in", r.getRank_value()); map.put("ecno_io_1_in", r.getRank_ratio()); break; case 2: map.put("ecno_s_2_in", r.getRank_arithmetic()); map.put("ecno_v_2_in", r.getRank_value()); map.put("ecno_io_2_in", r.getRank_ratio()); break; case 4: map.put("ecno_s_4_in", r.getRank_arithmetic()); map.put("ecno_v_4_in", r.getRank_value()); map.put("ecno_io_4_in", r.getRank_ratio()); break; default: break; } } //室外TXPOWER if(r.getKpi_code()==3&&r.getScene()==0){ switch (r.getRank_code()) { case 1: map.put("tx_s_1", r.getRank_arithmetic()); map.put("tx_v_1", r.getRank_value()); map.put("tx_io_1", r.getRank_ratio()); break; case 2: map.put("tx_s_2", r.getRank_arithmetic()); map.put("tx_v_2", r.getRank_value()); map.put("tx_io_2", r.getRank_ratio()); break; case 4: map.put("tx_s_4", r.getRank_arithmetic()); map.put("tx_v_4", r.getRank_value()); map.put("tx_io_4", r.getRank_ratio()); break; default: break; } } //室内TXPOWER if(r.getKpi_code()==3&&r.getScene()==1){ switch (r.getRank_code()) { case 1: map.put("tx_s_1_in", r.getRank_arithmetic()); map.put("tx_v_1_in", r.getRank_value()); map.put("tx_io_1_in", r.getRank_ratio()); break; case 2: map.put("tx_s_2_in", r.getRank_arithmetic()); map.put("tx_v_2_in", r.getRank_value()); map.put("tx_io_2_in", r.getRank_ratio()); break; case 4: map.put("tx_s_4_in", r.getRank_arithmetic()); map.put("tx_v_4_in", r.getRank_value()); map.put("tx_io_4_in", r.getRank_ratio()); break; default: break; } } //室外FTP上行 if(r.getKpi_code()==4&&r.getScene()==0){ switch (r.getRank_code()) { case 1: map.put("fu_s_1", r.getRank_arithmetic()); map.put("fu_v_1", r.getRank_value()); map.put("fu_io_1", r.getRank_ratio()); //map=setAbb(map,r.getRank_avg(),"fu_av",1); map.put("fu_av_1", r.getRank_avg()); break; case 2: map.put("fu_s_2", r.getRank_arithmetic()); map.put("fu_v_2", r.getRank_value()); map.put("fu_io_2", r.getRank_ratio()); map.put("fu_av_2", r.getRank_avg()); //map=setAbb(map,r.getRank_avg(),"fu_av",2); break; case 4: map.put("fu_s_4", r.getRank_arithmetic()); map.put("fu_v_4", r.getRank_value()); map.put("fu_io_4", r.getRank_ratio()); map.put("fu_av_4", r.getRank_avg()); //map=setAbb(map,r.getRank_avg(),"fu_av",4); break; default: break; } } //室内FTP上行 if(r.getKpi_code()==4&&r.getScene()==1){ switch (r.getRank_code()) { case 1: map.put("fu_s_1_in", r.getRank_arithmetic()); map.put("fu_v_1_in", r.getRank_value()); map.put("fu_io_1_in", r.getRank_ratio()); //map=setAbb(map,r.getRank_avg(),"fu_av",1); map.put("fu_av_1_in", r.getRank_avg()); break; case 2: map.put("fu_s_2_in", r.getRank_arithmetic()); map.put("fu_v_2_in", r.getRank_value()); map.put("fu_io_2_in", r.getRank_ratio()); map.put("fu_av_2_in", r.getRank_avg()); //map=setAbb(map,r.getRank_avg(),"fu_av",2); break; case 4: map.put("fu_s_4_in", r.getRank_arithmetic()); map.put("fu_v_4_in", r.getRank_value()); map.put("fu_io_4_in", r.getRank_ratio()); map.put("fu_av_4_in", r.getRank_avg()); //map=setAbb(map,r.getRank_avg(),"fu_av",4); break; default: break; } } //室外下行 if(r.getKpi_code()==5&&r.getScene()==0){ switch (r.getRank_code()) { case 1: map.put("fd_s_1", r.getRank_arithmetic()); map.put("fd_v_1", r.getRank_value()); map.put("fd_io_1", r.getRank_ratio()); map.put("fd_av_1", r.getRank_avg()); //map=setAbb(map,r.getRank_avg(),"fd_av",1); break; case 2: map.put("fd_s_2", r.getRank_arithmetic()); map.put("fd_v_2", r.getRank_value()); map.put("fd_io_2", r.getRank_ratio()); map.put("fd_av_2", r.getRank_avg()); //map=setAbb(map,r.getRank_avg(),"fd_av",2); break; case 4: map.put("fd_s_4", r.getRank_arithmetic()); map.put("fd_v_4", r.getRank_value()); map.put("fd_io_4", r.getRank_ratio()); map.put("fd_av_4", r.getRank_avg()); //map=setAbb(map,r.getRank_avg(),"fd_av",4); break; default: break; } } //室内下行 if(r.getKpi_code()==5&&r.getScene()==1){ switch (r.getRank_code()) { case 1: map.put("fd_s_1_in", r.getRank_arithmetic()); map.put("fd_v_1_in", r.getRank_value()); map.put("fd_io_1_in", r.getRank_ratio()); map.put("fd_av_1_in", r.getRank_avg()); //map=setAbb(map,r.getRank_avg(),"fd_av",1); break; case 2: map.put("fd_s_2_in", r.getRank_arithmetic()); map.put("fd_v_2_in", r.getRank_value()); map.put("fd_io_2_in", r.getRank_ratio()); map.put("fd_av_2_in", r.getRank_avg()); //map=setAbb(map,r.getRank_avg(),"fd_av",2); break; case 4: map.put("fd_s_4_in", r.getRank_arithmetic()); map.put("fd_v_4_in", r.getRank_value()); map.put("fd_io_4_in", r.getRank_ratio()); map.put("fd_av_4_in", r.getRank_avg()); //map=setAbb(map,r.getRank_avg(),"fd_av",4); break; default: break; } } //室外RXLEV if(r.getKpi_code()==6&&r.getScene()==0){ switch (r.getRank_code()) { case 1: map.put("rxl_s_1", r.getRank_arithmetic()); map.put("rxl_v_1", r.getRank_value()); map.put("rxl_io_1", r.getRank_ratio()); break; case 2: map.put("rxl_s_2", r.getRank_arithmetic()); map.put("rxl_v_2", r.getRank_value()); map.put("rxl_io_2", r.getRank_ratio()); break; case 4: map.put("rxl_s_4", r.getRank_arithmetic()); map.put("rxl_v_4", r.getRank_value()); map.put("rxl_io_4", r.getRank_ratio()); break; default: break; } } //室外RXLEV if(r.getKpi_code()==6&&r.getScene()==1){ switch (r.getRank_code()) { case 1: map.put("rxl_s_1_in", r.getRank_arithmetic()); map.put("rxl_v_1_in", r.getRank_value()); map.put("rxl_io_1_in", r.getRank_ratio()); break; case 2: map.put("rxl_s_2_in", r.getRank_arithmetic()); map.put("rxl_v_2_in", r.getRank_value()); map.put("rxl_io_2_in", r.getRank_ratio()); break; case 4: map.put("rxl_s_4_in", r.getRank_arithmetic()); map.put("rxl_v_4_in", r.getRank_value()); map.put("rxl_io_4_in", r.getRank_ratio()); break; default: break; } } //室外RXQUAL if(r.getKpi_code()==7&&r.getScene()==0){ switch (r.getRank_code()) { case 1: map.put("rxq_s_1", r.getRank_arithmetic()); map.put("rxq_v_1", r.getRank_value()); map.put("rxq_io_1", r.getRank_ratio()); break; case 2: map.put("rxq_s_2", r.getRank_arithmetic()); map.put("rxq_v_2", r.getRank_value()); map.put("rxq_io_2", r.getRank_ratio()); break; case 4: map.put("rxq_s_4", r.getRank_arithmetic()); map.put("rxq_v_4", r.getRank_value()); map.put("rxq_io_4", r.getRank_ratio()); break; default: break; } } //室外RXQUAL if(r.getKpi_code()==7&&r.getScene()==1){ switch (r.getRank_code()) { case 1: map.put("rxq_s_1_in", r.getRank_arithmetic()); map.put("rxq_v_1_in", r.getRank_value()); map.put("rxq_io_1_in", r.getRank_ratio()); break; case 2: map.put("rxq_s_2_in", r.getRank_arithmetic()); map.put("rxq_v_2_in", r.getRank_value()); map.put("rxq_io_2_in", r.getRank_ratio()); break; case 4: map.put("rxq_s_4_in", r.getRank_arithmetic()); map.put("rxq_v_4_in", r.getRank_value()); map.put("rxq_io_4_in", r.getRank_ratio()); break; default: break; } } //室外C/I if(r.getKpi_code()==8&&r.getScene()==0){ switch (r.getRank_code()) { case 1: map.put("ci_s_1", r.getRank_arithmetic()); map.put("ci_v_1", r.getRank_value()); map.put("ci_io_1", r.getRank_ratio()); break; case 2: map.put("ci_s_2", r.getRank_arithmetic()); map.put("ci_v_2", r.getRank_value()); map.put("ci_io_2", r.getRank_ratio()); break; case 4: map.put("ci_s_4", r.getRank_arithmetic()); map.put("ci_v_4", r.getRank_value()); map.put("ci_io_4", r.getRank_ratio()); break; default: break; } } //室内C/I if(r.getKpi_code()==8&&r.getScene()==1){ switch (r.getRank_code()) { case 1: map.put("ci_s_1_in", r.getRank_arithmetic()); map.put("ci_v_1_in", r.getRank_value()); map.put("ci_io_1_in", r.getRank_ratio()); break; case 2: map.put("ci_s_2_in", r.getRank_arithmetic()); map.put("ci_v_2_in", r.getRank_value()); map.put("ci_io_2_in", r.getRank_ratio()); break; case 4: map.put("ci_s_4_in", r.getRank_arithmetic()); map.put("ci_v_4_in", r.getRank_value()); map.put("ci_io_4_in", r.getRank_ratio()); break; default: break; } } } return map; } /** * * @Title: getGradeBean * @Description: TODO * @param map参数 * @param list查询出的指标百分比 * @param rr指标统计值 * @param isfree是否自己模式1-是,0-非 * @param er项目评分 * @param drop下降项目档 * @param kpi选择的路测指标 * @param grad查询等级 * @return * @return: List<GradeBean> */ public Map<String,Object> getGisgrad(Map map,List<GradeBean> list,List<ScoreRule> rr, int isfree,List<EvaluateRule> er,List<RevisRule> drop,String kpi,String grad){ List<Double> latM = new ArrayList<Double>(); List<Double> lngM = new ArrayList<Double>(); DecimalFormat df = new DecimalFormat("0.##"); List li=new ArrayList(); Gisgrad gg=null; //综合等级数量 int yy=0,ll=0,zz=0,cc=0; int yjia=0,ljia=0,zjia=0,cjia=0; int yjian=0,ljian=0,zjian=0,cjian=0; //指标等级数量 int kpiy=0,kpil=0,kpiz=0,kpic=0; for (int i=0;i<list.size();i++){ Double satte=0.0;//最后得分状态 //取得每个指标的等级得分 gg=new Gisgrad(); GradeBean wb=list.get(i); latM.add(wb.getLat_m()); lngM.add(wb.getLng_m()); //装每个指标得分; List<Integer> kpilist=new ArrayList<Integer>(); String ss_1=(String) map.get("rxl_io_1"); String ss_2=(String) map.get("rxl_io_2"); String ss_4=(String) map.get("rxl_io_4"); String ss_1_in=(String) map.get("rxl_io_1_in"); String ss_2_in=(String) map.get("rxl_io_2_in"); String ss_4_in=(String) map.get("rxl_io_4_in"); //判断指标是否测试并且是否选择查询当前指标 if(wb.getInside().equals("1")){ ss_1=ss_1_in; ss_2=ss_2_in; ss_4=ss_4_in; } if(wb.getRXLEV_Sub_1()!=null&&(kpi.equals("-1")||kpi.equals("6"))){ if(findBigSmall(wb.getRXLEV_Sub_4(),ss_1)){ wb.setRx_g("优"); kpilist.add(rr.get(0).getRank_score()); if(!kpi.equals("-1"))kpiy++; }else if (findBigSmall(wb.getRXLEV_Sub_3(),ss_2)){ wb.setRx_g("良"); kpilist.add(rr.get(1).getRank_score()); if(!kpi.equals("-1"))kpil++; }else if (findBigSmall(wb.getRXLEV_Sub_1(),ss_4)){ wb.setRx_g("差"); kpilist.add(rr.get(3).getRank_score()); if(!kpi.equals("-1"))kpic++; }else{ wb.setRx_g("中"); kpilist.add(rr.get(2).getRank_score()); if(!kpi.equals("-1"))kpiz++; } } String qq_1=(String) map.get("rxq_io_1"); String qq_2=(String) map.get("rxq_io_2"); String qq_4=(String) map.get("rxq_io_4"); String qq_1_in=(String) map.get("rxq_io_1_in"); String qq_2_in=(String) map.get("rxq_io_2_in"); String qq_4_in=(String) map.get("rxq_io_4_in"); //判断指标是否测试并且是否选择查询当前指标 if(wb.getInside().equals("1")){ qq_1=qq_1_in; qq_2=qq_2_in; qq_4=qq_4_in; } if(wb.getRXQUAL_Sub_1()!=null&&(kpi.equals("-1")||kpi.equals("7"))){ //rxqual不加入综合评分计算,所以注释 if(findBigSmall(wb.getRXQUAL_Sub_4(),qq_1)){ wb.setRq_g("优"); //kpilist.add(rr.get(0).getRank_score()); if(!kpi.equals("-1"))kpiy++; }else if (findBigSmall(wb.getRXQUAL_Sub_3(),qq_2)){ wb.setRq_g("良"); //kpilist.add(rr.get(1).getRank_score()); if(!kpi.equals("-1"))kpil++; }else if (findBigSmall(wb.getRXQUAL_Sub_1(),qq_4)){ wb.setRq_g("差"); //kpilist.add(rr.get(3).getRank_score()); if(!kpi.equals("-1"))kpic++; }else{ wb.setRq_g("中"); //kpilist.add(rr.get(2).getRank_score()); if(!kpi.equals("-1"))kpiz++; } } // C/I String cc_1=(String) map.get("ci_io_1"); String cc_2=(String) map.get("ci_io_2"); String cc_4=(String) map.get("ci_io_4"); String cc_1_in=(String) map.get("ci_io_1_in"); String cc_2_in=(String) map.get("ci_io_2_in"); String cc_4_in=(String) map.get("ci_io_4_in"); //判断指标是否测试并且是否选择查询当前指标 if(wb.getInside().equals("1")){ cc_1=cc_1_in; cc_2=cc_2_in; cc_4=cc_4_in; } if(wb.getCi_1()!=null&&(kpi.equals("-1")||kpi.equals("8"))){ if(findBigSmall(wb.getCi_4(),cc_1)){ wb.setCi_g("优"); kpilist.add(rr.get(0).getRank_score()); if(!kpi.equals("-1"))kpiy++; }else if (findBigSmall(wb.getCi_3(),cc_2)){ wb.setCi_g("良"); kpilist.add(rr.get(1).getRank_score()); if(!kpi.equals("-1"))kpil++; }else if (findBigSmall(wb.getCi_1(),cc_4)){ wb.setCi_g("差"); kpilist.add(rr.get(3).getRank_score()); if(!kpi.equals("-1"))kpic++; }else{ wb.setCi_g("中"); kpilist.add(rr.get(2).getRank_score()); if(!kpi.equals("-1"))kpiz++; } } String rr_1=(String) map.get("rscp_io_1"); String rr_2=(String) map.get("rscp_io_2"); String rr_4=(String) map.get("rscp_io_4"); String rr_1_in=(String) map.get("rscp_io_1_in"); String rr_2_in=(String) map.get("rscp_io_2_in"); String rr_4_in=(String) map.get("rscp_io_4_in"); if(wb.getInside().equals("1")){ rr_1=rr_1_in; rr_2=rr_2_in; rr_4=rr_4_in; } if(wb.getRSCP_4()!=null&&(kpi.equals("-1")||kpi.equals("1"))){ if(findBigSmall(wb.getRSCP_4(),rr_1)){ wb.setRSCP_g("优"); kpilist.add(rr.get(0).getRank_score()); if(!kpi.equals("-1"))kpiy++; }else if (findBigSmall(wb.getRSCP_3(),rr_2)){ wb.setRSCP_g("良"); kpilist.add(rr.get(1).getRank_score()); if(!kpi.equals("-1"))kpil++; }else if (findBigSmall(wb.getRSCP_1(),rr_4)){ wb.setRSCP_g("差"); kpilist.add(rr.get(3).getRank_score()); if(!kpi.equals("-1"))kpic++; }else{ wb.setRSCP_g("中"); kpilist.add(rr.get(2).getRank_score()); if(!kpi.equals("-1"))kpiz++; } } String ee_1=(String) map.get("ecno_io_1"); String ee_2=(String) map.get("ecno_io_2"); String ee_4=(String) map.get("ecno_io_4"); String ee_1_in=(String) map.get("ecno_io_1_in"); String ee_2_in=(String) map.get("ecno_io_2_in"); String ee_4_in=(String) map.get("ecno_io_4_in"); if(wb.getInside().equals("1")){ ee_1=ee_1_in; ee_2=ee_2_in; ee_4=ee_4_in; } if(wb.getEC_NO_4()!=null&&(kpi.equals("-1")||kpi.equals("2"))){ if(findBigSmall(wb.getEC_NO_4(),ee_1)){ wb.setECNO_g("优"); kpilist.add(rr.get(0).getRank_score()); if(!kpi.equals("-1"))kpiy++; }else if (findBigSmall(wb.getEC_NO_3(),ee_2)){ wb.setECNO_g("良"); kpilist.add(rr.get(1).getRank_score()); if(!kpi.equals("-1"))kpil++; }else if (findBigSmall(wb.getEC_NO_1(),ee_4)){ wb.setECNO_g("差"); kpilist.add(rr.get(3).getRank_score()); if(!kpi.equals("-1"))kpic++; }else{ wb.setECNO_g("中"); kpilist.add(rr.get(2).getRank_score()); if(!kpi.equals("-1"))kpiz++; } } String tx_1=(String) map.get("tx_io_1"); String tx_2=(String) map.get("tx_io_2"); String tx_4=(String) map.get("tx_io_4"); String tx_1_in=(String) map.get("tx_io_1_in"); String tx_2_in=(String) map.get("tx_io_2_in"); String tx_4_in=(String) map.get("tx_io_4_in"); if(wb.getInside().equals("1")){ tx_1=tx_1_in; tx_2=tx_2_in; tx_4=tx_4_in; } if(wb.getTxpower_4()!=null&&(kpi.equals("-1")||kpi.equals("3"))){ if(findBigSmall(wb.getTxpower_4(),tx_1)){ wb.setTxpower_g("优"); kpilist.add(rr.get(0).getRank_score()); if(!kpi.equals("-1"))kpiy++; }else if (findBigSmall(wb.getTxpower_3(),tx_2)){ wb.setTxpower_g("良"); if(!kpi.equals("-1"))kpil++; kpilist.add(rr.get(1).getRank_score()); }else if (findBigSmall(wb.getTxpower_1(),tx_4)){ wb.setTxpower_g("差"); if(!kpi.equals("-1"))kpic++; kpilist.add(rr.get(3).getRank_score()); }else{ wb.setTxpower_g("中"); kpilist.add(rr.get(2).getRank_score()); if(!kpi.equals("-1"))kpiz++; } } String fu_1=(String) map.get("fu_io_1"); String fu_2=(String) map.get("fu_io_2"); String fu_4=(String) map.get("fu_io_4"); String fu_1_in=(String) map.get("fu_io_1_in"); String fu_2_in=(String) map.get("fu_io_2_in"); String fu_4_in=(String) map.get("fu_io_4_in"); if(wb.getInside().equals("1")){ fu_1=fu_1_in; fu_2=fu_2_in; fu_4=fu_4_in; } if(wb.getFTP_SPEED_UP_4()!=null&&wb.getFtp_avg_speed()!=null&&(kpi.equals("-1")||kpi.equals("4"))){ if(findBigSmall(wb.getFTP_SPEED_UP_4(),fu_1)&&findBigSmall(wb.getFtp_avg_speed(),(String) map.get("fu_av_1"))){ wb.setFu_g("优"); kpilist.add(rr.get(0).getRank_score()); if(!kpi.equals("-1"))kpiy++; }else if (findBigSmall(wb.getFTP_SPEED_UP_3(),fu_2)&&findBigSmall(wb.getFtp_avg_speed(),(String) map.get("fu_av_2"))){ wb.setFu_g("良"); kpilist.add(rr.get(1).getRank_score()); if(!kpi.equals("-1"))kpil++; }else if (findBigSmall(wb.getFTP_SPEED_UP_1(),fu_4)||findBigSmall(wb.getFtp_avg_speed(),(String) map.get("fu_av_4"))){ wb.setFu_g("差"); kpilist.add(rr.get(3).getRank_score()); if(!kpi.equals("-1"))kpic++; }else{ wb.setFu_g("中"); kpilist.add(rr.get(2).getRank_score()); if(!kpi.equals("-1"))kpiz++; } } String fd_1=(String) map.get("fd_io_1"); String fd_2=(String) map.get("fd_io_2"); String fd_4=(String) map.get("fd_io_4"); String fd_1_in=(String) map.get("fd_io_1_in"); String fd_2_in=(String) map.get("fd_io_2_in"); String fd_4_in=(String) map.get("fd_io_4_in"); if(wb.getInside().equals("1")){ fd_1=fd_1_in; fd_2=fd_2_in; fd_4=fd_4_in; } if(wb.getFTP_SPEED_DOWN_4()!=null&&wb.getFtp_avg_speed()!=null&&(kpi.equals("-1")||kpi.equals("5"))) { if(findBigSmall(wb.getFTP_SPEED_DOWN_4(),fd_1)&&findBigSmall(wb.getFtp_avg_speed(),(String) map.get("fd_av_1"))){ wb.setFd_g("优"); kpilist.add(rr.get(0).getRank_score()); if(!kpi.equals("-1"))kpiy++; }else if (findBigSmall(wb.getFTP_SPEED_DOWN_3(),fd_2)&&findBigSmall(wb.getFtp_avg_speed(),(String) map.get("fd_av_2"))){ wb.setFd_g("良"); kpilist.add(rr.get(1).getRank_score()); if(!kpi.equals("-1"))kpil++; }else if (findBigSmall(wb.getFTP_SPEED_DOWN_1(),fd_4)||findBigSmall(wb.getFtp_avg_speed(),(String) map.get("fd_av_4"))){ wb.setFd_g("差"); kpilist.add(rr.get(3).getRank_score()); if(!kpi.equals("-1"))kpic++; }else{ wb.setFd_g("中"); kpilist.add(rr.get(2).getRank_score()); if(!kpi.equals("-1"))kpiz++; } } //计算等级项目得分 //进行讲挡计算(自由模式与非自己模式) for(int j=0;j<kpilist.size();j++){ satte+=kpilist.get(j); } if(kpilist.size()>0){ satte=Math.ceil(satte/kpilist.size()); } if(wb.getNettype().equals("3")){ //自由模式降档 for(int k=2;k<drop.size();k++){ String ss="["+drop.get(k).getLeft_rate()+","+drop.get(k).getRight_rate()+"]"; //在降档敬意内并且降档等级大于0 if(findBigSmall(wb.getFree3(),ss)==true&&drop.get(k).getRevis_level()>0){ for(int h=0;h<er.size();h++){ //优良降档 if(satte==er.get(h).getRank_score()){ if(h+drop.get(k).getRevis_level()<er.size()){ satte=(double) er.get(h+drop.get(k).getRevis_level()).getRank_score(); }else{ satte=(double) er.get(er.size()-1).getRank_score(); } break; } } break; } } }else{ //非自由模式 //判断状态是否是优+-、或良+-并且是否有一荐指标为差 //项目优的封装 int cha=rr.get(rr.size()-1).getRank_score(); for(int h=0;h<er.size();h++){ //优良降档 if(satte==er.get(h).getRank_score()&&(er.get(h).getRank_code()==1||er.get(h).getRank_code()==2)&&kpilist.contains(cha)){ if(h+drop.get(er.get(h).getRank_code()-1).getRevis_level()<er.size()){ satte=(double) er.get(h+drop.get(er.get(h).getRank_code()-1).getRevis_level()).getRank_score(); }else{ satte=(double) er.get(er.size()-1).getRank_score(); } break; } } } gg.setLat_m(wb.getLat_m()); gg.setLng_m(wb.getLng_m()); gg.setSer(wb.getSerialno()); gg.setAdd(wb.getProblemsAddress()); gg.setRscp(wb.getRSCP_g()); gg.setEcno(wb.getECNO_g()); gg.setTx(wb.getTxpower_g()); gg.setFu(wb.getFu_g()); gg.setFd(wb.getFd_g()); gg.setRx(wb.getRx_g()); gg.setRq(wb.getRq_g()); gg.setCi(wb.getCi_g()); gg.setNet(wb.getNettype()); gg.setInside(wb.getInside()); gg.setIsf(wb.getIsf()+""); gg.setTitle(this.getTitle(wb)); gg.setArea(wb.getArea()); gg.setSence(wb.getSence()); gg.setTime(String.valueOf(wb.getTime())); gg.setJtime(String.valueOf(wb.getJtime())); gg.setType(wb.getTest_type()+""); gg.setPath(wb.getPath()); gg.setFlowid(wb.getFlowid()); gg.setPocent3(df.format(wb.getFree3())); gg.setPocent2(df.format(wb.getPocent2())); gg.setTalkaround(df.format(wb.getTalkaround())); gg.setSumc(wb.getSumc()); gg.setNetwork(wb.getNet_worktype()); gg.setLat(wb.getLat_y()); gg.setLng(wb.getLng_y()); gg.setCall_type(wb.getCall_type()); gg.setFtp_type(wb.getFtp_type()); gg.setPhone(wb.getPhone()); EvaluateRule ek=null; for (int h=0;h<er.size();h++){ ek=er.get(h); if(ek.getRank_score()==satte){ break; } } if(ek==null){ gg.setColor("差");//设置等级分值 gg.setRealgrad("差-"); }else{ switch (ek.getRank_code()) { case 1: gg.setColor("优"); if(ek.getRank_code_sub()==1){ gg.setRealgrad("优+"); yjia++; }else if(ek.getRank_code_sub()==3){ gg.setRealgrad("优-"); yjian++; }else{ gg.setRealgrad("优"); yy++; } if(grad.equals("1")){li.add(gg);} break; case 2: gg.setColor("良"); if(ek.getRank_code_sub()==1){ gg.setRealgrad("良+"); ljia++; }else if(ek.getRank_code_sub()==3){ gg.setRealgrad("良-"); ljian++; }else{ gg.setRealgrad("良"); ll++; } if(grad.equals("2")){li.add(gg);} break; case 3: gg.setColor("中"); if(ek.getRank_code_sub()==1){ gg.setRealgrad("中+"); zjia++; }else if(ek.getRank_code_sub()==3){ gg.setRealgrad("中-"); zjian++; }else{ gg.setRealgrad("中"); zz++; } if(grad.equals("3")){li.add(gg);} break; case 4: gg.setColor("差"); if(ek.getRank_code_sub()==1){ gg.setRealgrad("差+"); cjia++; }else if(ek.getRank_code_sub()==3){ gg.setRealgrad("差-"); cjian++; }else{ gg.setRealgrad("差"); cc++; } if(grad.equals("4")){li.add(gg);} break; default: break; } } if(grad.equals("-1")){li.add(gg);} } List<Integer> ylzc=new ArrayList<Integer>(); if(!kpi.equals("-1")){ if(grad.equals("-1")||grad.equals("1"))ylzc.add(kpiy); if(grad.equals("-1")||grad.equals("2"))ylzc.add(kpil); if(grad.equals("-1")||grad.equals("3"))ylzc.add(kpiz); if(grad.equals("-1")||grad.equals("4"))ylzc.add(kpic); }else{ if(grad.equals("-1")||grad.equals("1")){ ylzc.add(yjia);ylzc.add(yy);ylzc.add(yjian); } if(grad.equals("2")||grad.equals("-1")){ ylzc.add(ljia);ylzc.add(ll);ylzc.add(ljian); } if(grad.equals("3")||grad.equals("-1")){ ylzc.add(zjia);ylzc.add(zz);ylzc.add(zjian); } if(grad.equals("4")||grad.equals("-1")){ ylzc.add(cjia);ylzc.add(cc);ylzc.add(cjian); } } //li.add(s); Map<List<Integer>, List<Gisgrad>> mm = new HashMap<List<Integer>, List<Gisgrad>>(); mm.put(ylzc, li); Map<String,List<Double>> ap = new HashMap<String,List<Double>>(); ap.put("lngM",lngM); ap.put("latM",latM); Map<String,Object> rm = new HashMap<String,Object>(); rm.put("mm", mm); rm.put("lat", ap); return rm; } /** * 判断百分比在哪个等级区间 * @Title: findBigSmall * @Description: TODO * @param value * @param str * @return * @return: Boolean */ public Boolean findBigSmall(Double value,String str){ if(str!=null&&value!=null){ String s1=str.substring(0,1); String s2=str.substring(str.length()-1,str.length()); String s3=str.substring(1,str.length()-1); List<String> li = new ArrayList<String>(); for(String t : s3.split(",")){ li.add(t); } if(s3.contains("∞")){ if(li.size()>1){ if(li.get(0).contains("∞")&&li.get(1).contains("∞")){ return true; }else if(li.get(0).contains("∞")&&!li.get(1).contains("∞")){ if(s2.equals(")")){ if(value<Double.parseDouble(li.get(1))){ return true; } } if(s2.equals("]")){ if(value<=Double.parseDouble(li.get(1))){ return true; } } }else if(!li.get(0).contains("∞")&&li.get(1).contains("∞")){ if(s1.equals("(")){ if(value>Double.parseDouble(li.get(0))){ return true; } } if(s1.equals("[")){ if(value>=Double.parseDouble(li.get(0))){ return true; } } } } else if(li.size()==1){ return true; } }else{ if (li.size()>1){ if(s1.equals("(")&&s2.equals(")")){ if(value>Double.parseDouble(li.get(0))&&value<Double.parseDouble(li.get(1))){ return true; } } if(s1.equals("(")&&s2.equals("]")){ if(value>Double.parseDouble(li.get(0))&&value<=Double.parseDouble(li.get(1))){ return true; } } if(s1.equals("[")&&s2.equals(")")){ if(value>=Double.parseDouble(li.get(0))&&value<Double.parseDouble(li.get(1))){ return true; } } if(s1.equals("[")&&s2.equals("]")){ if(value>=Double.parseDouble(li.get(0))&&value<=Double.parseDouble(li.get(1))){ return true; } } }else if(li.size()==1){ if(s1.equals("(")){ if(value>Double.parseDouble(li.get(0))){ return true; } } if(s1.equals("[")){ if(value>=Double.parseDouble(li.get(0))){ return true; } } } } } return false; } /** * 查询等级颜色 * @Title: showColor * @Description: TODO * @return * @return: List<RateColor> */ public List<RateColor> showColor(){ List<RateColor> colorlist=this.gisgradMapper.showGradColor(); return colorlist; } public String getTitle(GradeBean wb){ String temp=""; if (wb.getNettype() != null) { String netstr = ""; switch (Integer.parseInt(wb.getNettype())) { case 1: netstr = "GSM"; break; case 2: netstr = "WCDMA_锁频"; break; case 3: netstr = "WCDMA_自由模式"; break; case 4: netstr = "WCDMA_自由模式"; break; default: break; } temp += netstr; } if (wb.getTest_type()!= 0) { String teststr = ""; switch (wb.getTest_type()) { case 1: teststr = "_IDLE"; break; case 2: teststr = "_CS"; break; case 3: teststr = "_PS"; break; default: break; } temp += teststr; } if (wb.getCall_type() != 0) { String callstr = ""; if (wb.getCall_type() == 1) { callstr = "_短呼"; } else if (wb.getCall_type() == 2) { callstr = "_长呼"; } else { } temp += callstr; } if (wb.getFtp_type()!=0) { String ftpstr = ""; if (wb.getFtp_type() == 1) { ftpstr = "_上行"; } else if (wb.getFtp_type()== 2) { ftpstr = "_下行"; } else { } temp += ftpstr; } return temp; } /*** * 查询中心经纬度 * @Title: queryCenter * @Description: TODO * @return * @return: CenterZoom */ public CenterZoom queryCenter(VoBean vo){ Map<String, Object> map = new HashMap<String, Object>(); List<Rate> listr=this.gisgradMapper.showGradKpi(); map=this.setKpi(listr, map, vo); CenterZoom center=this.gisgradMapper.queryCenter(map); // if(center!=null){ // map.put("maxlat", center.getMax_lat()); // map.put("minlat", center.getMin_lat()); // map.put("maxlng", center.getMax_lng()); // map.put("minlng", center.getMin_lng()); // CenterZoom dd=this.gisgradMapper.querydistence(map); // center.setDistance(dd.getDistance()); // } return center; } /** * * @Title: queryCells * @Description: 点击GIS点根据流水号查询测试连接的所有小区 * @param map * @return * @return: List<TCasCell> */ public List<TCasCell> queryCells(String flowid,String areaids){ Map<String, Object> map = new HashMap<String, Object>(); Sysconfig sysconfig = new Sysconfig(); try { sysconfig = this.sysConfigDao.getAngleconfig("cell_angle_config"); } catch (Exception e) { logger.error("cell_angle_config",e); } String[] str = sysconfig.getConfigvalue().split("="); String type = str[1].substring(0,1); map.put("type", type); map.put("flowid", flowid); map.put("areaids", areaids); return this.gisgradMapper.queryCells(map); } /** * 查询角度配置 * @return */ public Map<String ,String> getAngleconfig(){ Sysconfig sysconfig = new Sysconfig(); try { sysconfig = this.sysConfigDao.getAngleconfig("cell_angle_config"); } catch (Exception e) { logger.error("cell_angle_config",e); } String[] str = sysconfig.getConfigvalue().split("="); String type = str[1].substring(0,1); String angle = str[2]; Map<String ,String> map = new HashMap<String ,String>(); map.put("type", type); map.put("angle", angle); return map; } /** * 保存角度配置 */ public Integer saveAngleconfig(String type ,String angle){ String configvalue = "type="+type+"|angle="+angle; try { Map map = new HashMap(); map.put("configvalue", configvalue); map.put("configkey", "cell_angle_config"); this.sysConfigDao.saveAngleconfig(map); } catch (Exception e) { logger.error("save angleconfig",e); return 2; } return 1; } } <file_sep>/src/main/java/com/complaint/test/MarsCoordinateTest.java package com.complaint.test; public class MarsCoordinateTest { public void testConvert2Mars() { MarsCoordinate mci = new MarsCoordinate(); MarsCoordinate.Coordinate earth = mci.new Coordinate(); earth.lat = 29.56312328; earth.lng = 106.54258334; MarsCoordinate.Coordinate mars = mci.convert2Mars(earth); System.out.println(mars.lat + "," + mars.lng); } public static void main(String[] args) { MarsCoordinateTest t=new MarsCoordinateTest(); t.testConvert2Mars(); } } <file_sep>/src/main/webapp/js/epinfo/epinfolist.js $(function() { var addCount = 0; var editCount = 0; var leadCount = 0; $('.add').click(function(){ $("#dlg").dialog({ href:contextPath + '/epinfo/addEpinfo', height: 330,width: 880,title: "终端用户信息", modal: true,closed:false, draggable:false }); $('#dlg').dialog('open'); $.parser.parse('#dlg'); var count = 0; $(".change").die().live("click",function(){ var name = $(this).attr("name"); var _ul = $(this).parents("ul"); if(name == "add"){ var model = $(epinfomore()); _ul.after(model); $.parser.parse(model); count++; }else{ $(this).parents("ul").remove(); count--; } }); }); $(".saveedit").click(function(){ var type = $("#type").val(); if(type == 0){ if(addCount == 0){ addCount ++; var url = contextPath + "/epinfo/addEpinfo"; $('#dataForm').ajaxForm({ url: url, beforeSubmit:function(){ if(!$('#dataForm').form('validate')){ addCount = 0; return false; }else{ return true; } }, success: function(data) { if(data.msg == 1){ $.messager.alert('提示','操作成功!',"success",function(){ $('#dlg').dialog('close'); window.location.href = window.location.href; }); }else if(data.msg == -1){ $.messager.alert("提示","UUID已经存在!","warning"); }else if(data.msg == -2){ $.messager.alert("提示","请不要输入相同的UUID!","warning"); }else if(data.msg == -100){ //重复提交 $('#dlg').dialog('close'); window.location.href = window.location.href; }else{ $.messager.alert("提示","操作失败!","error",function(){ $('#dlg').dialog('close'); window.location.href = window.location.href; }); } addCount = 0; } }); $("#dataForm").submit(); } }else{ if(editCount == 0){ editCount++; var url = contextPath + "/epinfo/updateEpinfo"; $('#dataForm').ajaxForm({ url: url, beforeSubmit:function(){ if(!$('#dataForm').form('validate')){ editCount = 0; return false; }else{ return true; } }, success: function(data) { if(data.msg == 1){ $.messager.alert('提示','操作成功!',"success",function(){ $('#dlg').dialog('close'); window.location.href = window.location.href; }); }else if(data.msg == -100){ //重复提交 $('#dlg').dialog('close'); window.location.href = window.location.href; }else if (data.msg == -1){ $.messager.alert("提示","UUID已经存在!","warning"); }else{ $.messager.alert("提示","操作失败!","error",function(){ $('#dlg').dialog('close'); window.location.href = window.location.href; }); } editCount = 0; } }); $("#dataForm").submit(); } } }); $("#parent").attr('checked',false); $("#parent").click(function () { if($("#parent").attr('checked') == undefined){ $('input[name="ids"]').attr('checked',false); }else{ $('input[name="ids"]').attr('checked',true); } }); $("#delall").click(function(){ var str=""; $("input[name='ids']:checked").each(function(){ str+=$(this).val()+","; }); if(str != "" && str.length > 1){ str = str.substring(0, str.length-1); deleteInfo(str); }else{ $.messager.alert("提示","请选择你要删除的终端用户信息!","warning"); } }); function deleteInfo(ids){ $.messager.confirm('提示', '是否删除你选择的终端用户?', function(r){ if (r){ $.ajax({ type:"post", url: contextPath + "/epinfo/deleteEpinfo", data:({ids : ids}), success:function(data){ if(data.msg == 1){ $.messager.alert("提示","删除成功!","success",function(){ location.href=contextPath +"/epinfo/epinfolist"; }); }else{ $.messager.alert("提示","删除失败!","error"); } } }); } }); } var optInit = {callback: function(page_index,jq){ $.ajax({ type:"post", url: contextPath + "/epinfo/epinfolist/template", data:({uuid : uuid,pageIndex: page_index+1}), success:function(data){ $('#content').html(data); $('.edit').click(function(){ $("#dlg").dialog({ href: contextPath + '/epinfo/updateEpinfo?id='+$(this).attr("id"), height: 360,width: 500,title: "终端用户信息", modal: true,closed:false, draggable:false }); $('#dlg').dialog('open'); $.parser.parse('#dlg'); }); $(".del").click(function(){ var id = $(this).attr("id"); deleteInfo(id); }); $("input[name='ids']").each(function(){ $(this).attr('checked',false); }); } }); return false; } }; $("#pager").pagination(pageTotal, optInit); /** * 下载工单信息报表 */ $("#download").click(function(){ location.href = contextPath+"/epinfo/download"; }); /** * 下载导入报表页面 */ $("#getTemplate").click(function(){ location.href = contextPath+"/epinfo/getTemplate"; }); /** * 导出错误文件 */ $(".errordown").click(function(){ location.href = contextPath+"/epinfo/getErrorFile?errorname="+$("#errordown").val(); }); /** * 导入excel */ $("#leadsave").click(function(){ var name = $("#file").val(); if(name!=""){ if(name.split(".")[1] =="xlsx"){ document.getElementById("leadExcel").submit(); //$('#epleaddlg').dialog('close'); }else{ $.messager.alert("提示","文件类型不正确!","error"); $("#fileshow").val(""); } }else{ $.messager.alert("提示","请选择文件!","error"); $("#fileshow").val(""); } }); /** * 导入弹框 */ $('#lead').click(function(){ $("#epleaddlg").dialog({ height: 150,width: 360,title: "导入模板", modal: true,closed:false, draggable:false }); $('#epleaddlg').dialog('open'); $.parser.parse('#epleaddlg'); $("#file").css("display","block"); $("#epleaddlg-buttons").css("display","block"); $("#ultext").css("display","block"); }); $("#file").change(function(){ $("#fileshow").val($(this).val()); }); }); function search(){ uuid = $.trim($("#uuid").val()); $("#uuid").val(uuid); $("#searchForm").submit(); } function lead(value,addnum,updatenum,unchangenum,errorname){ if(value == 0){ var addstr =''; var updatestr =''; var unchangestr = ''; var jd = ""; if(parseInt(addnum)!=0||parseInt(updatenum)!=0){ if(parseInt(addnum)!=0){ addstr = "新增 "+addnum+" 个"; } if(parseInt(updatenum)!=0){ updatestr = "修改 "+updatenum+" 个"; } if(parseInt(unchangenum)!=0){ unchangestr = "有 "+unchangenum+" 个没有变动"; } $.messager.alert("提示",addstr+updatestr+unchangestr,"success",function(){ location.href=contextPath +"/epinfo/epinfolist"; }); }else{ jd = "没有变动"; $.messager.alert("提示",jd+addstr+updatestr+unchangestr,"success",function(){ location.href=contextPath +"/epinfo/epinfolist"; }); } }else if(value == 3){ $.messager.alert("提示","数据有错","success",function(){ location.href=contextPath +"/epinfo/epinfolist?errorname="+errorname; }); } }<file_sep>/src/main/java/com/complaint/action/GisGradController.java /** * 地图评价报表 */ package com.complaint.action; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.MathContext; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.mail.internet.MimeUtility; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.util.FileCopyUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import cn.zhugefubin.maptool.ConverterTool; import cn.zhugefubin.maptool.Point; import com.complaint.action.vo.CellVo; import com.complaint.action.vo.VoBean; import com.complaint.model.Area; import com.complaint.model.AreaBean; import com.complaint.model.BaseStation; import com.complaint.model.CenterZoom; import com.complaint.model.Gisgrad; import com.complaint.model.RateColor; import com.complaint.model.ReportCells; import com.complaint.model.Resource; import com.complaint.model.Scene; import com.complaint.model.TCasCell; import com.complaint.service.AreaService; import com.complaint.service.BaseStationService; import com.complaint.service.GisgradExcelDownLoadService; import com.complaint.service.GisgradService; import com.complaint.service.SceneService; import com.complaint.service.SysConfigService; import com.complaint.utils.Constant; import com.complaint.utils.ConstantUtil; import com.complaint.utils.DateUtils; import com.complaint.utils.RoleResourceLoader; @Controller @RequestMapping("/gisgrad") public class GisGradController { private static final Logger logger = LoggerFactory.getLogger(GisGradController.class); /** * * @Title: rolelist * @Description: 跳转到地图评价页面 * @param request * @return * @return: ModelAndView */ @Autowired private GisgradService gisgradService; @Autowired private SceneService sceneService; @Autowired private BaseStationService baseStationService; @Autowired private GisgradExcelDownLoadService gisgradExcelDownLoadService; @Autowired private RoleResourceLoader roleResourceLoader; @Autowired private SysConfigService sysConfigService; @Autowired private AreaService areaService; @RequestMapping(value = "/gisgrad", method = RequestMethod.GET) public ModelAndView gisgrad1(@ModelAttribute VoBean vo,HttpServletRequest request) { if(vo.getAreaids() == null){ vo.setAreaids("-1"); } if(vo.getSenceids() == null){ vo.setSenceids("-1"); } if(vo.getTesttype()== null){ vo.setTesttype("-1"); } if(vo.getStartTime()== null){ vo.setStartTime(DateUtils.getDayTime(new Date(), -1)); } if(vo.getEndTime()== null){ vo.setEndTime(DateUtils.getDayTime(new Date(), 0)); } if(vo.getNettype()==null){ vo.setNettype("-1"); } if(vo.getGrad()==null){ vo.setGrad("-1"); } if(vo.getInside()==null){ vo.setInside("-1"); } if(vo.getDatatype()==null){ vo.setDatatype("1"); } if(vo.getJobtype()==null){ vo.setJobtype("-1"); } if(vo.getTestnet()==null){ vo.setTestnet("-1"); } if(vo.getKpi()==null){ vo.setKpi("-1"); } //判断查看和导出权限 List<Resource> buttons = this.roleResourceLoader.getButtons(request); String download =""; String search = ""; for(Resource resource:buttons){ if(resource.getUrl().equals("/gisgrad/download")){ download = "download"; }else if(resource.getUrl().equals("/gisgrad/search")){ search = "search"; } } //获取颜色更新版本 String vi = (String)request.getSession().getServletContext().getAttribute(ConstantUtil.SYS_RATE_COLOR_VERSION); vi = vi==null?"":vi; String sctype = sysConfigService.getAngleType(); ModelAndView mv = null; String value=sysConfigService.getValue(Constant.MAPTYPE); if(value.equals("baidu")){ mv= new ModelAndView("/gisgrad/gisgrad_baidu"); }else{ mv = new ModelAndView("/gisgrad/gisgrad"); } mv.addObject("allowdownload", download); mv.addObject("allowsearch", search); mv.addObject("buttons",buttons); mv.addObject("areaids", vo.getAreaids()); mv.addObject("areatext", vo.getAreatext()); mv.addObject("senceids", vo.getSenceids()); mv.addObject("senctext", vo.getSenctext()); mv.addObject("testtype", vo.getTesttype()); mv.addObject("testtypeText", vo.getTesttypeText()); mv.addObject("datatype", vo.getDatatype()); mv.addObject("jobtype", vo.getJobtype()); mv.addObject("startTime", vo.getStartTime()); mv.addObject("endTime", vo.getEndTime()); mv.addObject("testnet", vo.getTestnet()); mv.addObject("testnetName", vo.getTestnetName()); mv.addObject("kpi", vo.getKpi()); mv.addObject("colorversion", vi); mv.addObject("sctype", sctype); return mv; } /** * 根据条件查询数据 */ @RequestMapping(value = "/gisgrad", method = RequestMethod.POST) public @ResponseBody Map<String, Object> gisgrad2(@ModelAttribute VoBean vo,HttpServletRequest request) { String colorversion = request.getParameter("colorversion"); String currversion = (String)request.getSession().getServletContext().getAttribute(ConstantUtil.SYS_RATE_COLOR_VERSION); currversion = currversion==null ? "" : currversion; String content = ""; //0-没有更新,1-更新 Integer ischange = currversion.equals(colorversion) ? 0 : 1; vo.setStartTime(vo.getStartTime()+" 00:00:00"); vo.setEndTime(vo.getEndTime()+" 23:59:59"); Map<String , Object> mm = this.gisgradService.showGrad(vo ,"search"); Map<List<Integer>, List<Gisgrad>> li=(Map<List<Integer>, List<Gisgrad>>) mm.get("all"); List<Integer> count=null; List<Gisgrad> ll=null; for(List<Integer> key:li.keySet()){ count=key; ll=li.get(key); } List<RateColor> colorlist=this.gisgradService.showColor(); //CenterZoom center=this.gisgradService.queryCenter(vo); CenterZoom center=(CenterZoom) mm.get("center"); Map<String, Object> map = new HashMap<String, Object>(); map.put("list", ll); map.put("count", count); map.put("color", colorlist); map.put("center", center); map.put("ischange", ischange); return map; } @RequestMapping(value = "/sencelist") public ModelAndView sencelist(@ModelAttribute VoBean vo,HttpServletRequest request){ ModelAndView mv = new ModelAndView("/gisgrad/sencelist"); mv.addObject("senceids", vo.getSenceids()); mv.addObject("inside", vo.getInside()); return mv; } @RequestMapping(value = "/getscene") public @ResponseBody List<Area> getscene(String senceids,String inside,HttpServletRequest request){ List<Area> arealist = new ArrayList<Area>(); List<Scene> list = this.sceneService.queryScene(); List<Area> arealist1 = new ArrayList<Area>(); List<Area> arealist_out= new ArrayList<Area>(); List<Area> arealist_in = new ArrayList<Area>(); Area ar = new Area(); ar.setId(null); ar.setText("选择场景"); ar.setChecked(false); ar.setState("open"); String[] ids = senceids.split(","); Area areaall = new Area(); areaall.setId(Integer.parseInt("-1")); areaall.setText("全部"); areaall.setState("open"); Scene wo = null; Area area = null; for(int i = 0; i < list.size(); i++){ area = new Area(); wo = list.get(i); area.setId(Integer.parseInt(wo.getSceneid().toString())); area.setText(wo.getName()); area.setState("open"); for(String id:ids){ if(Long.parseLong(id) == wo.getSceneid()||id.equals("-1")){ area.setChecked(true); break; } } if(wo.getInside()==0){ arealist_out.add(area); } if(wo.getInside()==1){ arealist_in.add(area); } } Area areaall_in = new Area(); Area areaall_out = new Area(); areaall_in.setId(Integer.parseInt("-2")); areaall_in.setText("室内"); areaall_in.setState("open"); areaall_out.setId(Integer.parseInt("0")); areaall_out.setText("室外"); areaall_out.setState("open"); areaall_in.setChildren(arealist_in); areaall_out.setChildren(arealist_out); if(senceids!=null&&senceids.equals("-1")){ areaall_in.setChecked(true); areaall_out.setChecked(true); } if(inside.equals("1")){ arealist1.add(areaall_in); }else if(inside.equals("0")){ arealist1.add(areaall_out); }else{ arealist1.add(areaall_in); arealist1.add(areaall_out); } areaall.setChildren(arealist1); arealist.add(areaall); return arealist; } //业务状态多选 @RequestMapping(value = "/testtypelist") public ModelAndView testtypelist(@ModelAttribute VoBean vo,HttpServletRequest request){ ModelAndView mv = new ModelAndView("/gisgrad/testtypelist"); mv.addObject("testtype", vo.getTesttype()); mv.addObject("nettype", vo.getNettype()); return mv; } //业务状态 @RequestMapping(value = "/gettesttype") public @ResponseBody List<Area> gettesttype(String testtype,String nettype,HttpServletRequest request){ List<Area> arealist = new ArrayList<Area>(); List<Area> list = new ArrayList<Area>(); List<Area> list1 = new ArrayList<Area>(); List<Area> list2 = new ArrayList<Area>(); Area a1=new Area(); a1.setId(2); a1.setText("语音"); Area a2=new Area(); a2.setId(3); a2.setText("数据"); Area a3=new Area(); a3.setId(4); a3.setText("长呼"); Area a4=new Area(); a4.setId(5); a4.setText("短呼"); Area a5=new Area(); a5.setId(6); a5.setText("FTP上行"); Area a6=new Area(); a6.setId(7); a6.setText("FTP下行"); list1.add(a3); list1.add(a4); list2.add(a5); list2.add(a6); a1.setChildren(list1); a2.setChildren(list2); Area a7=new Area(); a7.setId(1); a7.setText("IDLE"); list.add(a7); if(nettype!=null&&nettype.equals("2")){ list.add(a1); }else{ list.add(a1); list.add(a2); } List<Area> arealist1 = new ArrayList<Area>(); Area ar = new Area(); ar.setId(null); ar.setText("选择业务类型"); ar.setChecked(false); ar.setState("open"); String[] ids = testtype.split(","); Area areaall = new Area(); areaall.setId(Integer.parseInt("-1")); areaall.setText("全部"); areaall.setState("open"); Area wo = null; Area area = null; Area wo1 = null; Area area1 = null; List<Area> chid=null; for(int i = 0; i < list.size(); i++){ area = new Area(); wo = list.get(i); area.setId(wo.getId()); area.setText(wo.getText()); area.setState("open"); for(String id:ids){ if(Long.parseLong(id) == wo.getId()||id.equals("-1")){ area.setChecked(true); break; } } chid=wo.getChildren(); List<Area> ali = new ArrayList<Area>(); if(chid!=null){ for(int j = 0; j < chid.size(); j++){ area1 = new Area(); wo1 = chid.get(j); area1.setId(wo1.getId()); area1.setText(wo1.getText()); area1.setState("open"); for(String id:ids){ if(Long.parseLong(id) == wo1.getId()||id.equals("-1")){ area1.setChecked(true); break; } } ali.add(area1); } } area.setChildren(ali); arealist1.add(area); } areaall.setChildren(arealist1); arealist.add(areaall); return arealist; } @RequestMapping(value = "/testNetlist") public ModelAndView testNetlist(@ModelAttribute VoBean vo,HttpServletRequest request){ ModelAndView mv = new ModelAndView("/gisgrad/testNetlist"); mv.addObject("testnet", vo.getTestnet()); mv.addObject("nettype", vo.getNettype()); return mv; } //网络制式 @RequestMapping(value = "/gettestNet") public @ResponseBody List<Area> gettestNet(String nettype,String testnet,HttpServletRequest request){ List<Area> arealist = new ArrayList<Area>(); List<Area> list = new ArrayList<Area>(); Area a1=new Area(); a1.setId(3); a1.setText("WCDMA自由模式"); Area a2=new Area(); a2.setId(2); a2.setText("WCDMA锁频模式"); Area a4=new Area(); a4.setId(1); a4.setText("GSM锁频模式"); if(nettype!=null&&nettype.equals("-1")){ list.add(a1); list.add(a2); list.add(a4); }else if(nettype!=null&&nettype.equals("1")){ list.add(a1); list.add(a2); }else if(nettype!=null&&nettype.equals("2")){ list.add(a1); list.add(a4); } List<Area> arealist1 = new ArrayList<Area>(); String[] ids = testnet.split(","); Area areaall = new Area(); areaall.setId(Integer.parseInt("-1")); areaall.setText("全部"); areaall.setState("open"); Area wo = null; Area area = null; for(int i = 0; i < list.size(); i++){ area = new Area(); wo = list.get(i); area.setId(wo.getId()); area.setText(wo.getText()); area.setState("open"); for(String id:ids){ if(Long.parseLong(id) == wo.getId()||id.equals("-1")){ area.setChecked(true); break; } } arealist1.add(area); } areaall.setChildren(arealist1); arealist.add(areaall); return arealist; } /** * 下载报表 * @throws IOException */ @RequestMapping(value = "/download") public ResponseEntity<byte[]> download(@ModelAttribute VoBean vo,HttpServletRequest request){ vo.setStartTime(vo.getStartTime()+" 00:00:00"); vo.setEndTime(vo.getEndTime()+" 23:59:59"); Map<String ,Object> mm = this.gisgradService.showGrad(vo ,"download"); Map<List<Integer>, List<Gisgrad>> li=(Map<List<Integer>, List<Gisgrad>>) mm.get("all"); List<Gisgrad> ll=null; for(List<Integer> key:li.keySet()){ ll=li.get(key); } List<Gisgrad> gisgrads =ll; Long name = System.currentTimeMillis(); //工程根路径 String filePath = request.getSession().getServletContext().getRealPath("/").replace("\\", "/")+Constant.CAS_GIS_TEMPLATE_EXPORT_PATH; //判断路径是否存在,不存在就创建 File fl=new File(filePath); if(!fl.exists()&&!fl.isDirectory()) { fl.mkdirs(); } //文件存放于服务器的路径 String path = filePath+String.valueOf(name)+".xlsx"; gisgradExcelDownLoadService.createExcel(gisgrads,path,vo); // 下载文件的名字 String fileName = "gradReport.xlsx"; HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_OCTET_STREAM); header.setContentDispositionFormData("attachment",encodeFilename(fileName, request)); File file = new File(path); byte[] bytes = null; try { bytes = FileCopyUtils.copyToByteArray(file); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.error("", e); } return new ResponseEntity<byte[]>(bytes, header, HttpStatus.OK); } /** * 设置下载文件中文件的名称 * * @param filename * @param request * @return */ public static String encodeFilename(String filename, HttpServletRequest request) { String agent = request.getHeader("USER-AGENT"); try { if ((agent != null) && (-1 != agent.indexOf("MSIE"))) { String newFileName = URLEncoder.encode(filename, "UTF-8"); newFileName = StringUtils.replace(newFileName, "+", "%20"); if (newFileName.length() > 150) { newFileName = new String(filename.getBytes("GB2312"), "ISO8859-1"); newFileName = StringUtils.replace(newFileName, " ", "%20"); } return newFileName; } if ((agent != null) && (-1 != agent.indexOf("Mozilla"))) return MimeUtility.encodeText(filename, "UTF-8", "B"); return filename; } catch (Exception ex) { return filename; } } /** * 查询基站 * 如果是百度地图小区转换经纬度 */ @RequestMapping(value = "/showCell") public @ResponseBody Map<String, Object> test(@ModelAttribute CellVo vo,HttpServletRequest request){ Map<String, Object> map = new HashMap<String, Object>(); List<BaseStation> list = baseStationService.getAllCell(vo); //CenterZoom center = baseStationService.getCenter(vo.getAreas()); String[] areas = vo.getAreas().split(","); if(areas != null && areas.length > 0){ List<Map<String,Object>> paramsList = new ArrayList<Map<String,Object>>(); Map<String,Object> params = new HashMap<String, Object>(); for(int i=0,len=areas.length; i<len; i++){ Map<String,Object> item = new HashMap<String, Object>(); item.put("areaid", areas[i]); paramsList.add(item); } params.put("areasList", paramsList); params.put("size", 1); List<Map<String,Object>> positionList = baseStationService.queryAreaPosition(params); if(positionList != null && !positionList.isEmpty()){ map.put("position", positionList); } } //转换百度经纬度 String value=sysConfigService.getValue(Constant.MAPTYPE); if(value.equals("baidu")){ ConverterTool ct=new ConverterTool(); for(int i=0;i<list.size();i++){ List<TCasCell> blist=list.get(i).getBsList(); List<TCasCell> bcell=new ArrayList<TCasCell>(); for(int j=0;j<blist.size();j++){ Point p = ct.GG2BD(blist.get(j).getCelllng().doubleValue(),blist.get(j).getCelllat().doubleValue()); blist.get(j).setCelllng(BigDecimal.valueOf(p.getLongitude())); blist.get(j).setCelllat(BigDecimal.valueOf(p.getLatitude())); bcell.add(blist.get(j)); } list.get(i).setBsList(bcell); } } map.put("data", list); //map.put("center", center); return map; } /** * 根据LAC CID查询邻区 * 如果是百度地图小区转换经纬度 */ @RequestMapping(value = "/getnearcell") public @ResponseBody Map<String, Object> getnearcell(@ModelAttribute CellVo vo,HttpServletRequest request){ Map<String, Object> map = baseStationService.getNearCell(vo); List<TCasCell> cell=(List<TCasCell>) map.get("list"); TCasCell tcc=(TCasCell) map.get("tcc"); List<TCasCell> cc1=new ArrayList<TCasCell>(); String value=sysConfigService.getValue(Constant.MAPTYPE); if(value.equals("baidu")){ ConverterTool ct=new ConverterTool(); for(int i=0;i<cell.size();i++){ Point p = ct.GG2BD(cell.get(i).getCelllng().doubleValue(),cell.get(i).getCelllat().doubleValue()); cell.get(i).setCelllng(BigDecimal.valueOf(p.getLongitude())); cell.get(i).setCelllat(BigDecimal.valueOf(p.getLatitude())); cc1.add(cell.get(i)); } map.put("list", cc1); Point p1 = ct.GG2BD(tcc.getCelllng().doubleValue(),tcc.getCelllat().doubleValue()); tcc.setCelllng(BigDecimal.valueOf(p1.getLongitude())); tcc.setCelllat(BigDecimal.valueOf(p1.getLatitude())); map.put("tcc", tcc); } return map; } /** * 查询单个基站 * 如果是百度地图小区转换经纬度 */ @RequestMapping(value = "/getbasestation") public @ResponseBody Map<String, Object> getBaseStation(Integer bid,HttpServletRequest request){ Map<String, Object> map = new HashMap<String, Object>(); BaseStation bs = baseStationService.getBaseStationById(bid); List<TCasCell> cell=bs.getBsList(); List<TCasCell> cc1=new ArrayList<TCasCell>(); String value=sysConfigService.getValue(Constant.MAPTYPE); if(value.equals("baidu")){ ConverterTool ct=new ConverterTool(); for(int i=0;i<cell.size();i++){ Point p = ct.GG2BD(cell.get(i).getCelllng().doubleValue(),cell.get(i).getCelllat().doubleValue()); cell.get(i).setCelllng(BigDecimal.valueOf(p.getLongitude())); cell.get(i).setCelllat(BigDecimal.valueOf(p.getLatitude())); System.out.println(cell.get(i).getCelllng()); cc1.add(cell.get(i)); } bs.setBsList(cc1); } map.put("bs", bs); return map; } /** * 根据流水点击点查询小区 * 如果是百度地图小区转换经纬度 */ @RequestMapping(value = "/giscell", method = RequestMethod.POST) public @ResponseBody Map<String, Object> giscell(String areaids,String flowid,HttpServletRequest request) { Map<String, Object> map = new HashMap<String, Object>(); List<TCasCell> cell=this.gisgradService.queryCells(flowid,areaids); List<TCasCell> cc1=new ArrayList<TCasCell>(); String value=sysConfigService.getValue(Constant.MAPTYPE); if(value.equals("baidu")){ ConverterTool ct=new ConverterTool(); for(int i=0;i<cell.size();i++){ Point p = ct.GG2BD(cell.get(i).getCelllng().doubleValue(),cell.get(i).getCelllat().doubleValue()); cell.get(i).setCelllng(BigDecimal.valueOf(p.getLongitude())); cell.get(i).setCelllat(BigDecimal.valueOf(p.getLatitude())); cc1.add(cell.get(i)); } map.put("cell", cc1); }else{ map.put("cell", cell); } return map; } /** * GIS角度配置 */ @RequestMapping(value = "/angleconfig", method = RequestMethod.GET) public ModelAndView getAngleConfig(HttpServletRequest request){ ModelAndView mav = new ModelAndView("/gisgrad/angleconfig"); Map<String ,String> map = gisgradService.getAngleconfig(); String type = map.get("type"); String angle = map.get("angle"); mav.addObject("typeangle",type); mav.addObject("angle",angle); return mav; } /** * 保存GIS角度配置修改 */ @RequestMapping(value = "/saveangle", method = RequestMethod.POST) public @ResponseBody Integer getAngleConfig(String angletype ,String angle ,HttpServletRequest request){ int result = 0; if(angletype.equals("0")){ result = gisgradService.saveAngleconfig(angletype,angle); }else if(angletype.equals("1")){ result = gisgradService.saveAngleconfig(angletype,"30"); } return result; } /** * 显示小区详情 * 如果是百度地图小区转换经纬度 */ @RequestMapping(value = "/showContent", method = RequestMethod.POST) public @ResponseBody Map<String, Object> showContent(Long lac,Long cid,HttpServletRequest request) { Map<String, Object> map = new HashMap<String, Object>(); TCasCell ccg=this.baseStationService.queryCellById(lac, cid); map.put("ccg", ccg); String value=sysConfigService.getValue(Constant.MAPTYPE); TCasCell cell =new TCasCell(); if(value.equals("baidu")){ ConverterTool ct=new ConverterTool(); Point p = ct.GG2BD(ccg.getCelllng().doubleValue(),ccg.getCelllat().doubleValue()); cell.setCelllng(BigDecimal.valueOf(p.getLongitude())); cell.setCelllat(BigDecimal.valueOf(p.getLatitude())); } map.put("cell", cell); return map; } /** * 设置当前区域中心经纬度 */ @RequestMapping(value = "/setAreaCenter", method = RequestMethod.POST) public @ResponseBody Map<String, Object> setAreaCenter(String lat,String lng,String areaids,String address,HttpServletRequest request) { Map<String, Object> map = new HashMap<String, Object>(); map.put("suc", 1); try { BigDecimal bigLat = new BigDecimal(lat, new MathContext(10)); BigDecimal biglng = new BigDecimal(lng,new MathContext(11)); String[] areas = areaids.split(","); if(areas != null && areas.length > 0){ List<Map<String,Object>> paramsList = new ArrayList<Map<String,Object>>(); Map<String,Object> params = new HashMap<String, Object>(); for(int i=0,len=areas.length; i<len; i++){ Map<String,Object> item = new HashMap<String, Object>(); item.put("areaid", areas[i]); paramsList.add(item); } params.put("areasList", paramsList); params.put("size", 1); List<AreaBean> areaList = areaService.queryAreaCondition(params); if(areaList != null && !areaList.isEmpty()){ for(AreaBean item : areaList){ if(address.contains(item.getAreaname())){ this.baseStationService.setAreaCenter(item.getAreaid().toString(),bigLat,biglng); break; } } } } } catch (Exception e) { e.printStackTrace(); map.put("suc", 0); } return map; } /** * 导出小区信息 * @param vo * @param request * @return * @throws IOException */ @RequestMapping(value = "/downloadcellinfo") public ResponseEntity<byte[]> downloadCellInfo(@ModelAttribute CellVo vo,HttpServletRequest request){ Long name = System.currentTimeMillis(); //工程根路径 String filePath = request.getSession().getServletContext().getRealPath("/"); //判断路径是否存在,不存在就创建 File path=new File(filePath.replace("\\", "/")+Constant.CAS_GIS_TEMPLATE_EXPORT_PATH); if(!path.exists()&&!path.isDirectory()) { path.mkdirs(); } //文件存放于服务器的路径 filePath = filePath.replace("\\", "/")+Constant.CAS_GIS_TEMPLATE_EXPORT_PATH+String.valueOf(name)+".xlsx"; //type 0 框选导出 1小区导出 2 点击邻区导出 3导出小区加载 //if(vo.getReport_type() == 1 || vo.getReport_type() == 0 ){ if(vo.getReport_type() == 3){ List<ReportCells> list = baseStationService.getReportLoadCells(vo); gisgradExcelDownLoadService.createReportLoadCell(list, filePath); }else{ gisgradExcelDownLoadService.createCellInfoExcel(vo,filePath); } /*}else if(vo.getReport_type() == 2){ List<GwCasCell> list = baseStationService.getReportNearCell(vo); gisgradExcelDownLoadService.createCellInfoExcel(list, filePath ,0); }else if(vo.getReport_type() == 0){ baseStationService.getRegiondownCell(vo,filePath); }else if(vo.getReport_type() == 3){ List<GwCasCell> list = baseStationService.getReportLoadCell(vo); gisgradExcelDownLoadService.createReportLoadCell(list, filePath); } gisgradExcelDownLoadService.createNearCellInfoExcel(list, filePath); }*/ //下载文件的名字 String fileName = "cellInfos.xlsx"; HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_OCTET_STREAM); header.setContentDispositionFormData("attachment",encodeFilename(fileName, request)); File file = new File(filePath); byte[] bytes = null; try { bytes = FileCopyUtils.copyToByteArray(file); } catch (IOException e) { e.printStackTrace(); logger.error("", e); } return new ResponseEntity<byte[]>(bytes, header, HttpStatus.OK); } @RequestMapping(value = "/searchCell", method = RequestMethod.GET) public ModelAndView searchCell(@ModelAttribute CellVo vo,HttpServletRequest request){ ModelAndView mv = new ModelAndView("/gisgrad/searchCell"); List<AreaBean> areas = areaService.getAllArea(); mv.addObject("areas", areas); mv.addObject("cellVo", vo); return mv; } @RequestMapping(value = "/graphlist") public ModelAndView graphlist(@ModelAttribute VoBean vb,Integer openType,HttpServletRequest request){ ModelAndView mv = new ModelAndView("/gisgrad/graphlist"); mv.addObject("inside",vb.getInside()==null?"-1":vb.getInside()); mv.addObject("grad",vb.getGrad()); if(vb.getStartTime()== null||vb.getStartTime()==""){ mv.addObject("startTime",DateUtils.getDayTime(new Date(), -1)); }else{ mv.addObject("startTime",vb.getStartTime()); } if(vb.getEndTime()== null||vb.getEndTime()==""){ mv.addObject("endTime",DateUtils.getDayTime(new Date(), 0)); }else{ mv.addObject("endTime",vb.getEndTime()); } mv.addObject("areaids",vb.getAreaids()); try { mv.addObject("areatext",new String(vb.getAreatext().getBytes("ISO-8859-1"),"UTF-8")); mv.addObject("testtypeText",new String(vb.getTesttypeText().getBytes("ISO-8859-1"),"UTF-8")); mv.addObject("testnetName",new String(vb.getTestnetName().getBytes("ISO-8859-1"),"UTF-8")); mv.addObject("senctext",new String(vb.getSenctext().getBytes("ISO-8859-1"),"UTF-8")); } catch (Exception e) { logger.error("Transcoding histogram conditions",e); } mv.addObject("senceids",vb.getSenceids()); mv.addObject("testtype",vb.getTesttype()); mv.addObject("nettype",vb.getNettype()); mv.addObject("datatype",vb.getDatatype()); mv.addObject("jobtype",vb.getJobtype()); mv.addObject("kpi",vb.getKpi()); mv.addObject("sernos",vb.getSernos()); mv.addObject("testnet",vb.getTestnet()); mv.addObject("openType",openType); return mv; } } <file_sep>/src/main/java/com/complaint/dao/ComplainStatisticsDao.java package com.complaint.dao; import java.util.List; import java.util.Map; import com.complaint.model.ComplainProbability; /** * 投诉率与投诉统计 * @author peng * */ public interface ComplainStatisticsDao { public List<ComplainProbability> getComplain(Map<String, Object> map); } <file_sep>/src/main/webapp/js/reportIndependent/indoorMap_baidu.js /** * 加载indoorMap的小区 * */ var span_map_psc = new Array(); var p_map_jizhan = new Array(); var sctype; var angle; var mapWforGoogle; function getCell(map,lat,lng,flowid){ $.ajax({ type : "post", url : contextPath + "/reportIndependent/getCell", data : ({flowid : flowid}), success : function(data) { angle = data.angle; var cells = data.cell; sctype = data.type; var distance=[]; for(var i=0;i<cells.length;i++){ //画线 //连线的点组合 // var stanceValue = map.getDistance(new BMap.Point(lng,lat),new BMap.Point(cells[i].celllng,cells[i].celllat)).toFixed(2); // var message = stanceValue+"m"; // distance[i] = stanceValue; (function(i) { //封装经纬度数据转换成百度经纬度 var paths_pol=[new BMap.Point(cells[i].celllng, cells[i].celllat), new BMap.Point(lng, lat)]; /*var paths_pol_baidu=[]; BMap.Convertor.translate(paths_pol[0],2,function(p){ paths_pol_baidu.push(p); paths_pol_baidu.push(paths_pol[1]);*/ var polyline= new BMap.Polyline(paths_pol, { strokeColor:"#00ccff", //颜色 strokeWeight:4, //宽度 strokeOpacity:1 //透明度 } ); var dd=map.getDistance(polyline.getPath()[0],polyline.getPath()[1]).toFixed(2); distance.push(dd); polyline.addEventListener('click', function(i){ $("#currvalue").val(map.getDistance(polyline.getPath()[0],polyline.getPath()[1]).toFixed(2)+"m"); }); map.addOverlay(polyline); //最后次画线时计算最远和最近距离并重新调整中心点 if(i==cells.length-1){ if(distance.length>0){ getDistance(distance); } } //}); })(i); } stationInitData = data.list; for (var j = 0; j < stationInitData.length; j++) { drawStation(stationInitData[j].bsList, map); } } }); } var EARTH_RADIUS = 6378137.0; //单位M var PI = Math.PI; function getRad(d){ return d*PI/180.0; } /** * 初始化百度地图 */ function initMap_baidu(){ //创建地图 var map = new BMap.Map("indoor_div"); // 创建地图实例 var point = new BMap.Point(lng,lat); // 创建点坐标 map.enableDragging(); //启用地图拖拽事件,默认启用(可不写) map.enableScrollWheelZoom(); //启用地图滚轮放大缩小 map.enableDoubleClickZoom(); //启用鼠标双击放大,默认启用(可不写) map.enableKeyboard(); //启用键盘上下左右键移动地图 addMapControl(map); var marker = new BMap.Marker(point); var label = new BMap.Label('测试位置',{"offset":new BMap.Size(9,-15)}); marker.setLabel(label); map.addOverlay(marker); map.centerAndZoom(point, 15); // 初始化地图,设置中心点坐标和地图级别 getCell(map,lat,lng,flowid_);//加载连线和小区 } //地图控件添加函数: function addMapControl(map) { //向地图中添加缩放控件 var ctrl_nav = new BMap.NavigationControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT, type: BMAP_NAVIGATION_CONTROL_SMALL }); map.addControl(ctrl_nav); //向地图中添加缩略图控件 var ctrl_ove = new BMap.OverviewMapControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT, isOpen: 1 }); map.addControl(ctrl_ove); //向地图中添加比例尺控件 var ctrl_sca = new BMap.ScaleControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT }); map.addControl(ctrl_sca); } /** * 计算两点距离 */ function getFlatternDistance(lat1,lng1,lat2,lng2){ var radLat1 = getRad(lat1); var radLat2 = getRad(lat2); var a = radLat1 - radLat2; var b = getRad(lng1) - getRad(lng2); var s = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2))); s = s*EARTH_RADIUS; s = Math.round(s*10000)/10000.0; return s; } /** * 计算最远和最近的一个距离 */ function getDistance(distance){ var max; var min; for(var i=0;i<distance.length;i++){ if(i==0){ max = distance[i]; min = distance[i]; }else{ if(distance[i]>max){ max = distance[i]; } if(distance[i]<min){ min = distance[i]; } } } $("#titleName").html("<span>当前距离:<input type=\"text\" id=\"currvalue\" disabled=\"disabled\" style=\"height:20px;border-color:#C8C8C8;width:70px;text-align:center;color:#ff00ff;\"></span>"+ "<span>最远距离:<input type=\"text\" id=\"maxvalue\" disabled=\"disabled\" style=\"height:20px;border-color:#C8C8C8;width:70px;text-align:center;color:#ff00ff;\"></span>"+ "<span>最近距离:<input type=\"text\" id=\"minvalue\" disabled=\"disabled\" style=\"height:20px;border-color:#C8C8C8;width:70px;text-align:center;color:#ff00ff;\"></span>"); $("#maxvalue").val(max+"m"); $("#minvalue").val(min+"m"); }<file_sep>/src/main/java/com/complaint/action/MapController.java package com.complaint.action; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.complaint.service.MapTypeService; @Controller @RequestMapping("/map") public class MapController { private static final Logger logger = LoggerFactory .getLogger(MapController.class); @Autowired private MapTypeService mapTypeService; @RequestMapping(value="/mapType") public ModelAndView mapType(HttpServletRequest request){ ModelAndView mv = new ModelAndView("/map/map"); String mapType = mapTypeService.getType(); mv.addObject("mapType" ,mapType); return mv; } @RequestMapping(value="/update", method = RequestMethod.POST) public @ResponseBody Map update(HttpServletRequest request,String mapType){ Map map = new HashMap(); int i= 0; try { mapTypeService.update(mapType); i = 1; } catch (Exception e) { logger.error("update Map type error" ,e); } map.put("msg", i); return map; } } <file_sep>/src/main/java/com/complaint/action/WorkOrderController.java package com.complaint.action; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.complaint.action.vo.VoBean; import com.complaint.model.Area; import com.complaint.model.WorkOrder; import com.complaint.page.PageBean; import com.complaint.service.WorkOrderExcelService; import com.complaint.service.WorkOrderService; import com.complaint.utils.Constant; import com.complaint.utils.DateUtils; @Controller @RequestMapping(value="/workorder") public class WorkOrderController { private static final Logger logger = LoggerFactory.getLogger(WorkOrderController.class); private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); @Autowired private WorkOrderService workOrderService; @Autowired private WorkOrderExcelService workOrderExcelService; @RequestMapping(value="/workorderlist") public ModelAndView workOrderList(@ModelAttribute VoBean vo,String s_id,HttpServletRequest request){ ModelAndView mv = new ModelAndView("/workorder/workorderlist"); Date[] dates = getDates(vo.getStartTime(),vo.getEndTime()); if(vo.getIsDeal()== null){ vo.setIsDeal(-1); } if(vo.getAreaids() == null){ vo.setAreaids("-1"); } if(vo.getSenceids() == null){ vo.setSenceids("-1"); } if(vo.getTesttype()== null){ vo.setTesttype("-1"); } if(vo.getNettype()==null){ vo.setNettype("-1"); } if(vo.getInside()==null){ vo.setInside("-1"); } if(vo.getDatatype()==null){ vo.setDatatype("1"); } if(vo.getJobtype()==null){ vo.setJobtype("-1"); } if(vo.getTestnet()==null){ vo.setTestnet("-1"); } if(vo.getStartTime()== null){ vo.setStartTime(DateUtils.getDayTime(new Date(), -1)); } if(vo.getEndTime()== null){ vo.setEndTime(DateUtils.getDayTime(new Date(), 0)); } if(vo.getVerify() == null){ vo.setVerify(-1); } if(vo.getWorkerOrderNet() == null){ vo.setWorkerOrderNet("-1"); } if(vo.getWorkerOrderNetName() == null){ vo.setWorkerOrderNetName("全网络"); } PageBean pb = workOrderService.countWorkOrderList(Constant.PAGESIZE, 1, vo,s_id); mv.addObject("pb", pb); mv.addObject("sernos", vo.getSernos()); mv.addObject("isDeal", vo.getIsDeal()); mv.addObject("testphone", vo.getTestphone()); mv.addObject("areaids", vo.getAreaids()); mv.addObject("areatext", vo.getAreatext()); mv.addObject("senceids", vo.getSenceids()); mv.addObject("senctext", vo.getSenctext()); mv.addObject("testtype", vo.getTesttype()); mv.addObject("testtypeText", vo.getTesttypeText()); mv.addObject("datatype", vo.getDatatype()); mv.addObject("jobtype", vo.getJobtype()); mv.addObject("startTime", vo.getStartTime()); mv.addObject("endTime", vo.getEndTime()); mv.addObject("testnet", vo.getTestnet()); mv.addObject("inside", vo.getInside()); mv.addObject("nettype", vo.getNettype()); mv.addObject("testnetName", vo.getTestnetName()); mv.addObject("s_id", s_id); mv.addObject("verify", vo.getVerify()); mv.addObject("workerOrderNet", vo.getWorkerOrderNet()); mv.addObject("workerOrderNetName", vo.getWorkerOrderNetName()); return mv; } @RequestMapping(value = "/workorderlist/template") public String workOrderJson(Model model,Integer pageIndex,VoBean vo,String s_id,HttpServletRequest request){ try { PageBean pb = this.workOrderService.getWorkOrderList(Constant.PAGESIZE, pageIndex,vo,s_id); List<WorkOrder> list = (List<WorkOrder>) pb.getList(); model.addAttribute("list", list); model.addAttribute("contextPath", request.getContextPath()); } catch (Exception e) { e.printStackTrace(); logger.error("",e); } return "/workorder/childlist"; } private Date[] getDates(String startTime,String endTime){ Date startDate = null; Date endDate = null; if(StringUtils.isNotEmpty(startTime)){ try { startTime = startTime + " 00:00:00"; startDate = sdf.parse(startTime.replaceAll("-", "/")); } catch (ParseException e) { logger.debug(e.getMessage()); } } if(StringUtils.isNotEmpty(endTime)){ try { endTime = endTime + " 23:59:59"; endDate = sdf.parse(endTime.replaceAll("-", "/")); } catch (ParseException e) { logger.debug(e.getMessage()); } } return new Date[]{startDate,endDate}; } @RequestMapping(value = "/arealist") public ModelAndView areaList(String areaids,Integer type,HttpServletRequest request){ ModelAndView mv = new ModelAndView("/workorder/arealist"); mv.addObject("areaids", areaids); mv.addObject("type", type); return mv; } @RequestMapping(value = "/getarea") public @ResponseBody List<Area> getList(String areaids,Integer type,HttpServletRequest request){ List<Area> arealist = new ArrayList<Area>(); List<WorkOrder> list = this.workOrderService.getAllArea(); List<Area> arealist1 = new ArrayList<Area>(); Area ar = new Area(); ar.setId(null); ar.setText("选择区域"); ar.setChecked(false); ar.setState("open"); if(areaids == null || areaids.equals("")){ areaids = "-1"; } String[] ids = areaids.split(","); if(type.equals(0)){ Area areaall = new Area(); areaall.setId(Integer.parseInt("-1")); areaall.setText("全部"); areaall.setState("open"); arealist1.add(areaall); } WorkOrder wo = null; Area area = null; for(int i = 0; i < list.size(); i++){ area = new Area(); wo = list.get(i); area.setId(wo.getAreaId()); area.setText(wo.getAreaname()); area.setState("open"); for(String id:ids){ if(Long.parseLong(id) == wo.getAreaId()){ area.setChecked(true); break; } } arealist1.add(area); } ar.setChildren(arealist1); arealist.add(ar); return arealist; } //业务状态多选 @RequestMapping(value = "/testtypelist") public ModelAndView testtypelist(@ModelAttribute VoBean vo,HttpServletRequest request){ ModelAndView mv = new ModelAndView("/workorder/testtypelist"); mv.addObject("testtype", vo.getTesttype()); mv.addObject("nettype", vo.getNettype()); return mv; } //业务状态 @RequestMapping(value = "/gettesttype") public @ResponseBody List<Area> gettesttype(String testtype,String nettype,HttpServletRequest request){ List<Area> arealist = new ArrayList<Area>(); List<Area> list = new ArrayList<Area>(); List<Area> list1 = new ArrayList<Area>(); List<Area> list2 = new ArrayList<Area>(); Area a1=new Area(); a1.setId(2); a1.setText("语音"); Area a2=new Area(); a2.setId(3); a2.setText("数据"); Area a3=new Area(); a3.setId(4); a3.setText("长呼"); Area a4=new Area(); a4.setId(5); a4.setText("短呼"); Area a5=new Area(); a5.setId(6); a5.setText("FTP上行"); Area a6=new Area(); a6.setId(7); a6.setText("FTP下行"); list1.add(a3); list1.add(a4); list2.add(a5); list2.add(a6); a1.setChildren(list1); a2.setChildren(list2); Area a7=new Area(); a7.setId(1); a7.setText("IDLE"); list.add(a7); if(nettype!=null&&nettype.equals("2")){ list.add(a1);//2G没有数据测试 }else if(nettype!=null&&nettype.equals("4")){ list.add(a2);//4G没有语音测试 }else{ list.add(a1); list.add(a2); } List<Area> arealist1 = new ArrayList<Area>(); Area ar = new Area(); ar.setId(null); ar.setText("选择业务类型"); ar.setChecked(false); ar.setState("open"); String[] ids = testtype.split(","); Area areaall = new Area(); areaall.setId(Integer.parseInt("-1")); areaall.setText("全部"); areaall.setState("open"); Area wo = null; Area area = null; Area wo1 = null; Area area1 = null; List<Area> chid=null; for(int i = 0; i < list.size(); i++){ area = new Area(); wo = list.get(i); area.setId(wo.getId()); area.setText(wo.getText()); area.setState("open"); for(String id:ids){ if(Long.parseLong(id) == wo.getId()||id.equals("-1")){ area.setChecked(true); break; } } chid=wo.getChildren(); List<Area> ali = new ArrayList<Area>(); if(chid!=null){ for(int j = 0; j < chid.size(); j++){ area1 = new Area(); wo1 = chid.get(j); area1.setId(wo1.getId()); area1.setText(wo1.getText()); area1.setState("open"); for(String id:ids){ if(Long.parseLong(id) == wo1.getId()||id.equals("-1")){ area1.setChecked(true); break; } } ali.add(area1); } } area.setChildren(ali); arealist1.add(area); } areaall.setChildren(arealist1); arealist.add(areaall); return arealist; } @RequestMapping(value = "/testNetlist") public ModelAndView testNetlist(@ModelAttribute VoBean vo,HttpServletRequest request){ ModelAndView mv = new ModelAndView("/workorder/testNetlist"); mv.addObject("testnet", vo.getTestnet()); mv.addObject("nettype", vo.getNettype()); return mv; } //网络制式 @RequestMapping(value = "/gettestNet") public @ResponseBody List<Area> gettestNet(String nettype,String testnet,HttpServletRequest request){ List<Area> arealist = new ArrayList<Area>(); List<Area> list = new ArrayList<Area>(); Area a1=new Area(); a1.setId(3); a1.setText("WCDMA自由模式"); Area a2=new Area(); a2.setId(2); a2.setText("WCDMA锁频模式"); Area a4=new Area(); a4.setId(1); a4.setText("GSM锁频模式"); Area a6=new Area(); a6.setId(5); a6.setText("LTE自由模式"); Area a5=new Area(); a5.setId(4); a5.setText("LTE锁频模式"); if(nettype!=null&&nettype.equals("-1")){ list.add(a1); list.add(a2); list.add(a4); list.add(a5); list.add(a6); }else if(nettype!=null&&nettype.equals("1")){ list.add(a1); list.add(a2); }else if(nettype!=null&&nettype.equals("2")){ list.add(a1); list.add(a4); }else if(nettype!=null&&nettype.equals("4")){ list.add(a5); }else if(nettype!=null&&nettype.equals("5")){ list.add(a6); } List<Area> arealist1 = new ArrayList<Area>(); String[] ids = testnet.split(","); Area areaall = new Area(); areaall.setId(Integer.parseInt("-1")); areaall.setText("全部"); areaall.setState("open"); Area wo = null; Area area = null; for(int i = 0; i < list.size(); i++){ area = new Area(); wo = list.get(i); area.setId(wo.getId()); area.setText(wo.getText()); area.setState("open"); for(String id:ids){ if(Long.parseLong(id) == wo.getId()||id.equals("-1")){ area.setChecked(true); break; } } arealist1.add(area); } areaall.setChildren(arealist1); arealist.add(areaall); return arealist; } @RequestMapping(value = "/workerOrderNetList") public ModelAndView workerOrderNetList( String netIds,HttpServletRequest request){ ModelAndView mv = new ModelAndView("/workorder/workerOrderNetList"); mv.addObject("netIds", netIds); return mv; } //网络制式 @RequestMapping(value = "/getworkerOrderNet") public @ResponseBody List<Area> getworkerOrderNet(String netIds ,HttpServletRequest request){ List<Area> list = new ArrayList<Area>(); List<Map<String ,Object>> nets = workOrderService.getWorkerOrderNetList(); String[] ids = netIds.split(","); Area areaall = new Area(); areaall.setId(Integer.parseInt("-1")); areaall.setText("全网络"); areaall.setState("open"); for(String id:ids){ if("-1".equals(id)){ areaall.setChecked(true); } } List<Area> children = new ArrayList<Area>(); Area area = null; for(int i = 0; i < nets.size(); i++){ Map<String ,Object> net = nets.get(i); area = new Area(); area.setId(i); area.setText(net.get("NET_WORKTYPE")!=null?net.get("NET_WORKTYPE").toString():""); area.setState("open"); for(String id:ids){ if(String.valueOf(i).equals(id)){ area.setChecked(true); break; } } children.add(area); } areaall.setChildren(children); list.add(areaall); return list; } @RequestMapping(value = "/workorderlist/export") public @ResponseBody String workOrderExport(VoBean vo,String s_id,HttpServletRequest request){ String filename ="-1"; try {//生成文件存放于服务器的路径 filename = workOrderExcelService.getMD5(String.valueOf(System.currentTimeMillis())+"workOrder"); String path = request.getSession().getServletContext().getRealPath("/").replace("\\", "/")+Constant.CAS_WORKORDER_TEMPLATE_EXPORT_PATH; File filePath = new File(path); if(!filePath.exists()&&!filePath.isDirectory()) { filePath.mkdirs(); } this.workOrderExcelService.getWorkExport(vo,s_id,path+filename+".xlsx"); } catch (Exception e) { e.printStackTrace(); logger.error("",e); } return filename; } /** * 下载生成的Excel * @param Name * @param request * @param response * @return */ @RequestMapping(value="/downLoadExcel", method = RequestMethod.GET) public ModelAndView downLoad(String name ,HttpServletRequest request ,HttpServletResponse response){ ModelAndView mv = null; String path = request.getSession().getServletContext().getRealPath("/").replace("\\", "/")+Constant.CAS_WORKORDER_TEMPLATE_EXPORT_PATH+name+".xlsx"; ServletOutputStream out = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //文件名称 String fname=name+".xlsx"; fname = URLEncoder.encode(fname, "GB2312"); fname = URLDecoder.decode(fname, "ISO8859_1"); File file = new File(path); byte[] buf = new byte[1024]; int len = 0; response.reset(); // 非常重要 response.addHeader("Content-Disposition", "attachment;filename=\"" + fname + "\""); out = response.getOutputStream(); bis = new BufferedInputStream(new FileInputStream(file)); bos = new BufferedOutputStream(out); while (-1 != (len = bis.read(buf, 0, buf.length))) { bos.write(buf, 0, len); } } catch (Exception e) { mv = new ModelAndView("/export/error"); logger.error("", e); }finally{ if (bis != null){ try { bis.close(); } catch (IOException e) { } } if (bos != null){ try { bos.close(); } catch (IOException e) { } } } return mv; } } <file_sep>/src/main/webapp/js/gisgrad/station_baidu.js var stationMap = [];//生成的基站图层数据 var changeCells = [];//领区数据 var stationInitData = [];//查询区域内的数据 var span_map_psc_g3=[];//G3PSC标注 var p_map_jizhan_g3=[];//G3基站名称标注 var p_map_jizhan_g2=[];//G2基站名称标注 var span_map_psc_g2=[];//G2PSC标注 var imgheight=[12,19,25,32,38,45]; //var click_cell = ""; /** * 画小区图 * @param cells * @param map */ function drawStation(cells, map) { var s = null; if (cells.length >= 1) { var xxbhMap={}; for ( var j = 0; j < cells.length; j++) { //根据经纬度分组 if (xxbhMap[cells[j].celllat+"_"+cells[j].celllng] == undefined) { var list = []; list.push(cells[j]); xxbhMap[cells[j].celllat+"_"+cells[j].celllng] = list; } else { xxbhMap[cells[j].celllat+"_"+cells[j].celllng].push(cells[j]); } } for (ss in xxbhMap) { var jjzhan_modetype=[]; var html = ''; var st = xxbhMap[ss]; var bhMap={}; for(var i=0;i<st.length;i++){ if(st[i].indoor == 1){ st[i].azimuth = st[i].self_azimuth; }else{ if(sctype == '0'){ st[i].azimuth = st[i].self_azimuth; }else{ st[i].azimuth = st[i].ant_azimuth; } } //根据方位角分组 if (bhMap[st[i].azimuth] == undefined) { var list = []; list.push(st[i]); bhMap[st[i].azimuth] = list; } else { bhMap[st[i].azimuth].push(st[i]); } } for(bk in bhMap){ var bb=bhMap[bk]; var count = 1; var C_count=1; var modetypes_psc=[]; for(var k=0;k<bb.length;k++){ modetypes_psc.push(bb[k].modetype); jjzhan_modetype.push(bb[k].modetype); //计算放入PSC if(sctype==1){ var radian = (bb[k].azimuth-90) * Math.PI / 180; var xMargin = Math.cos(radian) * imgheight[k]; var yMargin = Math.sin(radian) * imgheight[k]; var xx="",yy=""; if(xMargin>0) xx="left:"+xMargin*2+"px;"; if(xMargin<0) xx="right:"+Math.abs(xMargin)*2+"px;"; if(bb[k].azimuth==270||bb[k].azimuth==180){ yy="top:"+(10*k+yMargin*2)+"px;"; }else{ yy="top:"+yMargin*2+"px;"; } var s_html='<span class="img_span" style="'+xx+yy+'">'+bb[k].psc+'</span>'; var obj_psc=new Object(); obj_psc.id= bb[k].lac+"_"+bb[k].cellId; obj_psc.html=s_html; if($.inArray(0, modetypes_psc)>=0&&$.inArray(1, modetypes_psc)>=0) { obj_psc.net=3; if($("#pp_sc").find("span").length>0||$("#bb_ch").find("span").length>0){ html=html+s_html; } }else if($.inArray(1, modetypes_psc)>=0){ obj_psc.net=2; if($("#bb_ch").find("span").length>0){ html=html+s_html; } } else if($.inArray(0, modetypes_psc)>=0){ obj_psc.net=1; if($("#pp_sc").find("span").length>0){ html=html+s_html; } } span_map_psc.push(obj_psc); } if(bb[k].indoor == 1){ bb[k].fix=bb[k].fix==undefined?'c_':bb[k].fix; html += '<img class="cellimg" azimuth="'+bb[k].azimuth+'" flag="0" id ="img_' + bb[k].lac + '_' + bb[k].cellId + '" style="z-index:' + (6-C_count) + ';margin-top:-' + (C_count - 1) * 6 + 'px;margin-left:-' + (C_count - 1) * 3 + 'px;" count="'+C_count+'" type="1" src="' + contextPath + '/images/cell/'+bb[k].fix+C_count+'.png"/>'; if(C_count ==6){ break; } C_count++; }else{ bb[k].fix=bb[k].fix==undefined?'sx':bb[k].fix; html += '<img class="cellimg" azimuth="'+bb[k].azimuth+'" flag="0" id ="img_' + bb[k].lac + '_' + bb[k].cellId + '" style="z-index:' + (6-count) + ';margin-top:-' + (count - 1) * 7 + 'px;margin-left:-' + (count - 1) * 3 + 'px;" count="'+count+'" type="0" src="' + contextPath + '/images/cell/'+bb[k].fix+count+'.png"/>'; if(count == 6){ break; } count++; } if(sctype==0){ var radian = (bb[0].azimuth-90) * Math.PI / 180; var xMargin = Math.cos(radian) * imgheight[0]; var yMargin = Math.sin(radian) * imgheight[0]; var xx="",yy=""; if(xMargin>0) xx="left:"+xMargin*2+"px;"; if(xMargin<0) xx="right:"+Math.abs(xMargin)*2+"px;"; if(bb[0].azimuth==270||bb[0].azimuth==180){ yy="top:"+(10*0+yMargin*2)+"px;"; }else{ yy="top:"+yMargin*2+"px;"; } var s_html='<span class="img_span" style="'+xx+yy+'">'+bb[0].psc+'</span>'; var obj_psc=new Object(); obj_psc.id= bb[0].lac+"_"+bb[0].cellId; obj_psc.html=s_html; if($.inArray(0, modetypes_psc)>=0&&$.inArray(1, modetypes_psc)>=0) { obj_psc.net=3; if($("#pp_sc").find("span").length>0||$("#bb_ch").find("span").length>0){ html=html+s_html; } }else if($.inArray(1, modetypes_psc)>=0){ obj_psc.net=2; if($("#bb_ch").find("span").length>0){ html=html+s_html; } } else if($.inArray(0, modetypes_psc)>=0){ obj_psc.net=1; if($("#pp_sc").find("span").length>0){ html=html+s_html; } } span_map_psc.push(obj_psc); } } } var start_dex=0; for(var i = 0;i < st[0].baseName.length;i++){ if(st[0].baseName.charCodeAt(i) > 128){ start_dex=i; break; } } if (html != '') { var jizhan_html='<span class="img_p">'+st[0].baseName.substring(start_dex,st[0].baseName.length)+'</span>'; var obj_jizhan=new Object(); obj_jizhan.id= st[st.length-1].lac+"_"+st[st.length-1].cellId; obj_jizhan.html=jizhan_html; if($.inArray(0, jjzhan_modetype)>=0&&$.inArray(1, jjzhan_modetype)>=0) { obj_jizhan.net=3; if($("#jizhan_g3").find("span").length>0||$("#jizhan_g2").find("span").length>0){ html=html+jizhan_html; } }else if($.inArray(1, jjzhan_modetype)>=0){ obj_jizhan.net=2; if($("#jizhan_g2").find("span").length>0){ html=html+jizhan_html; } } else if($.inArray(0, jjzhan_modetype)>=0){ obj_jizhan.net=1; if($("#jizhan_g3").find("span").length>0){ html=html+jizhan_html; } } p_map_jizhan.push(obj_jizhan); var latLng = new BMap.Point(st[0].celllng,st[0].celllat); st[0].isclick=st[0].isclick==undefined?0:st[0].isclick; st[0].isdelet=st[0].isdelet==undefined?0:st[0].isdelet; s = new stationLayer(st, html, map, latLng,st[0].isclick,st[0].baseName.substring(start_dex,st[0].baseName.length),st[0].isdelet); stationMap.push(s); map.addOverlay(s); } } } } /** * google map 叠加层 * @param cells 小区数组 * @param html 展示的html * @param map map对象 * @param latLng 叠加层显示的经纬度 * @param isclick 单击事件是否有效 * @param labelText 标记 * @param isdelet 是否删除 * @returns */ function stationLayer(cells, html, map, latLng,isclick,labelText,isdelet) { this.map_ = map; this.text_ = html; this.latLng_ = latLng; this.labelText = labelText; this.div_ = null; this.data_ = cells; this.isdelet_=isdelet; this.isclick_ = isclick; } stationLayer.prototype = new BMap.Overlay(); stationLayer.prototype.initialize = function() { var div = document.createElement('P'); div.setAttribute('class', 'test'); div.style.border = 'none'; div.style.position = 'absolute'; $(div).html(this.text_); this.div_ = div; this.map_.getPanes().markerPane.appendChild(div); rotateStation(this.data_, this.map_,this.isclick_); return div; }; stationLayer.prototype.draw = function() { var latLng = this.map_.pointToOverlayPixel(this.latLng_); var div = this.div_; var ww = $(div).find('img').width() / 2; var hh = $(div).find('img').height(); var size = new BMap.Size(ww, hh); div.style.left = (latLng.x - size.width) + 'px'; div.style.top = (latLng.y - size.height) + 'px'; }; /** * ie8 * @param _data * @param _map * @param _isclick */ function rotateStationByIE(_data, _map,_isclick){ var len = _data.length; for(var i=0;i<len;i++){ if( _data[i].indoor==1) _data[i].azimuth=0; $("#img_" + _data[i].lac + "_" + _data[i].cellId).die().rotate({ angle : _data[i].azimuth, center : [ "50%", "100%" ], map : _map, isclick : _isclick }); } } /** * 绑定小区单击事件和图片旋转 * @param _data * @param _map * @param _isclick */ function rotateStation(_data, _map,_isclick) { if(commUtils.browser()=="ie" && commUtils.ieVersion() <= 8){ rotateStationByIE(_data, _map,_isclick); }else{ var len = _data.length; if(commUtils.browser()=="ie"){ for(var i=0;i<len;i++){ if( _data[i].indoor==1) _data[i].azimuth=0; var t; $("#img_" + _data[i].lac + "_" + _data[i].cellId).unbind().rotate({ bind : { click : function() { if(_isclick!=1){ $("#export_near").css('color',''); //清空上次点击的小区邻区颜色 var id = $(this).attr('id'); // if(click_cell != id){ clicktrunk = id cleanCellImg(); changeCells = []; var ccsObj = {}; var fix = 'red_'; var type = $(this).attr('type'); //当前点击小区设为默认颜色 var src=contextPath+'/images/cell/red_'+$(this).attr('count')+'.png'; //判断是否是时分 if(type==1){ src=contextPath+'/images/cell/c_red_'+$(this).attr('count')+'.png'; fix = 'c_red_'; } ccsObj["fix"] = fix; ccsObj["img_id"] = "#"+id; changeCells.push(ccsObj); $(this).css('margin-left',($(this).attr('count')-1)*-5); $(this).attr('src',src); //显示邻区关系 showNearInfo(id,_map); // } } }, mouseover:function(){ //if(_isclick!=1){ var id = $(this).attr('id'); t=setTimeout(function(){showcells(id,_map,$(this))},1000); //} },mouseout:function(){ //if(_isclick!=1) clearTimeout(t); } }, angle : _data[i].azimuth, center : [ "50%", "100%" ] }); } }else{ for(var i=0;i<len;i++){ if( _data[i].indoor==1) _data[i].azimuth=0; var t; $("#img_" + _data[i].lac + "_" + _data[i].cellId).unbind().rotate({ bind : { mouseup : function() { if(_isclick!=1){ $("#export_near").css('color',''); //清空上次点击的小区邻区颜色 var id = $(this).attr('id'); // if(click_cell != id){ clicktrunk = id cleanCellImg(); changeCells = []; var ccsObj = {}; var fix = 'red_'; var type = $(this).attr('type'); //当前点击小区设为默认颜色 var src=contextPath+'/images/cell/red_'+$(this).attr('count')+'.png'; //判断是否是时分 if(type==1){ src=contextPath+'/images/cell/c_red_'+$(this).attr('count')+'.png'; fix = 'c_red_'; } ccsObj["fix"] = fix; ccsObj["img_id"] = "#"+id; changeCells.push(ccsObj); $(this).css('margin-left',($(this).attr('count')-1)*-5); $(this).attr('src',src); //显示邻区关系 showNearInfo(id,_map); // } } }, mouseover:function(){ //if(_isclick!=1){ var id = $(this).attr('id'); t=setTimeout(function(){showcells(id,_map,$(this))},1000); //} },mouseout:function(){ //if(_isclick!=1) clearTimeout(t); } }, angle : _data[i].azimuth, center : [ "50%", "100%" ] }); } } } } // 小区连线方法 /******************************************************************************* * markerLatLng 点位置 cells 连接多个小区 /** * 根据CID、LAC查询小区的信息 * @param cid * @param lac */ var opts = {enableMessage:false}; function showcells(id,map,obj){ $.post(contextPath + "/gisgrad/showContent", {lac:id.split("_")[1], cid:id.split("_")[2]}, function(data){ cell=data.cell; ccg=data.ccg; cell.sctype=sctype; ccg.sctype=sctype; var html=""; if(ccg.modetype==0){ html = new EJS({url: contextPath+'/js/gisgrad/cell_info.ejs'}).render(ccg); }else if(ccg.modetype==1){ html = new EJS({url: contextPath+'/js/gisgrad/cell_info_gsm.ejs'}).render(ccg); } var jinwei=new BMap.Point(cell.celllng,cell.celllat); var infoWindow = new BMap.InfoWindow(html,opts); // 创建信息窗口对象 map.openInfoWindow(infoWindow, jinwei); // 打开信息窗口 }); } //小区连线方法 /*** * markerLatLng 点位置 * cells 连接多个小区 */ function countLatLng(cells, markerLatLng) { var line=[];//线路径 if(polyline){ _map.removeOverlay(polyline); for(var j=0;j<cells.length;j++){ var cc=cells[j]; var obj=$("#img_"+cc.lac+"_"+cc.cellId); line.push(getlanlngBypx(cc,obj)); line.push(markerLatLng); } } return line; } function getlanlngBypx(cc,obj){ if(sctype == 0){ cc.azimuth = cc.self_azimuth; }else{ cc.azimuth = cc.ant_azimuth; } if(obj.attr('type') != 0){ cc.azimuth=0; } var dis=obj.height()-1; var latLng= new BMap.Point(cc.celllng,cc.celllat); var pp =_map.pointToOverlayPixel(latLng); var radian = (cc.azimuth-90) * Math.PI / 180; var xMargin = Math.cos(radian) * dis; var yMargin = Math.sin(radian) * dis; //扇叶边缘经纬度 var ln=_map.overlayPixelToPoint( new BMap.Pixel(pp.x + xMargin,pp.y + yMargin)); return ln; } /*** * 显示邻区 * @param id * @param _map */ function showNearInfo(id,_map){ var lac_cid = id.substring(id.indexOf('_')+1,id.length); //var cid = id.substring(id.lastIndexOf('_')+1,id.length); var areas = $("#stationareaids").val(); var nettype = $("#cellnettype").val(); var indoor = $("#cellindoor").val(); var cellBands = $("#cellcellbands").val(); $.ajax({ type : 'get', url : contextPath + '/gisgrad/getnearcell', data : { lac_cid : lac_cid, areas : areas, modetypes : nettype, indoor : indoor, cellBands : cellBands }, async:false, success : function(data) { var thisCell = data.tcc; var list = data.list; var obj = new Object(); var bids = []; var len = list.length; var cells = []; // 首先判断该小区是否在地图上画过了 for ( var i = 0; i < len; i++) { var cell = list[i]; var img_id = "#img_" + cell.lac + "_" + cell.cellId; var _this = $(img_id); var src = contextPath + "/images/cell/"; var fix = ""; var ccsObj = {}; if(cell.indoor == 1){ fix+='c_'; }else{ fix+=''; } //判断邻区关系1、同频2、异频3、异网络 if (cell.nearrel == 1) { if($("#tp").find("span").length>0){ fix += 'green_'; }else{ continue; } } else if (cell.nearrel == 2) { if($("#yp").find("span").length>0){ fix += 'blue_'; }else{ continue; } } else if (cell.nearrel == 3) { if($("#ywl").find("span").length>0){ fix += 'yellow_'; }else{ continue; } } //邻区关系 1、正向 2、反向 3、双向 if (cell.neartype == 1) { fix += 'left_'; } else if (cell.neartype == 2) { fix += 'right_'; } //判断邻区是否已经画出来 if (_this.length == 0) { cell.fix=fix; cell.isclick=1; //cell.isdelet = 1; cells.push(cell); ccsObj["img_id"] = img_id; ccsObj["fix"] = fix; changeCells.push(ccsObj); }else{ _this.attr('src', src + fix + _this.attr('count') + '.png'); ccsObj["img_id"] = img_id; ccsObj["fix"] = fix; changeCells.push(ccsObj); } } groupBybid(cells,_map); } }); } /** * 根据基站ID分组再进行画 * @param cells * @param _map */ function groupBybid(cells,_map){ if(cells.length>0){ var bidMap={}; for ( var j = 0; j < cells.length; j++) { if (bidMap[cells[j].bid] == undefined) { var list = []; list.push(cells[j]); bidMap[cells[j].bid] = list; } else { bidMap[cells[j].bid].push(cells[j]); } } for (ss in bidMap) { var st = bidMap[ss]; drawStation(st, _map); } } } /** * 清除上次点击的小区换的颜色 */ function cleanCellImg() { for ( var i = 0; i < changeCells.length; i++) { var img = $(changeCells[i].img_id); var count = img.attr('count'); $(img).css('margin-left',(count-1)*-3); if(img.attr('type') == 0){ img.attr('src', contextPath + '/images/cell/sx' + count + ".png"); }else{ img.attr('src', contextPath + '/images/cell/c_' + count + ".png"); } } } /** * 删除所有基站信息 */ function removeStationMap(){ for ( var i = 0; i < stationMap.length; i++) { _map.removeOverlay(stationMap[i]); } stationMap = []; if(polyline){ _map.removeOverlay(polyline); markerLatLng_bit=null; } _map.closeInfoWindow(); } /** * 筛选当前可视区域的基站信息 * @param map * @returns {Array} */ function getBoundsStation(map){ //获取当前屏幕最大最小经纬度 var latLngBounds = map.getBounds(); var latLngNE = latLngBounds.getNorthEast(); var latLngSW = latLngBounds.getSouthWest(); var latNE = latLngNE.lat; var lngNE = latLngNE.lng; var latSW = latLngSW.lat; var lngSW = latLngSW.lng; var objArr = []; var lat,lng; var bslist = null; //组装数据 for(var i = 0;i < stationInitData.length; i++){ bslist = stationInitData[i].bsList; var obj = new Object(); obj["bsList"] = []; var bid = stationInitData[i].bid; var bslists = []; for(var j = 0; j < bslist.length; j++){ lat = bslist[j].celllat; lng = bslist[j].celllng; //谷哥经纬度转换为百度经纬度 if(lat >= latSW && lng >= lngSW && lat <= latNE && lng <= lngNE){ bslists.push(bslist[j]); } } if(bslists.length > 0){ obj["bsList"] = bslists; obj["bid"] = bid ; objArr.push(obj); } } return objArr; } /**` * 是否显示小区PSC标注 */ function isShowPsc(){ if($("#pp_sc").find("span").length==1){ for(var i=0;i<span_map_psc.length;i++){ var obj_psc=span_map_psc[i]; if((obj_psc.net==1||obj_psc.net==3)&&$("#img_"+obj_psc.id).prev(".img_span").length==0){ $("#img_"+obj_psc.id).before(obj_psc.html); } } }else{ for(var i=0;i<span_map_psc.length;i++){ var obj_psc=span_map_psc[i]; if(obj_psc.net==1){ $("#img_"+obj_psc.id).prev(".img_span").remove(); } } } if($("#bb_ch").find("span").length==1){ for(var i=0;i<span_map_psc.length;i++){ var obj_psc=span_map_psc[i]; if((obj_psc.net==2||obj_psc.net==3)&&$("#img_"+obj_psc.id).prev(".img_span").length==0){ $("#img_"+obj_psc.id).before(obj_psc.html); } } }else{ for(var i=0;i<span_map_psc.length;i++){ var obj_psc=span_map_psc[i]; if(obj_psc.net==2){ $("#img_"+obj_psc.id).prev(".img_span").remove(); } } } if($("#bb_ch").find("span").length==0&&$("#pp_sc").find("span").length==0){ $(".img_span").remove(); } } /**` * 是否显示基站名称标注 */ function isShowJizhan(){ if($("#jizhan_g3").find("span").length==1){ for(var i=0;i<p_map_jizhan.length;i++){ var obj_jizhan=p_map_jizhan[i]; if((obj_jizhan.net==1||obj_jizhan.net==3)&&$("#img_"+obj_jizhan.id).next(".img_p").length==0){ $("#img_"+obj_jizhan.id).after(obj_jizhan.html); } } }else{ for(var i=0;i<p_map_jizhan.length;i++){ var obj_jizhan=p_map_jizhan[i]; if(obj_jizhan.net==1){ $("#img_"+obj_jizhan.id).next(".img_p").remove(); } } } if($("#jizhan_g2").find("span").length==1){ for(var i=0;i<p_map_jizhan.length;i++){ var obj_jizhan=p_map_jizhan[i]; if((obj_jizhan.net==2||obj_jizhan.net==3)&&$("#img_"+obj_jizhan.id).next(".img_p").length==0){ $("#img_"+obj_jizhan.id).after(obj_jizhan.html); } } }else{ for(var i=0;i<p_map_jizhan.length;i++){ var obj_jizhan=p_map_jizhan[i]; if(obj_jizhan.net==2){ $("#img_"+obj_jizhan.id).next(".img_p").remove(); } } } if($("#jizhan_g3").find("span").length==0&&$("#jizhan_g2").find("span").length==0){ $(".img_p").remove(); } } var cacheCells = []; var clicktrunk = ""; var clearTimeoutId; function eventHandler(_this,_isclick){ $(_this).bind({ click:function(){ if(_isclick != 1){ $("#export_near").attr('color',''); var group = _this.parentNode, span = group.parentNode, img = $("#"+span.getAttribute("myid")), id = img.attr("id"), count = img.attr('count'), azimuth = img.attr("azimuth"), isclick = img.attr("isclick"), type = img.attr("type"); // if(click_cell != id){ clicktrunk = id; clearCells(); cacheCells.length = 0; var src = contextPath+'/images/cell/red_'+count+'.png'; if(type==1){ src=contextPath+'/images/cell/c_red_'+count+'.png'; } img.attr("src",src); $(span).empty().remove(); nearHandler(id); img.rotate({ angle : type==1?0:azimuth-360, center : [ "50%", "100%" ], isclick : isclick}); cacheCells.push(id); // } } }, mouseover:function(){ //if(_isclick != 1){ var group = _this.parentNode, span = group.parentNode, img = $("#"+span.getAttribute("myid")), id = img.attr("id"); clearTimeoutId=setTimeout(function(){showcells(id,_map,$(_this));},1000); //} }, mouseout:function(){ //if(_isclick != 1){ if(clearTimeoutId) clearTimeout(clearTimeoutId); //} } }); } /** * clear near */ function clearCells(){ for(var i=0,len=cacheCells.length; i<len; i++){ (function(id){ var img = $("#"+id), azimuth = img.attr("azimuth"), count = img.attr('count'), type = img.attr("type"), isclick = img.attr("isclick"), src = contextPath+'/images/cell/sx'+count+'.png'; if(type == 1){ src = contextPath+'/images/cell/c_'+count+'.png'; } img.attr("src",src); $("#"+id+"_span").empty().remove(); img.rotate({ angle : type==1?0:azimuth-360, center : [ "50%", "100%" ], isclick : isclick}); })(cacheCells[i]); } } /** * near handler */ function nearHandler(id){ var lac_cid = id.substring(id.indexOf('_')+1,id.length); //var cid = id.substring(id.lastIndexOf('_')+1,id.length); var areas = $("#stationareaids").val(); var nettype = $("#cellnettype").val(); var indoor = $("#cellindoor").val(); var cellBands = $("#cellcellbands").val(); $.ajax({ type : 'get', url : contextPath + '/gisgrad/getnearcell', data : { lac_cid : lac_cid, areas : areas, modetypes : nettype, indoor : indoor, cellBands : cellBands }, async:false, success : function(data) { var list = data.list; var len = list.length; var cells = []; // 首先判断该小区是否在地图上画过了 for ( var i = 0; i < len; i++) { var cell = list[i]; var img_id = "img_" + cell.lac + "_" + cell.cellId; var _this = document.getElementById(img_id); var src = contextPath + "/images/cell/"; var fix = ""; if(cell.indoor == 1){ fix+='c_'; }else{ fix+=''; } //判断邻区关系1、同频2、异频3、异网络 if (cell.nearrel == 1) { if($("#tp").find("span").length>0){ fix += 'green_'; }else{ continue; } } else if (cell.nearrel == 2) { if($("#yp").find("span").length>0){ fix += 'blue_'; }else{ continue; } } else if (cell.nearrel == 3) { if($("#ywl").find("span").length>0){ fix += 'yellow_'; }else{ continue; } } //邻区关系 1、正向 2、反向 3、双向 if (cell.neartype == 1) { fix += 'left_'; } else if (cell.neartype == 2) { fix += 'right_'; } //判断邻区是否已经画出来 if (!_this) { cell.fix=fix; cell.isclick=1; //cell.isdelet = 1; cells.push(cell); }else{ var type = _this.getAttribute('type'); _this.src = src + fix + _this.getAttribute('count') + '.png'; $("#"+img_id+"_span").empty().remove(); $(_this).rotate({ angle : type==1?0:_this.getAttribute("azimuth")-360, center : [ "50%", "100%" ], isclick : _this.getAttribute("isclick")}); } cacheCells.push(img_id); } if(cells.length>0){ drawStation(cells, _map); } } }); } <file_sep>/src/main/webapp/js/reportIndependent/reportExcel.js $(function(){ $(".reportExcel").click(function(){ var col=["submitDateTime","netType","dealPath","area","testDateTime","breakflag", "workerid","operationClassify","acceptance","clientid","customer","testTime", "url" ,"contentrs" ,"module","serialno","indoor","roomName","room","gpsName", "scene","operationType","wcdmaRatio","gsmRatio","noService","evaluate"]; var value="{"; value +="\"serialnoFlow\":\""+ $("#ss_id").text()+"\""; value +=",\"gps\":\""+$("span[name='exc_gps']").text()+"\""; value +=",\"testUrl\":\""+$("span[name='exc_testUrl']").text()+"\""; for(var i=0;i<col.length;i++){ value +=",\""+col[i]+"\":\""+ ($("td[name=exc_"+col[i]+"]").text().replace(/\s+/g, "")).replace('\"', "!_!")+"\""; } //选中项 value +=",\"targetType\":\""+"Rxlev"+"\""; //采集点数 var aa = $("#sum_count").text(); value +=",\"point\":\""+aa.substring(4,aa.length)+"\""; value +="}"; //工单流水号 var flowid = $("#SelectBox").combobox("getValue"); var graph= graphList(); //评价 var eval_value = compEvalList(); $("#background").show(); $("#bar_id").show(); $(document).css({ "overflow" : "hidden" }); var ping = pingList(); $.ajax({ url:contextPath + "/reportIndependent/reportExcel", type:"post", data:{value:value,graph:graph,eval:eval_value,flowid:flowid,ping:ping}, dataType:"json", success:function(data){ location.href=contextPath +"/reportIndependent/downLoad?name="+data; $("#background").hide(); $("#bar_id").hide(); $(document).css({ "overflow" : "auto" }); } }); }); }); function pingList(){ var pingList = ["pinglo","pingdmax","pingdmix","pingdavg","httpsmax","httpsmin","httpsavg","httptmax","httptmix","httptavg"]; var value="{"; value +="\"test\":\"0\""; for(var i=0;i<pingList.length;i++){ value +=",\""+pingList[i]+"\":\""+ $("td[name="+pingList[i]+"]").text()+"\""; } value+="}"; return value; } /** * 柱状图数据 * @returns {String} */ function graphList(){ var graph = "{"; for(var i =0;i<flist_excel.length;i++){ var flist = flist_excel[i]; if(flist.x.length<=0||flist.y.length<=0){ continue; } var name = flist.kpiname; var listx = flist.x; var listy = flist.y; var x = listx.length; var y = listy.length; if(name==="BCCH"||name==="PSC"){ for(var j = 0;j<6;j++){ if(j<x){ graph +="\""+name+"_x\":\""+ listx[j]+"\","; }else{ graph +="\""+name+"_x\":\"\","; } if(j<y){ var yv = listy[j].percent; graph +="\""+name+"_y\":\""+ yv+"\","; }else{ graph +="\""+name+"_y\":\"\","; } } }else{ for(var j = 0;j<6;j++){ if(j<x){ graph +="\""+name+"_x\":\""+ listx[j]+"\","; }else{ graph +="\""+name+"_x\":\"\","; } } if(listy[0].one!=""){ graph +="\""+name+"_y\":\""+listy[0].one+"\","; }else{ graph +="\""+name+"_y\":\"\","; } if(listy[0].two!=""){ graph +="\""+name+"_y\":\""+listy[0].two+"\","; }else{ graph +="\""+name+"_y\":\"\","; } if(listy[0].three!=""){ graph +="\""+name+"_y\":\""+listy[0].three+"\","; }else{ graph +="\""+name+"_y\":\"\","; } if(listy[0].four!=""){ graph +="\""+name+"_y\":\""+listy[0].four+"\","; }else{ graph +="\""+name+"_y\":\"\","; } if(listy[0].five!=""){ graph +="\""+name+"_y\":\""+listy[0].five+"\","; }else{ graph +="\""+name+"_y\":\"\","; } if(listy[0].six!=""){ graph +="\""+name+"_y\":\""+listy[0].six+"\","; }else{ graph +="\""+name+"_y\":\"\","; } } } graph = graph.substring(0,graph.length-1); graph +="}"; return graph; } /** * 评价数据 */ function compEvalList(){ var eval_value = "{"; if(compEval_excel[0]!=null){ eval_value +="\"gsm\":\""+ compEval_excel[1]+"\","; eval_value +="\"gsm_c\":\""+ compEval_excel[0]+"\","; } if(compEval_excel[2]!=null){ eval_value +="\"wcdma\":\""+ compEval_excel[3]+"\","; eval_value +="\"wcdma_c\":\""+ compEval_excel[2]+"\","; } if(compEval_excel[0]==null&&compEval_excel[2]==null){ eval_value +="\"noservice\":\"无\","; } for(var i =0;i<flist_excel.length;i++){ var flist = flist_excel[i]; if(flist.gradName==null||flist.gradColor==null){ continue; } eval_value +="\""+flist.kpiname+"\":\""+ flist.gradName+"\","; eval_value +="\""+flist.kpiname+"_c\":\""+ flist.gradColor+"\","; } eval_value += "}"; return eval_value; }<file_sep>/src/main/java/com/complaint/service/EpinfoExcelService.java package com.complaint.service; import java.awt.Color; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFDataFormat; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.complaint.dao.EpinfoDao; import com.complaint.model.AreaBean; import com.complaint.model.Epinfo; import com.complaint.utils.Constant; @Service("epinfoExcelService") public class EpinfoExcelService { @Autowired private EpinfoDao epinfoDao; @Autowired private EpinfoService epinfoService; private static final Logger logger = LoggerFactory.getLogger(EpinfoExcelService.class); private List<Epinfo> el; private String errorname;//错误文件名字 /** * 查出area信息 */ public List<AreaBean> getAreaBean(){ return epinfoDao.getAreaBean(); } /** * 查出终端信息 */ public List<Epinfo> getInformation(){ return epinfoDao.getAllEpinfoList(); } /** * 生成终端信息excel */ public void createExcel(String path){ List<Epinfo> list = getInformation(); //创建excel和sheet XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet("终端信息"); //第一行 ,有就直接调用,没有就创建 XSSFRow rowTop = null; if(sheet.getRow(0) != null){ rowTop = sheet.getRow(0); }else{ rowTop = sheet.createRow(0); } //获取列名样式 CellStyle topStyle = getColumnStyle(wb); //第一列 区域 XSSFCell areaTop = rowTop.createCell(0); areaTop.setCellValue("区域"); areaTop.setCellStyle(topStyle); //第二列 UUID XSSFCell uuidTop = rowTop.createCell(1); uuidTop.setCellValue("UUID"); uuidTop.setCellStyle(topStyle); //第三列 责任人 XSSFCell functionaryTop = rowTop.createCell(2); functionaryTop.setCellValue("责任人"); functionaryTop.setCellStyle(topStyle); //第四列 联系电话 XSSFCell teltphoneTop = rowTop.createCell(3); teltphoneTop.setCellValue("联系电话"); teltphoneTop.setCellStyle(topStyle); //第五列 授权状态 XSSFCell islockTop = rowTop.createCell(4); islockTop.setCellValue("授权状态"); islockTop.setCellStyle(topStyle); //第六列 更新时间 XSSFCell updatetimeTop = rowTop.createCell(5); updatetimeTop.setCellValue("更新时间"); updatetimeTop.setCellStyle(topStyle); //填充类容 CellStyle style = getNormalStyle(wb); for(int i = 0;i<list.size();i++){ XSSFRow row = null; if(sheet.getRow(i+1)!=null){ row = sheet.getRow(i+1); }else{ row = sheet.createRow(i+1); } //第一列 区域 XSSFCell cellArea = row.createCell(0); cellArea.setCellValue(list.get(i).getAreaname()==null?"暂无":list.get(i).getAreaname()); cellArea.setCellStyle(style); //第二列 uuid XSSFCell celluuid = row.createCell(1); celluuid.setCellValue(list.get(i).getUuid()); celluuid.setCellStyle(style); //第三列 责任人 XSSFCell cellFunctionary = row.createCell(2); cellFunctionary.setCellValue(list.get(i).getFunctionary() == null?"暂无":list.get(i).getFunctionary()); cellFunctionary.setCellStyle(style); //第四列 联系电话 XSSFCell cellteltphone = row.createCell(3); cellteltphone.setCellValue(list.get(i).getTeltphone()==null?"暂无":list.get(i).getTeltphone()); cellteltphone.setCellStyle(style); //第五列 授权状态 XSSFCell cellislock = row.createCell(4); cellislock.setCellValue(list.get(i).getIslock()==1?"已授权":"未授权"); cellislock.setCellStyle(style); //第六列 更新时间 XSSFCell cellupdatetime = row.createCell(5); //格式化时间 String fmtime = timeFormat(list.get(i).getUpdatetime()); cellupdatetime.setCellValue(fmtime); cellupdatetime.setCellStyle(style); } //单元格自动适应内容长度 for(int i = 0; i < 6; i++){ sheet.autoSizeColumn(i, true); } try { // 获取一个输出流 FileOutputStream fileOut = new FileOutputStream(path); // 生成Excel wb.write(fileOut); // 关闭流 fileOut.close(); } catch (Exception e) { logger.error("close inputStream",e); } } /** * 创建Excel每列title样式 */ public XSSFCellStyle getColumnStyle(XSSFWorkbook wb) { XSSFCellStyle style = wb.createCellStyle(); XSSFDataFormat format = wb.createDataFormat(); // 加边框线 //style.setBorderBottom(CellStyle.BORDER_THIN);// 下方加边框 //style.setBottomBorderColor(IndexedColors.BLACK.getIndex());// 下方边框样式 //style.setBorderLeft(CellStyle.BORDER_THIN);// 左方加边框 //style.setLeftBorderColor(IndexedColors.BLACK.getIndex());// 左方边框样式 //style.setBorderRight(CellStyle.BORDER_THIN);// 右方加边框 //style.setRightBorderColor(IndexedColors.BLACK.getIndex());// 右方边框样式 //style.setBorderTop(CellStyle.BORDER_THIN);// 上方加边框 //style.setTopBorderColor(IndexedColors.BLACK.getIndex());// 上方边框样式 // 对齐方式 style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中 // 设置前端颜色 style.setFillForegroundColor(new XSSFColor(new Color(0, 150, 255))); // 设置填充模式 style.setFillPattern(CellStyle.SOLID_FOREGROUND); // 字体样式 XSSFFont font = wb.createFont();// 创建字体对象 font.setFontHeightInPoints((short) 15);// 设置字体大小 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 设置粗体 font.setFontName("宋体");// 设置为黑体字 style.setFont(font);// 将字体加入到样式对象 style.setDataFormat(format.getFormat("@")); return style; } /** * 创建Excel数据一般样式 */ public XSSFCellStyle getNormalStyle(XSSFWorkbook wb) { XSSFCellStyle style = wb.createCellStyle(); XSSFDataFormat format = wb.createDataFormat(); // 加边框线 //style.setBorderBottom(CellStyle.BORDER_THIN);// 下方加边框 //style.setBottomBorderColor(IndexedColors.BLACK.getIndex());// 下方边框样式 //style.setBorderLeft(CellStyle.BORDER_THIN);// 左方加边框 //style.setLeftBorderColor(IndexedColors.BLACK.getIndex());// 左方边框样式 //style.setBorderRight(CellStyle.BORDER_THIN);// 右方加边框 //style.setRightBorderColor(IndexedColors.BLACK.getIndex());// 右方边框样式 //style.setBorderTop(CellStyle.BORDER_THIN);// 上方加边框 //style.setTopBorderColor(IndexedColors.BLACK.getIndex());// 上方边框样式 // 对齐方式 style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平居中 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中 // 字体样式 XSSFFont font = wb.createFont();// 创建字体对象 font.setFontHeightInPoints((short) 12);// 设置字体大小 //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 设置粗体 font.setFontName("宋体");// 设置为黑体字 style.setFont(font);// 将字体加入到样式对象 style.setDataFormat(format.getFormat("@")); return style; } /** * 格式化时间 */ public String timeFormat(Date date){ DateFormat fm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String time = fm.format(date); return time; } /** * 导入控制 * @param inp * @return -1 文件类型错误,0成功 */ public Map<String,Object> leadSerice(MultipartFile file,String filePath){ Map<String,Object> mr = new HashMap<String,Object>(); mr.put("result", 0); mr.put("add", 0); mr.put("update", 0); mr.put("unchange", 0); List<Epinfo> list = new ArrayList<Epinfo>(); List<Epinfo> errorList = new ArrayList<Epinfo>(); List<AreaBean> ab = this.getAreaBean();//查出所有areaid对应areaname InputStream inp = null; Map<String ,Object> leadMap = new HashMap<String ,Object>(0); int startnum = 0; try { inp = file.getInputStream(); leadMap = this.getExcelInformation(inp);//解析excel list = (List<Epinfo>) leadMap.get("list");//解析excel startnum = (Integer) leadMap.get("startnum"); } catch (IOException e) { logger.error("lead excel", e); mr.put("result", 1); return mr; } finally { try { if(inp!=null){ inp.close(); } } catch (IOException e) { logger.error("close inputStream", e); } } List<Integer> errornumm = new ArrayList<Integer>(); for(int i=0;i<list.size();i++){ boolean flag = false; //验证手机格式 if(!this.isNum(list.get(i).getTeltphone(),i)){ flag = true; errorList.add(list.get(i)); errornumm.add(i+startnum); continue; } //验证负责人 if(!flag){ if(!this.isChinese(list.get(i).getFunctionary(),i)){ flag = true; errorList.add(list.get(i)); errornumm.add(i+startnum); continue; } } //验证区域 if(!flag){ int areaid = this.getAreaId(ab,list.get(i).getAreaname()); if(areaid == 0){ flag = true; errorList.add(list.get(i)); errornumm.add(i+startnum); continue; }else{ list.get(i).setAreaid(areaid); } } //判断UUID是否正确 if(!flag){ if(!judgeuuid(list,list.get(i).getUuid(), i)){ flag = true; errorList.add(list.get(i)); errornumm.add(i+startnum); continue; } } } InputStream inp2 = null; try { inp2 = file.getInputStream(); } catch (IOException e) { logger.error("get io",e); } if(errornumm.size()>0){//如果有错误的行 try { String errorname = this.createError(inp2,errornumm,filePath); mr.put("errorname", errorname); } catch (IOException e) { logger.error("create error template",e); } } try { if(inp2!=null){ inp2.close(); } } catch (IOException e) { logger.error("close io",e); } if(errornumm.size()<=0){ Map<String ,List<Epinfo>> map = this.classifyUUID(list); //根据UUID分为新增或修改 if(map.get("insert").size()!=0){ if(this.insert(map.get("insert"))!=0){//保存新增数据 mr.put("result", 2); return mr; } } if(map.get("update").size()!=0){ for(Epinfo ep:map.get("update")){//修改已有的uuid try { epinfoService.updateEpinfo(ep);//保存修改数据 } catch (Exception e) { logger.error("update epinfo",e); mr.put("result", 2); return mr; } } } mr.put("unchange", map.get("unchange").size()); mr.put("add", map.get("insert").size()); mr.put("update",map.get("update").size()); }else{ if(errornumm.size()>0){ mr.put("result", 3); } mr.put("unchange",0); mr.put("add",0); mr.put("update",0); } return mr; } /** * 解析excel * @param path * @return * @throws IOException */ public Map<String ,Object> getExcelInformation(InputStream inp) throws IOException{ List<Epinfo> list = new ArrayList<Epinfo>(); Map<String ,Object> map = new HashMap<String ,Object>(); int startnum =0;//excel起始解析行 //根据input流生成excel XSSFWorkbook wb = new XSSFWorkbook(inp); //获得excel的第一条 XSSFSheet sheet = wb.getSheetAt(0); //获取行数 st.getLastRowNum(); //遍历第一张表的所有行 boolean flag = false;//找到第一个返回“区域的行” int rownum =0;//只检查前10行 for(int i=0;i<sheet.getLastRowNum()+1;i++){ Epinfo epinfo = new Epinfo(); //获取行 XSSFRow row = sheet.getRow(i); if(!flag){ XSSFCell cell =null; cell= row.getCell(0); String value = getValue(cell); if("区域".equals(value)){ flag = true; startnum = i; }else{ rownum++; } if(rownum<10){ continue;//前十行没找到数据就继续循环 }else{ break;//十行之后没找到数据就跳出 } } //遇到第一个区域为空的就直接跳出 String stra = null; boolean v0 = false;//判断区域是否为空 boolean v1 = false;//判断UUID是否为空 boolean v2 = false;//判断责任人是否为空 boolean v3 = false;//判断联系电话是否为空 for(int j=0;j<5;j++){ XSSFCell cell = null;//如果输入一行中漏一项则捕获异常 try { cell= row.getCell(j); } catch (Exception e) { logger.error("lead have no data of row",e); break; } String value = getValue(cell); if(j==0){//区域 if(value == null){ v0 = true; } epinfo.setAreaname(value); }else if(j==1){ if(value == null){//UUID v1 = true; } epinfo.setUuid(value); }else if(j==2){//责任人 if(value == null){ v2 = true; } epinfo.setFunctionary(value); }else if(j==3){//联系电话 if(value == null){ v3 = true; } epinfo.setTeltphone(value); }else if(j==4){//授权 if(v0&&v1&&v2&&v3){ break; } int islock =0; if(value == null||value.equals("未授权")){ islock =0; }else if(value.equals("已授权")){ islock =1; }else{ break; } epinfo.setIslock(islock); } } if(v0&&v1&&v2&&v3){//当四个属性全为空的时候,跳出循环,并不 break; } list.add(epinfo); } map.put("list", list); map.put("startnum", startnum); return map; } /** * 获取单元格内容 */ public String getValue(XSSFCell cell){ String value = null; if(cell==null){ return value; } //查出单元格类型 try { switch(cell.getCellType()){ case XSSFCell.CELL_TYPE_STRING://字符串--文本类型 value = cell.getRichStringCellValue().toString().trim(); break; case XSSFCell.CELL_TYPE_NUMERIC://数字类型 if (DateUtil.isCellDateFormatted(cell)){//时间类型 value = cell.getDateCellValue().toString(); }else{ DecimalFormat df = new DecimalFormat("0"); String str = String.valueOf(df.format(cell.getNumericCellValue())).trim(); if(str!=null&&!"".equals(str)){ String [] strArray =str.split("."); if(strArray!=null&&strArray.length>1){ value = strArray[0]; }else{ value = str; } } } break; case XSSFCell.CELL_TYPE_BOOLEAN://boolean类型 value = String.valueOf(cell.getBooleanCellValue()).trim(); break; case XSSFCell.CELL_TYPE_FORMULA://公式类型 value = cell.getCellFormula().trim(); break; } } catch (Exception e) { logger.error("get lead excel null",e); } return value; } /** * 判断电话内容全是数字 */ public boolean isNum(String str ,Integer i){ if(str == null){ return false; } String param = "^(([0-9]{3}-[0-9]{8})|([0-9]{4}-[0-9]{7})|([0-9]{8})|([0-9]{11})|[0-9]{7}){1}$"; Pattern pattern = Pattern.compile(param); Matcher matcher = pattern.matcher( str ); if(!matcher.matches()){ return false; } return true; } /** * 验证名字为中文 */ public boolean isChinese(String str ,Integer i){ if(str == null){ return false; } if(str!=null){ String param = "^[\u4e00-\u9fa5]+$"; Pattern pattern = Pattern.compile(param); Matcher matcher = pattern.matcher(str); if(!matcher.matches()){ return false; } } return true; } /** * 验证根据区域查出并赋值区域id */ public Integer getAreaId(List<AreaBean> ab,String str){ int areaid = 0; if(str == null){ return areaid; } for(int j=0;j<ab.size();j++){ if(ab.get(j).getAreaname().equals(str)){ areaid = ab.get(j).getAreaid(); } } return areaid; } /** * 将UUID按照新增和修改,错误分类 */ public Map<String,List<Epinfo>> classifyUUID(List<Epinfo> list){ Map<String,List<Epinfo>> map = new HashMap<String,List<Epinfo>>(); List<Epinfo> insertEP = new ArrayList<Epinfo>();//存放数据库没有的 List<Epinfo> updateEP = new ArrayList<Epinfo>();//存放数据库已有的 List<Epinfo> errorEP = new ArrayList<Epinfo>();//存放数据库已有的 List<Epinfo> unchange = new ArrayList<Epinfo>();//为改变的 List<Epinfo> alluuid = this.getInformation();//查出数据库所有的信息 for(int i=0;i<list.size();i++){ String leadep = list.get(i).getUuid(); boolean flag = false;//用来判断在某部是否验证通过加入list,是就跳出当前循环 for(Epinfo epinfo:alluuid){//判断uuid在数据库中是否存在 if(epinfo.getUuid().equals(leadep)){ if((epinfo.getFunctionary()==null?"":epinfo.getFunctionary()).equals(list.get(i).getFunctionary()) && (epinfo.getAreaid()==null?"":epinfo.getAreaid()).equals(list.get(i).getAreaid()) && (epinfo.getTeltphone()==null?"":epinfo.getTeltphone()).equals(list.get(i).getTeltphone()) && (epinfo.getIslock()==null?0:epinfo.getIslock()) == list.get(i).getIslock()){//如果完全相等,不做处理 flag = true; unchange.add(list.get(i)); break; } list.get(i).setId(epinfo.getId()); updateEP.add(list.get(i));//存在就将epinfo加入insertEP flag = true; break; } } if(flag == true){continue;}//epinfo判断是否加入insertEP,是就跳出当前这次 if(!this.uuidFormat(leadep)){//判断uuid是否格式正确,不正确就加入错误集合 errorEP.add(list.get(i)); continue;//加入错误集合后跳出本次循环 } insertEP.add(list.get(i));//数据库不存在,格式又正确,加入新增集合 } map.put("insert", insertEP); map.put("update", updateEP); map.put("error", errorEP); map.put("unchange", unchange); return map; } /** * 判断UUID的格式是否正确 */ public boolean uuidFormat(String str){ if(str == null){ return false; } String param = "^[0-9]{15}$"; Pattern pattern = Pattern.compile(param); Matcher matcher = pattern.matcher(str); return matcher.matches(); } /** * 整理格式调用原来的存储方式 */ public Integer insert(List<Epinfo> epinfo){ String[] uuids = new String[epinfo.size()]; Integer[] areaid = new Integer[epinfo.size()]; String[] functionary = new String[epinfo.size()]; String[] teltphone = new String[epinfo.size()]; Integer[] islock = new Integer[epinfo.size()]; for(int i = 0 ;i<epinfo.size();i++){ uuids[i] = epinfo.get(i).getUuid(); areaid[i] = epinfo.get(i).getAreaid(); functionary[i] = epinfo.get(i).getFunctionary(); teltphone[i] = epinfo.get(i).getTeltphone(); islock[i] = epinfo.get(i).getIslock(); } Map<String, Object> map = new HashMap<String, Object>(); try { map = epinfoService.addEpinfo(uuids,areaid,functionary,teltphone,islock); } catch (Exception e) { logger.error("batch add EpInfo error.",e); map.put("msg", 0); } if(map.get("msg") != null && (Integer.parseInt(map.get("msg").toString()) == 1)){ return 0; }else{ return -1; } } /** * 判断UUID是否正确 */ public boolean judgeuuid(List<Epinfo> list ,String uuid ,Integer num){ if(uuid!=null && uuidFormat(uuid)){ for(int i=0;i<list.size();i++){ if(uuid.equals(list.get(i).getUuid()) && num!=i){ return false; } } return true; }else{ return false; } } /** * 生成错误文件 * @throws IOException */ public String createError(InputStream inp ,List<Integer> errornumm,String filePath) throws IOException{ //根据input流生成excel XSSFWorkbook wb = new XSSFWorkbook(inp); //获得excel的第一条 XSSFSheet sheet = wb.getSheetAt(0); //第一行 ,有就直接调用,没有就创建 XSSFRow row = null; XSSFCellStyle style = wb.createCellStyle(); style.setFillForegroundColor(new XSSFColor(new Color(255,0,0)));// 设置前端颜色 style.setFillPattern(CellStyle.SOLID_FOREGROUND);// 设置填充模式 style.setAlignment(XSSFCellStyle.ALIGN_CENTER); for(int i = 0;i<errornumm.size();i++){ if(sheet.getRow(errornumm.get(i)+1) != null){ row = sheet.getRow(errornumm.get(i)+1); }else{ row = sheet.createRow(errornumm.get(i)+1); } for(int j = 0;j<5;j++){ XSSFCell cell = null; if(row.getCell(j) == null){ cell = row.createCell(j);//如果输入一行中漏一项则捕获异常 }else{ cell = row.getCell(j); } cell.setCellStyle(style); } //row.setRowStyle(style); } Date d = new Date(); long time = d.getTime(); String errorname = String.valueOf(time); try { //判断路径是否存在 File file=new File(filePath+Constant.CAS_SYSTEM_TERMINAL_ERROR_PATH); if(!file .exists()&&!file .isDirectory()) { file .mkdirs(); } // 获取一个输出流 FileOutputStream fileOut = null; try { fileOut = new FileOutputStream(filePath+Constant.CAS_SYSTEM_TERMINAL_ERROR_PATH+errorname+".xlsx"); } catch (Exception e) { logger.error("get error excel fault" , e); } // 生成Excel wb.write(fileOut); // 关闭流 if(fileOut!=null){ fileOut.close(); } } catch (Exception e) { logger.error("close inputStream",e); } return errorname; } /** * 获取错误文件名字 */ public String getErrorName(){ return errorname; } } <file_sep>/src/main/webapp/js/workorder/rate.js $(function(){ $(".easyui-combobox").combobox({ onSelect: function(){ var oldval = $(this).attr("oldval"); var newval = $(this).combobox('getValue'); var text = ""; switch(parseInt(newval)){ case 1: text = ">"; break; case 2: text = "≥"; break; case 3: text = "<"; break; case 4: text = "≤"; break; } $(this).combobox("setText",text); var isc = $(this).attr("isc"); if(oldval != newval && isc ==0){ isChange ++; $(this).attr("isc",1); }else{ if(oldval == newval && isc==1){ isChange --; $(this).attr("isc",0); } } }, onBeforeLoad:function(){ var text = $(this).combobox("getText"); if(text == "&lt;"){ text = $(this).combobox("setText","<"); } if(text == "&gt;"){ text = $(this).combobox("setText",">"); } } }); //给FTP平局速度的最大值不全正无穷符号 $(".avgMax").each(function(){ //失去焦点,检查为没有","直接添加 $(this).live('blur',function(){ //先获得一次对象的验证结果,为防止从错误格式快速改成正确又进行失去焦点事件,导致的处理完还有格式不正确的图表 if($(this).validatebox("isValid")){ var b = $(this).val(); var a = addMaxValue(b); $(this).val(a); //增加正无穷后,判定与原来数据时候改变,修改判定改变的ischange和isc if(a!=b){ var oldval = $(this).attr("oldval"); var isc = $(this).attr("isc"); if(oldval != a && isc ==0){ }else{ if(oldval == a && isc==1){ isChange --; $(this).attr("isc",0); } } } } }); }); }); //自动添加+∞符号 function addMaxValue(a){ if(a.split(",").length==1){ var b = a.substring(0,a.length-1)+",+∞)"; a = b; } return a; } //给予没有输入两个数值的平均速率添加+∞ function addMax(a){ if(a.split(",")==1){ var b = a.substring(0,a.split(",").length-1)+",+∞)"; return b; }else{ return a; } } function validate(){ //验证rxlev,rxqual,rscp,ecno,txpower var type = ["rxlev","rxqual","ci","rscp","ecno","txpower","rsrp","rsrq","sinr"]; for(var i=0;i<type.length;i++){ if(!evalVerify(type[i],"outside")){ return false; } } for(var i=0;i<type.length;i++){ if(!evalVerify(type[i],"inside")){ return false; } } //验证ftp var direct =["up","up","up","up","down","down","down","down"]; var avg =["Value","Avg","Value","Avg","Value","Avg","Value","Avg"]; var scene = ["Outside","Outside","Inside","Inside","Outside","Outside","Inside","Inside"]; for(var i = 0;i<direct.length;i++){ if(!evalftpVerify("ftp",direct[i],avg[i],scene[i])){ return false; } } return true; } /** * 自检区间值左边数值是否小于右边数字 * @param a * @returns {Boolean} */ function validateMyself(a){ var num =a.split(","); var left = num[0].substring(1,num[0].length); var right; var leftSign=""; var rightSign=""; if(num.length>1){ leftSign = num[0].substring(0,1); rightSign = num[1].substring(num[1].length-1,num[1].length); } if(num[1]==="+∞)"){ right = 999999; }else{ right = num[1].substring(0,num[1].length-1); } if(leftSign ==="[" &&rightSign === "]"){ if(parseInt(left)<=parseInt(right)){ return true; }else{ return false; } }else{ if(parseInt(left)<parseInt(right)){ return true; }else{ return false; } } } /** * 比较相邻区间两个值是否是符号类型不同,数值相同 * @param a * @param b * @returns {Boolean} */ function validateInterval(a,b){ //每个参数为[x,y]形式 var num1 = a.split(","); var num2 = b.split(","); var sn1 = num1[0].substring(1,num1[0].length); var sn2 = num2[1].substring(0,num2[1].length-1); var sign1= num1[0].substring(0,1); var sign2= num2[1].substring(num2[1].length-1,num2[1].length); var sign3; if(sign1==="("){ sign3=")"; }else{ sign3="]"; } if(sign2!=sign3 && parseInt(sn1)==parseInt(sn2)){ return true; }else{ return false; } } /** * 不填右变数值的区间值转化为右边为最大值 */ function changeNoRight(a){ if(a.split(",").length==1){ var b = a.substring(0,a.length-1)+",+∞)"; a = b; } return a; } /** *判断是否修改过 */ function isChangeVal(arg){ var oldval = $(arg).attr("oldval"); var newval = $(arg).val(); var isc = $(arg).attr("isc"); if(oldval != newval && isc ==0){ isChange ++; $(arg).attr("isc",1); }else{ if(oldval == newval && isc==1){ isChange --; $(arg).attr("isc",0); } } } /** *区间值交接如果数字相同则,符号不同 */ function intervalJudge(a,b){ var c = b.split(",")[1]; var maxnum = a.substring(1,a.split(",")[0].length); var minnum = c.substring(0,c.length-1); if(parseInt(maxnum) < parseInt(minnum)){ return false; }else{ if(parseInt(maxnum) == parseInt(minnum)){ var tempSign = a.substring(0,1); var maxSign=""; if(tempSign=="("){ var maxSign = ")"; } if(tempSign=="["){ var maxSign = "]"; } var minSign = b.substring(b.length-1,b.length); if(maxSign==minSign){ return false; } } } return true; } /** *判断条件相等时进行区间值判断 */ function termJudge(type,scene,typeId){ var typeValue1 = $("#"+typeId+1).val(); var typeValue2 = $("#"+typeId+2).val(); var typeValue3 = $("#"+typeId+4).val(); var ari1 = $($("#"+type+"_arithmetic_"+scene+"1").next()[0]).find("input[name="+type+'_arithmetic'+"]").val(); var val1 = $("#"+type+"_value_"+scene+"1").val(); var ari2 = $($("#"+type+"_arithmetic_"+scene+"2").next()[0]).find("input[name="+type+'_arithmetic'+"]").val(); var val2 = $("#"+type+"_value_"+scene+"2").val(); var ari4 = $($("#"+type+"_arithmetic_"+scene+"4").next()[0]).find("input[name="+type+'_arithmetic'+"]").val(); var val4 = $("#"+type+"_value_"+scene+"4").val(); var sceneName; if(scene=="outside"){ sceneName="室外"; } if(scene=="inside"){ sceneName="室内"; } //FTP和其他数据相反是由小到大所以需要判定一次数据类型 if(parseInt(ari1)==parseInt(ari2)&&parseInt(val1)==parseInt(val2)){ if(type!="ftpup"&&type!="ftpdown"){ var realTypeName=""; var temp = type.substring(0,1); if(temp=="r" && temp!="rsrp" && temp!="rsrq"){ realTypeName="R"+type.substring(1,type.length); }else if(temp=="e"){ realTypeName="Ec/No"; }else if(temp=="t"){ realTypeName="TxPower"; }else if(temp=="c"){ realTypeName="C/I"; }else if(temp=="rsrp"){ realTypeName="RSRP"; }else if(temp=="rsrq"){ realTypeName="RSRQ"; }else if(temp=="sinr"){ realTypeName="SINR"; } if(intervalJudge(typeValue1,typeValue2)){ }else{ $.messager.alert("警告",sceneName+realTypeName+"条件相同时,区间值不能同时属于两个等级","warning",function(){ moveScroll(typeId+1); addWrong(typeId+1,typeId+2); }); return false; } }else{ var realTypeName=""; if(type=="ftpup"){ realTypeName="Ftp上行"; } if(type=="ftpdown"){ realTypeName="Ftp下行"; } if(intervalJudge(typeValue2,typeValue1)){ }else{ $.messager.alert("警告",sceneName+realTypeName+"条件相同时,区间值不能同时属于两个等级","warning",function(){ moveScroll(typeId+1); addWrong(typeId+1,typeId+2); }); return false; } } } if(parseInt(ari2)==parseInt(ari4)&&parseInt(val2)==parseInt(val4)){ if(type!="ftpup"&&type!="ftpdown"){ var realTypeName=""; var temp = type.substring(0,1); if(temp=="r"){ realTypeName="R"+type.substring(1,type.length); }else if(temp=="e"){ realTypeName="Ec/No"; }else if(temp=="t"){ realTypeName="TxPower"; }else if(temp=="c"){ realTypeName="C/I"; } if(intervalJudge(typeValue2,typeValue3)){ }else{ $.messager.alert("警告",sceneName+realTypeName+"条件相同时,区间值不能同时属于两个等级","warning",function(){ moveScroll(typeId+2); addWrong(typeId+2,typeId+4); }); return false; } }else{ var realTypeName=""; if(type=="ftpup"){ realTypeName="Ftp上行"; } if(type=="ftpdown"){ realTypeName="Ftp下行"; } if(intervalJudge(typeValue3,typeValue2)){ }else{ $.messager.alert("警告",sceneName+realTypeName+"条件相同时,区间值不能同时属于两个等级","warning",function(){ moveScroll(typeId+2); addWrong(typeId+2,typeId+4); }); return false; } } } if(parseInt(ari1)==parseInt(ari4)&&parseInt(val1)==parseInt(val4)){ if(type!="ftpup"&&type!="ftpdown"){ var realTypeName=""; var temp = type.substring(0,1); if(temp=="r"){ realTypeName="R"+type.substring(1,type.length); }else if(temp=="e"){ realTypeName="Ec/No"; }else if(temp=="t"){ realTypeName="TxPower"; }else if(temp=="c"){ realTypeName="C/I"; } if(intervalJudge(typeValue1,typeValue3)){ }else{ $.messager.alert("警告",sceneName+realTypeName+"条件相同时,区间值不能同时属于两个等级","warning",function(){ moveScroll(typeId+1); addWrong(typeId+1,typeId+4); }); return false; } }else{ var realTypeName=""; if(type=="ftpup"){ realTypeName="Ftp上行"; }else if(type=="ftpdown"){ realTypeName="Ftp下行"; } if(intervalJudge(typeValue3,typeValue1)){ }else{ $.messager.alert("警告",sceneName+realTypeName+"条件相同时,区间值不能同时属于两个等级","warning",function(){ moveScroll(typeId+1); addWrong(typeId+1,typeId+4); }); return false; } } } return true; } /** *对rxlev,rxqual,ci,rscp,ecno,Txpower验证 */ function evalVerify(type,scene){ var upperScene = scene.substring(0,1).toUpperCase()+scene.substring(1,scene.length); var sceneName = null; if(scene=="outside"){ sceneName="室外"; }else if(scene=="inside"){ sceneName="室内"; } var a = document.getElementById(type+upperScene+"1").value; var b = document.getElementById(type+upperScene+"2").value; var c = document.getElementById(type+upperScene+"4").value; if(validateMyself(a)&&validateMyself(b)&&validateMyself(c)){ if(termJudge(type,scene,type+upperScene)){ }else{ return false; } }else{ $.messager.alert("警告",sceneName+type+"区间值应该从小到大","warning",function(){ if(!validateMyself(a)){ moveScroll(type+upperScene+"1"); addWrong(type+upperScene+"1",null); }else if(!validateMyself(b)){ moveScroll(type+upperScene+"2"); addWrong(type+upperScene+"2",null); }else if(!validateMyself(c)){ moveScroll(type+upperScene+"4"); addWrong(type+upperScene+"4",null); } }); return false; } return true; } /** *对ftp数据进行验证 **/ function evalftpVerify(type,direct,avg,scene){ var sceneName; if(scene=="Inside"){ sceneName="室内"; } else if(scene=="Outside"){ sceneName="室外"; } var directName; if(direct=="up"){ directName="上行"; }else if(direct=="down"){ directName="下行"; } var typeName; if(avg=="Value"){ typeName="平均速度"; var a = document.getElementById(type+direct+avg+scene+"1").value; var b = document.getElementById(type+direct+avg+scene+"2").value; var c = document.getElementById(type+direct+avg+scene+"4").value; if(validateMyself(a)&&validateMyself(b)&&validateMyself(c)){ if(termJudge(type+direct,scene.substring(0,1).toLowerCase()+scene.substring(1,scene.length),type+direct+avg+scene)){ }else{ return false; } }else{ $.messager.alert("警告",sceneName+type+directName+"占比区间值,应该从小到大","warning",function(){ if(!validateMyself(a)){ moveScroll(type+direct+avg+scene+"1"); addWrong(type+direct+avg+scene+"1",null); }else if(!validateMyself(b)){ moveScroll(type+direct+avg+scene+"2"); addWrong(type+direct+avg+scene+"2",null); }else if(!validateMyself(c)){ moveScroll(type+direct+avg+scene+"4"); addWrong(type+direct+avg+scene+"4",null); } }); return false; } } else if(avg=="Avg"){ typeName=""; var a = changeNoRight(document.getElementById(type+direct+avg+scene+"1").value); var b = changeNoRight(document.getElementById(type+direct+avg+scene+"2").value); var c = changeNoRight(document.getElementById(type+direct+avg+scene+"4").value); if(validateMyself(a)&&validateMyself(b)&&validateMyself(c)){ if(validateInterval(a,b)){ }else{ $.messager.alert("警告",sceneName+type+directName+"优级 和 良级 平均速率区间值交界应该括号类型不同,值一样","warning",function(){ moveScroll(type+direct+avg+scene+"1"); addWrong(type+direct+avg+scene+"1",type+direct+avg+scene+"2"); }); return false; } }else{ $.messager.alert("警告",sceneName+type+directName+"平均速率区间值,应该从小到大","warning",function(){ if(!validateMyself(a)){ moveScroll(type+direct+avg+scene+"1"); addWrong(type+direct+avg+scene+"1",null); }else if(!validateMyself(b)){ moveScroll(type+direct+avg+scene+"2"); addWrong(type+direct+avg+scene+"2",null); }else if(!validateMyself(c)){ moveScroll(type+direct+avg+scene+"4"); addWrong(type+direct+avg+scene+"4",null); } }); return false; } } return true; }<file_sep>/src/main/java/com/complaint/model/ColourCode.java package com.complaint.model; public class ColourCode { private int serialNum; private String colourcode; public int getSerialNum() { return serialNum; } public void setSerialNum(int serialNum) { this.serialNum = serialNum; } public String getColourcode() { return colourcode; } public void setColourcode(String colourcode) { this.colourcode = colourcode == null ? null : colourcode.trim(); } } <file_sep>/src/main/java/com/complaint/model/TrackPoint.java package com.complaint.model; /*** * 轨迹(室内外)点图 * @author Administrator * */ public class TrackPoint { //点信息 private String id; private Double x;//x轴 private Double y;//y轴 private Double lat_modi;//修正纬度 private Double lng_modi;//修正经度 private Double lat;//纬度 private Double lng;//经度 private Integer psc; private Integer bcch;//bcch,psc,pci是值,其他指标是颜色值 private Integer pci; private Integer rscp; private Integer ecno; //颜色值 private Integer txpower; private Integer ftpSpeed; private Integer ftpType; private Integer rxlev; private Integer rxqual; private Integer ci; private Integer mos; private Integer ta; //4G private Integer rsrp; private Integer rsrq; private Integer snr; private Double snr_; private Double rscp_; private Double ecno_; private Double txpower_; private Double ftpSpeed_; private Double rxlev_; private Double rxqual_; private Double ci_; private Double mos_; private Double ta_; //4G private Double rsrp_; private Double rsrq_; private Integer inside;//室内外 private String eptime; private String flowid; private Integer realnet_type; public Integer getInside() { return inside; } public void setInside(Integer inside) { this.inside = inside; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getBcch() { return bcch; } public void setBcch(Integer bcch) { this.bcch = bcch; } public Integer getRscp() { return rscp; } public void setRscp(Integer rscp) { this.rscp = rscp; } public Integer getEcno() { return ecno; } public void setEcno(Integer ecno) { this.ecno = ecno; } public Integer getTxpower() { return txpower; } public void setTxpower(Integer txpower) { this.txpower = txpower; } public Integer getFtpSpeed() { return ftpSpeed; } public void setFtpSpeed(Integer ftpSpeed) { this.ftpSpeed = ftpSpeed; } public Integer getRxlev() { return rxlev; } public void setRxlev(Integer rxlev) { this.rxlev = rxlev; } public Integer getRxqual() { return rxqual; } public void setRxqual(Integer rxqual) { this.rxqual = rxqual; } public Integer getCi() { return ci; } public void setCi(Integer ci) { this.ci = ci; } public Integer getMos() { return mos; } public void setMos(Integer mos) { this.mos = mos; } public Double getX() { return x; } public void setX(Double x) { this.x = x; } public Double getY() { return y; } public void setY(Double y) { this.y = y; } public Integer getTa() { return ta; } public void setTa(Integer ta) { this.ta = ta; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } public Double getLng() { return lng; } public void setLng(Double lng) { this.lng = lng; } public Integer getPsc() { return psc; } public void setPsc(Integer psc) { this.psc = psc; } public Double getLat_modi() { return lat_modi; } public void setLat_modi(Double lat_modi) { this.lat_modi = lat_modi; } public Double getLng_modi() { return lng_modi; } public void setLng_modi(Double lng_modi) { this.lng_modi = lng_modi; } public String getEptime() { return eptime; } public void setEptime(String eptime) { this.eptime = eptime; } public String getFlowid() { return flowid; } public void setFlowid(String flowid) { this.flowid = flowid; } public Double getRscp_() { return rscp_; } public void setRscp_(Double rscp_) { this.rscp_ = rscp_; } public Double getEcno_() { return ecno_; } public void setEcno_(Double ecno_) { this.ecno_ = ecno_; } public Double getTxpower_() { return txpower_; } public void setTxpower_(Double txpower_) { this.txpower_ = txpower_; } public Double getFtpSpeed_() { return ftpSpeed_; } public void setFtpSpeed_(Double ftpSpeed_) { this.ftpSpeed_ = ftpSpeed_; } public Double getRxlev_() { return rxlev_; } public void setRxlev_(Double rxlev_) { this.rxlev_ = rxlev_; } public Double getRxqual_() { return rxqual_; } public void setRxqual_(Double rxqual_) { this.rxqual_ = rxqual_; } public Double getCi_() { return ci_; } public void setCi_(Double ci_) { this.ci_ = ci_; } public Double getMos_() { return mos_; } public void setMos_(Double mos_) { this.mos_ = mos_; } public Integer getFtpType() { return ftpType; } public void setFtpType(Integer ftpType) { this.ftpType = ftpType; } public Double getTa_() { return ta_; } public void setTa_(Double ta_) { this.ta_ = ta_; } public Integer getRealnet_type() { return realnet_type; } public void setRealnet_type(Integer realnet_type) { this.realnet_type = realnet_type; } public Integer getPci() { return pci; } public void setPci(Integer pci) { this.pci = pci; } public Integer getRsrp() { return rsrp; } public void setRsrp(Integer rsrp) { this.rsrp = rsrp; } public Integer getRsrq() { return rsrq; } public void setRsrq(Integer rsrq) { this.rsrq = rsrq; } public Integer getSnr() { return snr; } public void setSnr(Integer snr) { this.snr = snr; } public Double getSnr_() { return snr_; } public void setSnr_(Double snr_) { this.snr_ = snr_; } public Double getRsrp_() { return rsrp_; } public void setRsrp_(Double rsrp_) { this.rsrp_ = rsrp_; } public Double getRsrq_() { return rsrq_; } public void setRsrq_(Double rsrq_) { this.rsrq_ = rsrq_; } } <file_sep>/src/main/java/com/complaint/model/GroupManager.java package com.complaint.model; import java.util.List; public class GroupManager { private Integer group_big_id;//大组id private String group_big_name;//大组名称 private Integer group_small_id;//小组id private String group_small_name;//小组名称 private String manager_name;//小组人员名称 private String area_name;//区域人员名称 private Double score;//得分 public Integer getGroup_big_id() { return group_big_id; } public void setGroup_big_id(Integer group_big_id) { this.group_big_id = group_big_id; } public String getGroup_big_name() { return group_big_name; } public void setGroup_big_name(String group_big_name) { this.group_big_name = group_big_name; } public Integer getGroup_small_id() { return group_small_id; } public void setGroup_small_id(Integer group_small_id) { this.group_small_id = group_small_id; } public String getGroup_small_name() { return group_small_name; } public void setGroup_small_name(String group_small_name) { this.group_small_name = group_small_name; } public String getManager_name() { return manager_name; } public void setManager_name(String manager_name) { this.manager_name = manager_name; } public String getArea_name() { return area_name; } public void setArea_name(String area_name) { this.area_name = area_name; } public Double getScore() { return score; } public void setScore(Double score) { this.score = score; } } <file_sep>/src/main/webapp/js/reportconfig/qualityconfig.js $(function(){ window.onresize(); var oknum = 0; $('#ok').click(function(){ if(oknum == 0){ oknum ++; var _input = $('input'); var flag = false; var count = 0; for(var i = 0;i<_input.length;i++){ var _val = $(_input[i]).val(); if(!/^(-?\d+)(\.\d{1,2})?$/i.test(_val) || parseFloat(_val) > 100){ $(_input[i]).css('background-color','red'); if(count == 0){ flag = true; var _t = $(_input[i]).offset().left; var _div = $('#right').offset().left; var _left = _t - _div; if(_left > $('#right').width() - 90){ $('#right').scrollLeft(_t - _div); } //$(_input[i]).focus(); count++; oknum = 0; } } } var tscroe = $("input[name='tscroe']").val(); var stepc = $("input[name='stepc']").val(); if(!flag){ if(tscroe>=stepc){ var vals = new Array(); //基本数据 $('.khbb-cs-other').find("input").each(function(){ var obj = {}; obj['id'] = $(this).attr('operid'); obj['val'] = $(this).val(); obj['type'] = 2; vals.push(obj); }); //均值比较分步长 $("#svg_step").find("ul > li > input").each(function(){ var _this = $(this); var obj = {}; var _name = _this.attr("name"); obj['id'] = _this.attr('operid'); obj['svg_step'] = _this.val(); //根据 obj['annular_step'] = $("#annular_step").find("input[name='"+_name+"']").val(); obj['groupid'] = _name.split('_')[2]; obj['kpi'] = _name.split('_')[1]; obj['type'] = 1; vals.push(obj); }); $.ajax({ type:'post', url:contextPath + '/reportconfig/updatestep', data:{groups : JSON.stringify(vals)}, success:function(data){ if(data.msg == 1){ $.messager.alert('提示','操作成功!','success'); }else{ $.messager.alert('提示','操作失败!','error'); } oknum = 0; } }); }else{ $.messager.alert('提示','考核步长应该小于等于考核总分',"warning"); oknum = 0; } } } }); $('input').bind('focus blur',function(e) { if(e.type == 'focus'){ $(this).css('background-color',''); }else{ var _val = $(this).val(); if(!/^(-?\d+)(\.\d{1,2})?$/i.test(_val) || parseFloat(_val) > 100){ $(this).css('background-color','red'); } } }); }); window.onresize = function() { var scWidth = document.body.scrollWidth; var rightWidth = scWidth * 0.98 * 0.98 - 2 - 170 - 10 - 2; var _this = $("#right"); var _right = _this.attr("val") *90 * 2 + 5 - 1; if(rightWidth > _right){ _this.css("width", _right); }else{ _this.css("width", rightWidth); } // list?size*90*2 + list?size * 2 - 1 }<file_sep>/src/main/webapp/js/gisgrad/gisgrad.js /** * 地图评价相关JS */ var flashHeight; var DEFAULTMAPZOOM = 14; // default map zoom var geocoder = null; // address parse var searnum = 0; $(function() { $("#wlf_query").hide(); $("#background").hide(); $("#bar_id").hide(); var len =document.body.scrollWidth*0.5; $("#div_map").css("height",len); initeArea(); initeScence(); initeTestType(); initeTestnets(); map=initeMap(); window._map = map; var markerlist=[]; $("#show_flash").live('click',function(){ $("#hiquery").show(); $("#diatype").val("hi"); //隐藏柱状图 try{ $('#flash').window('close'); }catch(e){ } //打开查询条件 $("#cond").dialog({ href: contextPath + '/gisgrad/graphlist?inside='+grap_.inside+'&grad='+grap_.grad+'&startTime='+grap_.startTime+ '&endTime='+grap_.endTime+'&areaids='+grap_.areaids+'&areatext='+encodeURIComponent(grap_.areatext)+'&senceids='+grap_.senceids+ '&senctext='+encodeURIComponent(grap_.senctext)+'&testtype='+grap_.testtype+'&testtypeText='+encodeURIComponent(grap_.testtypeText)+'&nettype='+grap_.nettype+ '&datatype='+grap_.datatype+'&jobtype='+grap_.jobtype+'&kpi='+grap_.kpi+'&sernos='+grap_.sernos+'&testnet='+grap_.testnet+ '&testnetName='+encodeURIComponent(grap_.testnetName)+'&openType='+1, height: 400,width: 708,title: "柱状图查询", modal: true,closed:false }); $('#cond').dialog('open'); }); //页面第一次查询事件 $("#serch").die().live("click",function(e) { if($("#sernos").validatebox("isValid")==false){ $.messager.alert("提示","输入超出长度!","warning"); return false; } for(var j=0;j<markerlist.length;j++){ var marker=markerlist[j]; marker.setMap(null); } markerlist=[]; markerlist=queryData(map,1); }); $("#queryscend").die().live("click",function(e) { if($("#secendSerno").validatebox("isValid")==false){ $.messager.alert("提示","输入超出长度!","warning"); return false; } //页面上有数据时才能进行二次查询 if(markerlist.length>0&&$("#secendSerno").val().length>0){ for(var j=0;j<markerlist.length;j++){ var marker=markerlist[j]; marker.setMap(null); } markerlist=[]; markerlist=queryData(map,2); } }); //二次查询菜单 var ff=false; $("#samp_id").die().live("click",function(e) { if(ff==false){ //$("#samp_id").css({'background-image':'url(../images/map_deploy.png)'}); $(".map_two_search").toggle(); $(".map_two").css('width','48px'); $(".gis-mapgj ").css("top",'60px'); ff=true; }else{ //$("#samp_id").css({'background-image':'url(../images/map_stop.png)'}); $(".map_two_search").toggle(); $(".map_two").css('width','434px'); $(".gis-mapgj ").css("top",'20px'); ff=false; } }); //全屏事件 $("#quan_ping").die().live("click",function(e) { $(".mainmenu").toggle(); if($(".right").css("margin-top")=='100px'){ $(".right").css("margin-top","0px").css("padding-top","0px"); $("#quan_ping").html('<span class="gis_screen"></span>退出全屏'); } else { $(".right").css("margin-top","100px").css("padding-top","0px"); $("#quan_ping").html('<span class="gis_screen"></span>全屏'); } }); //查询条件事件 $("#query_id").die().live("click",function(e) { $("#wlf_query").toggle(); }); //小区信息事件 $("#c_info_li").live('mouseover',function(e){ $("#gis_cell_loading").show(); }); $("#c_info_li").live('mouseout',function(e){ $("#gis_cell_loading").hide(); }); //标注信息事件 $(".show_li").live('mouseover',function(e){ $(this).find("div").first().show(); }); $(".show_li").live('mouseout',function(e){ $(this).find("div").first().hide(); }); //领区事件 $("#showlinqu").live('mouseover',function(e){ $("#linqu_ul").show(); }); $("#showlinqu").live('mouseout',function(e){ $("#linqu_ul").hide(); }); //导出事件 $("#exports").live('mouseover',function(e){ if(stationInitData.length == 0){ $("#export_near").css('color','#CDCDCD'); } $("#gis_exports").show(); }); $("#exports").live('mouseout',function(e){ $("#gis_exports").hide(); }); //数据导出点击事件 $("#export_data").die().live("click",function(e) { if(searnum==1){ var obj=getPram(1); download_(obj); }else if(searnum==0){ $("#hiquery").show(); $("#diatype").val("dl"); //打开查询条件 $("#cond").dialog({ href: contextPath + '/gisgrad/graphlist?inside='+grap_s.inside+'&grad='+grap_s.grad+'&startTime='+grap_s.startTime+ '&endTime='+grap_s.endTime+'&areaids='+grap_s.areaids+'&areatext='+encodeURIComponent(grap_s.areatext)+'&senceids='+grap_s.senceids+ '&senctext='+encodeURIComponent(grap_s.senctext)+'&testtype='+grap_s.testtype+'&testtypeText='+encodeURIComponent(grap_s.testtypeText)+'&nettype='+grap_s.nettype+ '&datatype='+grap_s.datatype+'&jobtype='+grap_s.jobtype+'&kpi='+grap_s.kpi+'&sernos='+grap_s.sernos+'&testnet='+grap_s.testnet+ '&testnetName='+encodeURIComponent(grap_s.testnetName)+'&openType='+2, height: 400,width: 705,title: "评价导出", modal: true,closed:false }); $('#cond').dialog('open'); } }); //点击小区导出 $("#export_cell").die().live('click',function(e){ var ids = ''; var nettype = '0,1'; var indoor = '0,1'; var cellBands = '900,1800'; $("#celldlg").dialog({ href: contextPath + '/gisgrad/searchCell?type=1&areas=' + ids +'&indoor=' + indoor + '&modetypes=' + nettype + '&cellBands=' + cellBands, height: 400,width: 705,title: "小区导出", modal: true,closed:false }); $('#celldlg').dialog('open'); $.parser.parse('#celldlg'); $(".sel_cell > span > span").html("导出"); }); /** * 标注与领区选择事件 */ $(".isgou").die().live("click",function(e) { if($(this).find("span").length>0){ $(this).find("span").remove(); }else{ $(this).prepend("<span></span>"); } if($(this).attr("name")=="psc"&&span_map_psc.length>0) isShowPsc(); if($(this).attr("name")=="g3_name"&&p_map_jizhan.length>0) isShowJizhan(); if($(this).attr("name")=="bcch"&&span_map_psc.length>0) isShowPsc(); if($(this).attr("name")=="g2_name"&&p_map_jizhan.length>0) isShowJizhan(); }); $("#cell_gsm").die().live("click",function(){ if($(this).is(':checked')){ $("#cell_bands").find("input").each(function(i){ $(this).attr('checked','checked'); }); $("#cell_bands").show(); }else{ $("#cell_bands").find("input").each(function(i){ $(this).removeAttr('checked'); }); $("#cell_bands").hide(); } }); //点击邻区导出 $("#export_near").die().live("click",function(){ if(stationInitData.length > 0){ $(".gis-exporta").each(function(){ $(this).show(); }); $('#nearcelldlg').dialog('open'); $.parser.parse('#nearcelldlg'); $("#near_type").find("input").each(function(){ $(this).attr('checked','checked'); }); $("#report_cell_type").combobox({ valueField: 'val', textField: 'text', data: [{ "val":3, "text":"加载小区", "selected":true },{ "val":2, "text":"点击小区" }] }); } }); $(".sel_nearcell").die().live("click",function(){ var cellrel = ""; $("#near_type").find("input:checked:checked").each(function(){ cellrel += $(this).attr("value") +","; }); if(cellrel != "" && cellrel.length > 0){ cellrel = cellrel.substr(0 , cellrel.length - 1); var lac_cid = clicktrunk.substr(clicktrunk.indexOf("_")+1,clicktrunk.length); var report_cell_type = $("#report_cell_type").combobox("getValue"); if((report_cell_type == 2 && clicktrunk != "") || report_cell_type == 3){ var ids = $("#stationareaids").val(); var nettype = $("#cellnettype").val(); var indoor = $("#cellindoor").val(); var cellBands = $("#cellcellbands").val(); location.href = contextPath+'/gisgrad/downloadcellinfo?report_type='+report_cell_type+'&lac_cid='+lac_cid+'&cellrel='+cellrel+'&areas=' + ids +'&indoor=' + indoor + '&modetypes=' + nettype + '&cellBands=' + cellBands; }else{ $.messager.alert("提示","请点击小区后再选择点击小区导出!","warning"); return; } }else{ $.messager.alert("提示","请选择邻区关系!","warning"); return; } $('#nearcelldlg').dialog('close'); }); //小区加载 $("#station").die().live('click',function(e){ var ids = $("#stationareaids").val(); var nettype = $("#cellnettype").val(); var indoor = $("#cellindoor").val(); var cellBands = $("#cellcellbands").val(); $("#celldlg").dialog({ href: contextPath + '/gisgrad/searchCell?type=0&areas=' + ids +'&indoor=' + indoor + '&modetypes=' + nettype + '&cellBands=' + cellBands, height: 380,width: 705,title: "小区加载条件", modal: true,closed:false }); $('#celldlg').dialog('open'); $.parser.parse('#celldlg'); }); //查询小区 /小区导出 $(".sel_cell").die().live("click",function(e){ var type = $("#cell_btn_type").val(); var indoor = ""; var nettype = ""; var cellBands = ""; var areaids = ""; //室内/外 $("#cell_indoor").find("input:checkbox:checked").each(function(i){ indoor += $(this).attr('value') + ','; }); if(indoor != "" && indoor.length > 0){ indoor = indoor.substr(0 , indoor.length - 1); }else{ $.messager.alert("提示","请选择室内/外!","warning"); return; } //网路类型 $("#cell_nettype").find("input:checkbox:checked").each(function(i){ nettype += $(this).attr('value') + ','; }); if(nettype != "" && nettype.length > 0){ nettype = nettype.substr(0 , nettype.length - 1); }else{ $.messager.alert("提示","请选择网路类型!","warning"); return; } //频段 $("#cell_bands").find("input:checkbox:checked").each(function(i){ cellBands += $(this).attr('value') + ','; }); if(cellBands != "" && cellBands.length > 0){ cellBands = cellBands.substr(0 , cellBands.length - 1); } //区域 $("#cell_areas").find("input:checkbox:checked").each(function(i){ areaids += $(this).attr('value') + ','; }); if(areaids != "" && areaids.length > 0){ areaids = areaids.substr(0 , areaids.length - 1); }else{ $.messager.alert("提示","请选择区域!!","warning"); return; } //0 加载小区 1小区导出 if(type == 0){ if($("#cell_areas").find("input:checkbox:checked").length > 3){ $.messager.alert("提示","加载小区信息,不能超过三个区域!","warning"); return; } if(areaids != "" && areaids.length > 0){ removeStationMap(); changeCells = []; stationInitData = []; span_map_psc=[]; p_map_jizhan=[]; cacheCells = []; click_cell = ""; clicktrunk = ""; $("#stationareaids").val(areaids); $("#cellnettype").val(nettype); $("#cellindoor").val(indoor); $("#cellcellbands").val(cellBands); } $("#background").show(); $("#bar_id").show(); $.ajax({ type : 'get', url : contextPath + '/gisgrad/showCell', data : { areas : areaids, indoor : indoor, modetypes : nettype, cellBands : cellBands }, success : function(data) { if(data) is_showcell =true; var positionList = data.position; _map.positionList = positionList; if(positionList&&!list_marker){ var item = positionList[0]; map.setZoom(16); map.setCenter(new google.maps.LatLng(item.longitude,item.latitude)); } //清空小区信息 if(_infowindow) _infowindow.close(); //画小区 if(map.getZoom()>=DEFAULTMAPZOOM){ stationInitData = data.data; var inMapData = getBoundsStation(map); for (var j = 0; j < inMapData.length; j++) { drawStation(inMapData[j].bsList, map); } } $("#export_near").css('color',''); $("#background").hide(); $("#bar_id").hide(); } }); }else{ var areaids = ""; if($("#cell_area_all").is(":checked")){ areaids = "-1,"; }else{ $("#cell_areas").find("input:checkbox:checked").each(function(i){ areaids += $(this).attr('value') + ','; }); } if(areaids != "" && areaids.length > 0){ areaids = areaids.substr(0 , areaids.length - 1); location.href = contextPath+'/gisgrad/downloadcellinfo?report_type=1&areas=' + areaids +'&indoor=' + indoor + '&modetypes=' + nettype + '&cellBands=' + cellBands; }else{ $.messager.alert("提示","请选择小区!","warning"); return; } } $('#celldlg').dialog('close'); }); $("#cell_area_all").die().live("click",function(){ if($(this).is(":checked")){ $("#cell_areas").find("input:checkbox").each(function(i){ $(this).attr("checked","checked"); }); }else{ $("#cell_areas").find("input:checkbox").each(function(i){ $(this).removeAttr('checked'); }); } }); }); var queryContition;//页面查询条件 var is_showcell=false;//默认小区未加载 function getPram(isfirst){ if(isfirst==1){ var obj=new Object(); obj.inside = $("#ii").combobox('getValue'); obj.grad = $("#gg").combobox('getValue'); obj.startTime = $("#startTime").val(); obj.endTime = $("#endTime").val(); obj.areaids = $("#areaids").val(); obj.senceids = $("#senceids").val(); obj.testtype = $("#testtype").val(); obj.scendvalue=$("#secendSerno").val(); obj.nettype=$("#nettype").combobox('getValue'); obj.datatype=$("#datatype").combobox('getValue'); obj.jobtype=$("#jj").combobox('getValue'); obj.kpi=$("#kk").combobox('getValue'); obj.sernos=$("#sernos").val(); obj.testnet = $("#testnet").val(); if (obj.startTime != "" && obj.startTime != null && obj.endTime != "" && obj.endTime != null) { var arr1 = obj.startTime.split("/"); var startDate = new Date(arr1[0],parseInt(arr1[1])-1,arr1[2]); var arr2 = obj.endTime.split("/"); var endDate = new Date(arr2[0],parseInt(arr2[1])-1,arr2[2]); if(startDate > endDate){ $.messager.alert("提示","开始时间应小于结束时间!","warning"); return false; } }else{ $.messager.alert("提示","时间不能为空!","warning"); return false; } queryContition=obj; }else if(isfirst==3){//没查询过,点击柱状图和评价导出获取条件 var obj=new Object(); obj.inside = $("#ii_").combobox('getValue'); obj.grad = $("#gg_").combobox('getValue'); obj.startTime = $("#startTime_").val(); obj.endTime = $("#endTime_").val(); obj.areaids = $("#areaids_").val(); obj.senceids = $("#senceids_").val(); obj.testtype = $("#testtype_").val(); obj.scendvalue=""; obj.nettype=$("#nettype_").combobox('getValue'); obj.datatype=$("#datatype_").combobox('getValue'); obj.jobtype=$("#jj_").combobox('getValue'); obj.kpi=$("#kk_").combobox('getValue'); obj.sernos=$("#sernos_").val(); obj.testnet = $("#testnet_").val(); if (obj.startTime != "" && obj.startTime != null && obj.endTime != "" && obj.endTime != null) { var arr1 = obj.startTime.split("/"); var startDate = new Date(arr1[0],parseInt(arr1[1])-1,arr1[2]); var arr2 = obj.endTime.split("/"); var endDate = new Date(arr2[0],parseInt(arr2[1])-1,arr2[2]); if(startDate > endDate){ $.messager.alert("提示","开始时间应小于结束时间!","warning"); return false; } }else{ $.messager.alert("提示","时间不能为空!","warning"); return false; } queryContition=obj; }else{ queryContition.scendvalue=$("#secendSerno").val(); } return queryContition; } //根据条件查询数据 //聚合变量 var list_marker; var markerCluster; function queryData(map,isfirst){ searnum=1;//查询过一次,点评价导出,导出当前的信息 polyline.setMap(null); markerLatLng_bit=null; if(markerCluster){ markerCluster.clearMarkers(); } var markerlist=[]; var obj=getPram(isfirst); regionCondition = obj;//获取框选条件 $("#background").show(); $("#bar_id").show(); $.post(contextPath + "/gisgrad/gisgrad", {areaids:obj.areaids, inside:obj.inside, grad:obj.grad, isFirst:isfirst, secendSerno:obj.scendvalue, startTime:obj.startTime, endTime:obj.endTime, sernos:obj.sernos, senceids:obj.senceids, testtype:obj.testtype, nettype:obj.nettype, datatype:obj.datatype, jobtype:obj.jobtype, kpi:obj.kpi, testnet:obj.testnet, colorversion:colorversion }, function(data){ //若图例开启,隐藏图例 if(data.list.length<=0){ $(".case_tu").css("background",""); $(".case_tu").css("border-bottom", ""); $(".case_tu").css("border-right", ""); $("#demo_div").html(""); $(".gis_nav span").css({'background-image':'url(../images/gis_images.png)'}); $("#img_demo span").removeAttr("class").addClass("gis_chart"); //隐藏柱状图 try{ $('#flash').window('close'); }catch(e){ } } list_marker=data.list; $("#caiyang").html("采样点:"+list_marker.length); var colorlist=data.color; var count=data.count; var center=data.center; var flay=false; isColorChange = data.ischange; //图例点击事件 $('#img_demo').die().live("click",function(e) { flay=getDemo(list_marker,flay,count,colorlist,obj.grad,obj.kpi); }); if($("#demo_div").html()){flay=getDemo(list_marker,flay,count,colorlist,obj.grad,obj.kpi);} for(var i=0;i<list_marker.length;i++){ var li=list_marker[i]; var marker= addMarker(li,map,colorlist,obj.nettype,i); markerlist.push(marker); } markerCluster = new MarkerClusterer(map, markerlist,{ maxZoom: DEFAULTMAPZOOM-1, averageCenter: true }); if(list_marker.length>0&&count.length>0){ if(is_showcell==false){ setMapCenter(map,center); } } if(list_marker.length>0&&count.length>0){ //柱状图显示事件 $("#show_flash").show(); $("#show_flash").die().live("click",function(e) { initeFlash(); }); var wid_len=(document.body.scrollWidth-document.body.scrollWidth*0.05)/2; $("#flash").append("<div class='histogram_flash' id='div_state' style='width:"+wid_len+"px;margin:0 auto;position: relative;'></div>"); creatFlash('div_state',count,colorlist,obj.grad,obj.kpi); flashHeight = $("#flash").css("height"); }else{ $("#flash").html(""); $("#show_flash").hide(); } $("#background").hide(); $("#bar_id").hide(); }); return markerlist; } //初始化地图 function initeMap(){ var myOptions_dt = { zoom :14, center :new google.maps.LatLng(29.5,106.5) , mapTypeId : google.maps.MapTypeId.ROADMAP, mapTypeControl : true, streetViewControl : false, mapTypeControl:false, // mapTypeControlOptions : { // style : google.maps.MapTypeControlStyle.HORIZONTAL_BAR, // position : google.maps.ControlPosition.BOTTOM // }, panControl : true, panControlOptions : { position : google.maps.ControlPosition.RIGHT_BOTTOM }, zoomControl : true, zoomControlOptions : { position : google.maps.ControlPosition.RIGHT_BOTTOM } }; // 生成地图 var map = new google.maps.Map(document.getElementById("div_map"), myOptions_dt); geocoder = new google.maps.Geocoder(); //申明地址解析对象 //比例改变事件 google.maps.event.addListener(map, 'zoom_changed', function(re) { //重画连线 if(cells&&cells.length>0&&markerLatLng_bit){ polyline.setPath(countLatLng(cells,markerLatLng_bit)); polyline.setMap(map); } }); google.maps.event.addListener(map, 'zoom_changed', function(re) { if(map.getZoom()>=DEFAULTMAPZOOM){ //setTimeout(function(){ changeBound(map); //},1000); }else{ removeStationMap(); //取消小区弹出消息 if(_infowindow) _infowindow.close(); } }); google.maps.event.addListener(map, 'dragend', function(re) { if(map.getZoom()>=DEFAULTMAPZOOM){ changeBound(map); }else{ removeStationMap(); //取消小区弹出消息 if(_infowindow) _infowindow.close(); } }); google.maps.event.addListener(map, 'rightclick', function(event) { if(map.getZoom()>=DEFAULTMAPZOOM && stationInitData && stationInitData.length>0){ var currentLatLng = event.latLng; //var newPos = new google.maps.LatLng(mk.position.lat(),mk.position.lng()); geocoder.geocode({location:currentLatLng},function(results,status){ if(status == google.maps.GeocoderStatus.OK){ if(results[0]){ var address = results[0].formatted_address; showRightMenu(event.pixel.x, event.pixel.y,currentLatLng,address); } } }); } }); chooseMap(map); return map; } /** * setAreaCenter * @param _this */ function setAreaCenter(_this){ var latLngList,address,lat,lng,i,ids=[]; var latLng = $(_this).attr("latLng"); var nodes = $('#cell_areas').find("input:checkbox:checked"); latLngList = latLng.split(","); address = $(_this).attr("address"); lat = latLngList[0]; lng = latLngList[1]; if(nodes && nodes.length>0){ for(i = 0,len=nodes.length; i < len; i++){ ids.push($(nodes[i]).val()); } $.ajax({ type:"POST", url:contextPath + '/gisgrad/setAreaCenter', data:{areaids:ids.join(","),lat:lat,lng:lng,address:address}, error:function(){ $.messager.alert("提示","设置失败!","ok"); }, success:function(data){ $.messager.alert("提示","设置成功!","ok"); } }); } } /** * 显示右键菜单 * @param x * @param y */ function showRightMenu(x,y,latLng,address){ var rightMenu = $("#rightMenu"); var centerItme = $("#centerItme"); var rightMenu_cancel = $("#rightMenu_cancel"); if(rightMenu.find("div.area_item")){ rightMenu.find("div.area_item").remove(); } addShortcutArea(rightMenu_cancel,rightMenu); centerItme.attr("latLng",latLng.lat()+","+latLng.lng()).attr("address",address); rightMenu.menu('show', { left: x, top: y+rightMenu.height() }); $.parser.parse(rightMenu); } /** * current area shortcut menu * @param rightMenu_cancel * @param rightMenu */ function addShortcutArea(rightMenu_cancel,rightMenu){ var nodes = $('#cell_areas').find("input:checkbox:checked"); var currentArea = rightMenu.attr("currentArea"); var len = nodes.length; len = len>3 ? 3 : len; for(var i=0; i<len; i++){ var node = $(nodes[i]); var item = rightMenu_cancel.clone(true); var div = item.find("div"); item.attr("areaid",node.val()); div.html(node.parent().text()); item.removeAttr("id"); item.addClass("area_item"); if(currentArea == node.val()){ div .before("<span style='background:url(../images/gis_images.png) no-repeat;background-position:-141px -2px; width:16px; height:18px; display:block; float:left; margin:4px 6px 0 0;'></span>") .css({"marginLeft":"-22px"}); } item.bind({ click:function(){ var areaid = $(this).attr("areaid"); rightMenu.attr("currentArea",areaid); changeMapZoom(areaid); }, mouseover:function(){ rightMenu.find("div.menu-active").removeClass("menu-active"); $(this).addClass("menu-active"); }, mouseout:function(){ $(this).removeClass("menu-active"); } }); rightMenu_cancel.before(item); } } /** * shortcut menu item change for area * @param _this */ function changeMapZoom(areaid){ if(_map && _map.positionList){ for(var i=0,len=_map.positionList.length; i<len; i++){ var item = _map.positionList[i]; if(areaid == item.areaid){ //清空小区信息 removeStationMap(); _map.setCenter(new google.maps.LatLng(item.longitude,item.latitude)); var inMapData = getBoundsStation(_map); if(_map.getZoom()>=DEFAULTMAPZOOM){ for (var j = 0; j < inMapData.length; j++) { drawStation(inMapData[j].bsList, _map); } } break; } } } } /** * 地图放大拖动事件 * @param map */ function changeBound(map){ //获取当前屏幕最大最小经纬度 var latLngBounds = map.getBounds(); var latLngNE = latLngBounds.getNorthEast(); var latLngSW = latLngBounds.getSouthWest(); var latNE = latLngNE.lat(); var lngNE = latLngNE.lng(); var latSW = latLngSW.lat(); var lngSW = latLngSW.lng(); //循环判断在地图上的小区信息是否在当前屏幕,不在则删除 // if(_infowindow&&_infowindow.getContent()){ // if(_infowindow.getPosition().lat() <= latSW || // _infowindow.getPosition().lng() <= lngSW || // _infowindow.getPosition().lat() >= latNE || // _infowindow.getPosition().lng() >= lngNE){ // _infowindow.close(); // } // } for(var i = 0; i < stationMap.length; i++){ var lat = stationMap[i].latLng_.lat(),lng = stationMap[i].latLng_.lng(); if(lat <= latSW || lng <= lngSW || lat >= latNE || lng >= lngNE){ if(stationMap[i].isdelet_<1){ //删除小区信息 stationMap[i].setMap(null); stationMap.splice(i, 1); span_map_psc.splice(i, 1); } } } var bslist = null; //在可视范围的基站数据 var inMapData = getBoundsStation(map); for(var i = 0;i < inMapData.length; i++){ bslist = inMapData[i].bsList; //是否需要画小区 var flag = false; for(var j = 0; j < bslist.length; j++){ var img_ ="#img_"+bslist[j].lac+"_"+bslist[j].cellId; var del = false; for(var k = 0; k < changeCells.length; k++){ //判断小区是否在邻区数组中 if(img_ == changeCells[k].img_id){ //保存该小区图片前缀 bslist[j].fix = changeCells[k].fix; del = true; break; }else{ if(typeof(bslist[j].fix)!='undefined'){ bslist[j].fix=undefined; } } } //判断当前小区是否在地图上 if($(img_).length == 0){ flag = true; del = false; }else{ //删除叠加层 if(del){ $(img_).parent().remove(); flag = true; } } } if(flag){ //画小区 drawStation(bslist,map); } } } //地图上增加点与点击事件 /** * li:对象 */ var cells=null;//点击点连接的小区 var markerLatLng_bit=null;//点击的marker var isColorChange = 0;//阈值颜色是否更新 var polyline=new google.maps.Polyline({ strokeColor: "#898ce7", strokeOpacity: 1.0, strokeWeight: 2}); function addMarker(li,map,colorlist,nettype,index){ var position = new google.maps.LatLng(li.lat_m,li.lng_m); var n=""; if(li.net==1){n='g';} if(li.net==2){n='w';} if(li.net==3){n='w';} if(li.net==4){n='g';} if(li.isf&&li.isf==2){n='s';} if(li.color=='优')li.aa=1; if(li.color=='良')li.aa=2; if(li.color=='中')li.aa=3; if(li.color=='差')li.aa=4; var infowindow = null; var icon = isColorChange==1 ? contextPath+'/images/integration/'+n+'_'+li.aa+'.png'+"?t="+new Date().getTime() : contextPath+'/images/integration/'+n+'_'+li.aa+'.png'+""; var marker=new google.maps.Marker({ position :position, icon:icon, map : map, zIndex:index }); //点击事件 google.maps.event.addListener(marker, 'click', function(){ if (infowindow) { infowindow.close(); infowindow = null; }else{ var le= checkKpi(li,colorlist); var content=""; content+='<div class="map_tankuang" id="info_'+index+'">'; content+='<div style="font-weight: bold; padding-left: 10px;">'+li.ser+'</div>'; content+='<h1>'+li.title+'('+li.inside+')</h1><span style="background:'+li.cc+'">'+li.realgrad+'</span>'; content+='<div class="clear"></div>'; content+='<p>测试地址:'+li.add+'<br />'; content+=le.kpitext; content+='</p></div>'; infowindow = new google.maps.InfoWindow({ content:content, disableAutoPan:false }); infowindow.open(map, marker); infowindow.setZIndex(997); //气泡关闭事件 google.maps.event.addListener(infowindow, 'closeclick', function(){ infowindow = null; }); } // 判断小区是否显示 if(is_showcell==true){ polyine_cell(li,map); } //点击连接关联小区 }); return marker; } //点击流水连线小区,如果没有在地图区域内生成重新生成 function polyine_cell(li,map){ $.post(contextPath + "/gisgrad/giscell", {flowid:li.flowid}, function(data){ cells=data.cell; //不在区域内的小区 var cell_qita=[]; for(var j=0;j<cells.length;j++){ var cc=cells[j]; /*var obj=$("#img_"+cc.lac+"_"+cc.cellId); if(obj.length==0){ cc.isclick=1; cc.isdelet=1; cell_qita.push(cc); }*/ var flag = true; var bslist = null; var lac,cid; var sd= stationInitData; var bid; for(var i = 0;i < sd.length; i++){ bslist = sd[i].bsList; bid = sd[i].bid; if(cc.bid===bid){ for(var j = 0; j < bslist.length; j++){ lac = bslist[j].lac; cid = bslist[j].cellId; if(lac == cc.lac && cid == cc.cellId){ flag = false; } } } } if(flag){ cc.isclick=1; cc.isdelet=1; cell_qita.push(cc); } } if(cell_qita.length>0){ groupBybid(cell_qita,map); } setTimeout(function(){ //连线 markerLatLng_bit=new google.maps.LatLng(li.lat_m+0.000003,li.lng_m); polyline.setPath(countLatLng(cells,markerLatLng_bit)); polyline.setMap(map); },200); }); } /*** * 检查对象各测试指标 * @param li */ function checkKpi(li,colorlist){ var kpitext="指标评价:"; kpitext+=li.rscp==null?"":"RSCP:"+li.rscp+"&nbsp;&nbsp;&nbsp;&nbsp"; kpitext+=li.ecno==null?"":"Ec/No:"+li.ecno+"&nbsp;&nbsp;&nbsp;&nbsp"; kpitext+=li.tx==null?"":"TXPOWER:"+li.tx+"&nbsp;&nbsp;&nbsp;&nbsp"; kpitext+=li.fu==null?"":"FTP上行:"+li.fu+"&nbsp;&nbsp;&nbsp;&nbsp"; kpitext+=li.fd==null?"":"FTP下行:"+li.fd+"&nbsp;&nbsp;&nbsp;&nbsp"; kpitext+=li.rx==null?"":"Rxlev:"+li.rx+"&nbsp;&nbsp;&nbsp;&nbsp"; kpitext+=li.rq==null?"":"Rxqual:"+li.rq+"&nbsp;&nbsp;&nbsp;&nbsp"; kpitext+=li.ci==null?"":"C/I:"+li.ci+"&nbsp;&nbsp;&nbsp;&nbsp"; li.kpitext=kpitext; if(li.color=='优')li.cc=colorlist[0].rank_color; if(li.color=='良')li.cc=colorlist[1].rank_color; if(li.color=='中')li.cc=colorlist[2].rank_color; if(li.color=='差')li.cc=colorlist[3].rank_color; li.inside=li.inside=='0'?'室外':'室内'; return li; } /*** * 生成优良中差百分比图 * @param count * @param colorlist颜色 */ function creatFlash(idname,count,colorlist,grad,kpi){ var tempData = [ {y: 0 },{y: 0 },{y: 0 }, {y: 0 },{y: 0 },{y: 0 } ]; var xlist=[]; var options = { max: 100, chart: { renderTo:idname, backgroundColor: '#f0f0f0',plotBackgroundImage: '../images/bb.png' ,marginTop:50,marginBottom:50}, title: { text: '等级计算比例图',y:10,x:-10,align:'left'}, subtitle: { useHTML: true, x: -15,y:55}, xAxis: [{categories:[]}], plotOptions : { column : { groupPadding : 0.05 } } }; var ylist=[]; var obj={name:'Temperature', type:'column'}; var list=getCount(count,kpi,grad,colorlist); for(var t=0;t<list.length;t++){ var ca=list[t]; var cc1={ color:ca.color, y:(ca.yy),dataLabels:ca}; ylist.push(cc1); xlist.push(ca.xx); } obj.data=ylist; var objarr=[]; objarr.push(obj); options.series=objarr; //补图 var datas = options.series[0].data; var len = tempData.length, i=0; for(i=0;i<len;i++){ if(!datas[i]){datas.push(tempData[i]);xlist.push("");}else{ } } options.plotOptions = { xAxis : { categories : xlist }, column : { dataLabels : { formatter : function() { var result = this.y; return result ? result + '' : ''; } } } }; options.xAxis[0].categories=xlist; options.xAxis[0].labels={style: {color:'#020202'}}; var reportForms = new ReportForms(); reportForms.Create(options); } /*** * 根据路测指标、等级处理百分比数据 * @param count * @param kpi * @param grad */ function getCount(count,kpi,grad,colorlist){ //综合 //处理百分比数据和不为1的情况 var sum=0; for(var t=0;t<count.length;t++){ sum+=count[t]; } var num=0; var arr_num=[]; var list=[]; if(kpi==-1){ for(var t=1;t<=count.length;t++){ var ca={}; var str=""; if(grad==-1){ if(t==1||t==2||t==3){ca.color=colorlist[0].rank_color;str+="优";if(t==1)str+="+";if(t==3)str+="-";} if(t==4||t==5||t==6){ca.color=colorlist[1].rank_color;str+="良";if(t==4)str+="+";if(t==6)str+="-";} if(t==7||t==8||t==9){ca.color=colorlist[2].rank_color;str+="中";if(t==7)str+="+";if(t==9)str+="-";} if(t==10||t==11||t==12){ca.color=colorlist[3].rank_color;str+="差";if(t==10)str+="+";if(t==12)str+="-";} }else{ if(grad==1)str+="优"; if(grad==2)str+="良"; if(grad==3)str+="中"; if(grad==4)str+="差"; if(t==1||t==2||t==3){ca.color=colorlist[grad-1].rank_color;if(t==1)str+="+";if(t==3)str+="-";} } ca.xx=str; ca.yy=count[t-1]; // var nn=((ca.yy*100)/sum).toFixed(2); //alert(ca.yy+":"+sum+":"+(ca.yy/sum)+":"+nn+":"+parseInt((ca.yy*100)/sum*10000)/100); ca.yy=Math.round(parseFloat(ca.yy/sum)*10000)/100; num+=ca.yy; arr_num.push(ca.yy); list.push(ca); } }else{ //单指标 for(var t=1;t<=count.length;t++){ var ca={}; var str=""; if(grad==-1){ if(t==1){ca.color=colorlist[0].rank_color;str+="优";} if(t==2){ca.color=colorlist[1].rank_color;str+="良";} if(t==3){ca.color=colorlist[2].rank_color;str+="中";} if(t==4){ca.color=colorlist[3].rank_color;str+="差";} }else{ if(grad==1){ca.color=colorlist[0].rank_color;str+="优";} if(grad==2){ca.color=colorlist[1].rank_color;str+="良";} if(grad==3){ca.color=colorlist[2].rank_color;str+="中";} if(grad==4){ca.color=colorlist[3].rank_color;str+="差";} } ca.xx=str; ca.yy=count[t-1]; //var nn=((ca.yy*100)/sum).toFixed(2); ca.yy=Math.round(parseFloat(ca.yy/sum)*10000)/100; num+=ca.yy; arr_num.push(ca.yy); list.push(ca); } } num=num*100-10000; var ll=[]; var ii=0; for(var t=0;t<list.length;t++){ var ca=list[t]; var cc_nn=ca.yy; if ((num>0||num<0)&&Math.max.apply(null, arr_num) == cc_nn&&ii==0){ cc_nn=parseInt(cc_nn*100-num)/100; ii++; } ca.yy=cc_nn; ll.push(ca); } return ll; } /** * 设置地图中心经纬度与等级 * @param map * @param center */ function setMapCenter(map,center){ if (center) { var Item_1 = new google.maps.LatLng(center.max_lat ,center.max_lng); var myPlace = new google.maps.LatLng(center.min_lat, center.min_lng); var bounds = new google.maps.LatLngBounds(); bounds.extend(myPlace); bounds.extend(Item_1); map.setCenter(bounds.getCenter()); map.fitBounds(bounds); } } $(function(){ $(".cond_").live('click',function(){ if($("#sernos_").validatebox("isValid")==false){ $.messager.alert("提示","输入超出长度!","warning"); return false; } var str = $("#diatype").val(); var openType = $("#openType").val(); var obj=getPram(3); conditionSave(obj,openType); if(str==='hi'){ queryData_(1,obj); }else if(str==='dl'){ download_(obj); } }); }); function queryData_(time,obj){ $("#background").show(); $("#bar_id").show(); $('#cond').dialog('close'); $.post(contextPath + "/gisgrad/gisgrad", {areaids:obj.areaids, inside:obj.inside, grad:obj.grad, isFirst:time, secendSerno:obj.scendvalue, startTime:obj.startTime, endTime:obj.endTime, sernos:obj.sernos, senceids:obj.senceids, testtype:obj.testtype, nettype:obj.nettype, datatype:obj.datatype, jobtype:obj.jobtype, kpi:obj.kpi, testnet:obj.testnet, colorversion:colorversion }, function(data){ $("#background").hide(); $("#bar_id").hide(); if(data.list.length==0){ $.messager.alert("提示","查询条件内没有相应数据!","warning"); } list_marker=data.list; var colorlist=data.color; var count=data.count; isColorChange = data.ischange; if(list_marker.length>0&&count.length>0){ //柱状图显示事件 //$("#show_flash").show(); var wid_len=(document.body.scrollWidth-document.body.scrollWidth*0.05)/2; $("#flash").append("<div class='histogram_flash' id='div_state' style='width:"+wid_len+"px;margin:0 auto;position: relative;'></div>"); creatFlash('div_state',count,colorlist,obj.grad,obj.kpi); flashHeight = $("#flash").css("height"); initeFlash(); } } ); } /** * 评价导出 */ function download_(obj){ var str_vo=""; str_vo+="areaids="+obj.areaids; str_vo+="&inside="+obj.inside; str_vo+="&grad="+obj.grad; str_vo+="&isFirst="+1; str_vo+="&secendSerno="+obj.scendvalue; str_vo+="&startTime="+obj.startTime; str_vo+="&endTime="+obj.endTime; str_vo+="&senceids="+obj.senceids; str_vo+="&testtype="+obj.testtype; str_vo+="&nettype="+obj.nettype; str_vo+="&datatype="+obj.datatype; str_vo+="&jobtype="+obj.jobtype; str_vo+="&sernos="+obj.sernos; str_vo+="&kpi="+obj.kpi; str_vo+="&testnet="+obj.testnet; location.href = contextPath+"/gisgrad/download?"+str_vo; $('#cond').dialog('close'); } /** *提交柱状图查询时保留查询条件 */ function conditionSave(obj,openType){ if(openType==1){ grap_.inside = obj.inside; grap_.grad = obj.grad; grap_.startTime = obj.startTime ; grap_.endTime = obj.endTime; grap_.areaids = obj.areaids; grap_.areatext = $("#areatext_").val(); grap_.senceids = obj.senceids; grap_.senctext = $("#senctext_").val(); grap_.testtype = obj.testtype; grap_.testtypeText = $("#testtypeText_").val(); grap_.nettype= obj.nettype; grap_.datatype=obj.datatype; grap_.jobtype=obj.jobtype; grap_.kpi=obj.kpi; grap_.sernos=obj.sernos; grap_.testnet = obj.testnet; grap_.testnetName = $("#testnetName_").val(); }else if(openType==2){ grap_s.inside = obj.inside; grap_s.grad = obj.grad; grap_s.startTime = obj.startTime ; grap_s.endTime = obj.endTime; grap_s.areaids = obj.areaids; grap_s.areatext = $("#areatext_").val(); grap_s.senceids = obj.senceids; grap_s.senctext = $("#senctext_").val(); grap_s.testtype = obj.testtype; grap_s.testtypeText = $("#testtypeText_").val(); grap_s.nettype= obj.nettype; grap_s.datatype=obj.datatype; grap_s.jobtype=obj.jobtype; grap_s.kpi=obj.kpi; grap_s.sernos=obj.sernos; grap_s.testnet = obj.testnet; grap_s.testnetName = $("#testnetName_").val(); } }<file_sep>/src/main/java/com/complaint/model/Sysconfig.java package com.complaint.model; import java.io.Serializable; public class Sysconfig implements Serializable { private String configname; private String configkey; private String configvalue; private Integer status; public String getConfigname() { return configname; } public void setConfigname(String configname) { this.configname = configname; } public String getConfigkey() { return configkey; } public void setConfigkey(String configkey) { this.configkey = configkey; } public String getConfigvalue() { return configvalue; } public void setConfigvalue(String configvalue) { this.configvalue = configvalue; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } } <file_sep>/src/main/java/com/complaint/service/AreaService.java package com.complaint.service; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.complaint.dao.AreaDao; import com.complaint.model.AreaBean; import com.complaint.model.Group; import com.complaint.model.Personnel; @Service("areaService") public class AreaService { @Autowired private AreaDao areaDao; /** * 查询所有区域 * @return */ public List<AreaBean> getAllArea(){ return this.areaDao.queryAllArea(); } /** * 查询所有公司 * @return */ public List<AreaBean> getAllGroup(){ return this.areaDao.queryAllGroup(); } /** * @Title: queryAreaCondition * @param @param params * @return List<AreaBean> * @throws */ public List<AreaBean> queryAreaCondition(Map<String,Object> params){ return this.areaDao.queryAreaCondition(params); } } <file_sep>/src/main/java/com/complaint/action/TeamGroupController.java package com.complaint.action; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.complaint.model.AreaBean; import com.complaint.model.Group; import com.complaint.model.GroupManager; import com.complaint.model.Personnel; import com.complaint.model.TeamGroup; import com.complaint.page.PageBean; import com.complaint.service.TeamGroupService; import com.complaint.utils.ExcelUtil; @Controller @RequestMapping("/teamgroup") public class TeamGroupController { @Autowired private TeamGroupService teamGroupService; private static final Logger logger = LoggerFactory .getLogger(TeamGroupController.class); @RequestMapping(value = "/teamgroup") public ModelAndView GroupList(HttpServletRequest request, String name, Integer id) { ModelAndView mv = new ModelAndView("/teamgroup/teamgroup"); PageBean pb = teamGroupService.getPageBean(name);// 查询分页 mv.addObject("pb", pb); mv.addObject("name", name); return mv; } @RequestMapping(value = "/teamgroup/template") public String Ftplist(Model model, HttpServletRequest request, String name) { List<GroupManager> groupManager = teamGroupService.getInfo(name); model.addAttribute("groupManager", groupManager); return "/teamgroup/childlist"; } @RequestMapping(value = "/teammanager", method = RequestMethod.GET) public ModelAndView teammanager(HttpServletRequest request, Integer type) { ModelAndView mv = new ModelAndView("/teamgroup/teamManager"); //大组 List<TeamGroup> bigs = teamGroupService.getBigTeams(); //小组 List<TeamGroup> smalls = teamGroupService.getSmallTeams(); //人员 List<Personnel> personnels = teamGroupService.getPersonnels(); //不在大组的小组 List<TeamGroup> notBigs = teamGroupService.getNotInBig(); //不在小组的人员 List<Personnel> notSmalls = teamGroupService.getNotInSmall(); //不在人员的区域 List<AreaBean> notPersonnels = teamGroupService.getNotInPersonne(); //大组名称最长字节 int biglen = 0; for (int i = 0; i < bigs.size(); i++) { TeamGroup group = bigs.get(i); if (i == 0) { biglen = ExcelUtil.getStrLength(group.getGroupname()); } else { if (biglen < ExcelUtil.getStrLength(group.getGroupname())) { biglen = ExcelUtil.getStrLength(group.getGroupname()); } } } // 小组名称最长字节 int smalllen = 0; for (int i = 0; i < smalls.size(); i++) { TeamGroup group = smalls.get(i); if (i == 0) { smalllen = ExcelUtil.getStrLength(group.getGroupname()); } else { if (smalllen < ExcelUtil.getStrLength(group.getGroupname())) { smalllen = ExcelUtil.getStrLength(group.getGroupname()); } } } // 人员名称最长字节 int personnellen = 0; for (int i = 0; i < personnels.size(); i++) { Personnel ps = personnels.get(i); if (i == 0) { personnellen = ExcelUtil.getStrLength(ps.getName()); } else { if (personnellen < ExcelUtil.getStrLength(ps.getName())) { personnellen = ExcelUtil.getStrLength(ps.getName()); } } } mv.addObject("biglen", biglen); mv.addObject("smalllen", smalllen); mv.addObject("personnellen", personnellen); mv.addObject("bigs", bigs); mv.addObject("smalls", smalls); mv.addObject("personnels", personnels); mv.addObject("notbigs", notBigs); mv.addObject("notsmalls", notSmalls); mv.addObject("notpersonnels", notPersonnels); mv.addObject("type", type); return mv; } /** * 进入添加页面 * * @param request * @param type * @return */ @RequestMapping(value = "/addteam", method = RequestMethod.GET) public ModelAndView addTeam(HttpServletRequest request, Integer type) { ModelAndView mv = null; if (type.equals(1) || type.equals(2)) { mv = new ModelAndView("/teamgroup/addTeam"); } else { mv = new ModelAndView("/teamgroup/addPersonnel"); } mv.addObject("type", type); return mv; } /** * 添加 大组、小组、人员 * * @param request * @param type * @param groupname * @param phone * @return */ @RequestMapping(value = "/add", method = RequestMethod.POST) public @ResponseBody Map<String, Object> add(HttpServletRequest request, Integer type, String groupname, String phone) { Map<String, Object> map = new HashMap<String, Object>(); int msg = 0; if (type.equals(1) || type.equals(2)) { msg = teamGroupService.addTeam(type, groupname); } else { msg = teamGroupService.addPersonnel(groupname, phone); } map.put("msg", msg); map.put("type", type); return map; } /** * 删除 大组、小组、人员 * * @param request * @param type * @param ids * @return */ @RequestMapping(value = "/delete", method = RequestMethod.POST) public @ResponseBody Map<String, Object> delete(HttpServletRequest request, Integer type, String ids) { Map<String, Object> map = new HashMap<String, Object>(); int msg = 0; try { // type 1 大组 2小组 3人员 if (type.equals(1) || type.equals(2)) { teamGroupService.deleteTeam(type, ids); } else { teamGroupService.deletePersonnel(ids); } msg = 1; } catch (Exception e) { logger.error("", e); } map.put("msg", msg); map.put("type", type); return map; } /** * 修改大组、小组、人员 * * @param request * @param groups * @return */ @RequestMapping(value = "/update", method = RequestMethod.POST) public @ResponseBody Map<String, Object> update(HttpServletRequest request, Integer type, String groups) { Map<String, Object> map = new HashMap<String, Object>(); int msg = 0; try { // type 0 大组 1小组 2 人员 if (type.equals(1) || type.equals(2)) { teamGroupService.updateTeam(groups); } else { teamGroupService.updatePersonnel(groups); } msg = 1; } catch (Exception e) { logger.error("", e); } map.put("msg", msg); map.put("type", type); return map; } /** * 修改关系集合 * * @param groups * @return */ @RequestMapping(value = "/updatelist", method = RequestMethod.POST) public @ResponseBody Map<String, Object> updatelist(HttpServletRequest request, Integer type, String groups) { Map<String, Object> map = new HashMap<String, Object>(); int msg = 0; try { // type 4 大组与小组 5小组与区域 6 人员与区域 7 大组组长配置 8 小组组长配置 if (type.equals(4)) { teamGroupService.updateBigRelations(groups); } else if (type.equals(5)) { teamGroupService.updateSmallRelations(groups); } else if (type.equals(6)) { teamGroupService.updatePersonnelRelations(groups); } else if (type.equals(7) || type.equals(8)) { teamGroupService.updateLeader(groups, type); } msg = 1; } catch (Exception e) { logger.error("", e); } map.put("msg", msg); return map; } @RequestMapping(value = "/isExsit", method = RequestMethod.POST) public @ResponseBody boolean isExsit(String groupname) { boolean bool = this.teamGroupService.isExsit(groupname); return !bool; } } <file_sep>/src/main/java/com/complaint/utils/ByteUtil.java package com.complaint.utils; public class ByteUtil { /** * 转换short为byte * * @param b * @param s * 需要转换的short * @param index */ public static void putShort(byte b[], short s, int index) { b[index + 1] = (byte) (s >> 8); b[index + 0] = (byte) (s >> 0); } /** * 通过byte数组取到short * * @param b * @param index * 第几位开始取 * @return */ public static short getShort(byte[] b, int index) { return (short) (((b[index + 1] << 8) | b[index + 0] & 0xff)); } /** * 转换int为byte数组 * * @param bb * @param x * @param index */ public static void putInt(byte[] bb, int x, int index) { bb[index + 3] = (byte) (x >> 24); bb[index + 2] = (byte) (x >> 16); bb[index + 1] = (byte) (x >> 8); bb[index + 0] = (byte) (x >> 0); } /** * 通过byte数组取到int * * @param bb * @param index * 第几位开始 * @return */ public static int getInt(byte[] bb, int index) { return ((((bb[index + 3] & 0xff) << 24) | ((bb[index + 2] & 0xff) << 16) | ((bb[index + 1] & 0xff) << 8) | ((bb[index + 0] & 0xff) << 0))); } /** * 转换long型为byte数组 * * @param bb * @param x * @param index */ public static void putLong(byte[] bb, long x, int index) { bb[index + 7] = (byte) (x >> 56); bb[index + 6] = (byte) (x >> 48); bb[index + 5] = (byte) (x >> 40); bb[index + 4] = (byte) (x >> 32); bb[index + 3] = (byte) (x >> 24); bb[index + 2] = (byte) (x >> 16); bb[index + 1] = (byte) (x >> 8); bb[index + 0] = (byte) (x >> 0); } /** * 通过byte数组取到long * * @param bb * @param index * @return */ public static long getLong(byte[] bb, int index) { return ((((long) bb[index + 7] & 0xff) << 56) | (((long) bb[index + 6] & 0xff) << 48) | (((long) bb[index + 5] & 0xff) << 40) | (((long) bb[index + 4] & 0xff) << 32) | (((long) bb[index + 3] & 0xff) << 24) | (((long) bb[index + 2] & 0xff) << 16) | (((long) bb[index + 1] & 0xff) << 8) | (((long) bb[index + 0] & 0xff) << 0)); } // /** // * 字符到字节转换 // * // * @param ch // * @return // */ // public static void putChar(byte[] bb, char ch, int index) { // int temp = (int) ch; // // byte[] b = new byte[2]; // for (int i = 0; i < 2; i++) { // bb[index + i] = new Integer(temp & 0xff).byteValue(); // 将最高位保存在最低位 // temp = temp >> 8; // 向右移8位 // } // } // // /** // * 字节到字符转换 // * // * @param b // * @return // */ // public static char getChar(byte[] b, int index) { // int s = 0; // if (b[index + 1] > 0) // s += b[index + 1]; // else // s += 256 + b[index + 0]; // s *= 256; // if (b[index + 0] > 0) // s += b[index + 1]; // else // s += 256 + b[index + 0]; // char ch = (char) s; // return ch; // } /** * float转换byte * * @param bb * @param x * @param index */ public static void putFloat(byte[] bb, float x, int index) { // byte[] b = new byte[4]; int l = Float.floatToIntBits(x); for (int i = 0; i < 4; i++) { bb[index + i] = new Integer(l).byteValue(); l = l >> 8; } } /** * 通过byte数组取得float * * @param bb * @param index * @return */ public static float getFloat(byte[] b, int index) { int l; l = b[index + 0]; l &= 0xff; l |= ((long) b[index + 1] << 8); l &= 0xffff; l |= ((long) b[index + 2] << 16); l &= 0xffffff; l |= ((long) b[index + 3] << 24); return Float.intBitsToFloat(l); } /** * double转换byte * * @param bb * @param x * @param index */ public static void putDouble(byte[] bb, double x, int index) { // byte[] b = new byte[8]; long l = Double.doubleToLongBits(x); for (int i = 0; i < 8; i++) { bb[index + i] = new Long(l).byteValue(); l = l >> 8; } } /** * 通过byte数组取得float * * @param bb * @param index * @return */ public static double getDouble(byte[] b, int index) { long l; l = b[index + 0]; l &= 0xff; l |= ((long) b[index + 1] << 8); l &= 0xffff; l |= ((long) b[index + 2] << 16); l &= 0xffffff; l |= ((long) b[index + 3] << 24); l &= 0xffffffffl; l |= ((long) b[index + 4] << 32); l &= 0xffffffffffl; l |= ((long) b[index + 5] << 40); l &= 0xffffffffffffl; l |= ((long) b[index + 6] << 48); l &= 0xffffffffffffffl; l |= ((long) b[index + 7] << 56); return Double.longBitsToDouble(l); } public static String getString(byte[] b, int start, int end) { int length = 0; for (int i = start; i < end; i++) { if (b[i] != (byte) 0) { length++; } else { break; } } byte[] b2 = new byte[length]; System.arraycopy(b, start, b2, 0, length); return new String(b2); } /** * 转换int到字节 * @param iSource * @param iArrayLen * @return */ public static byte[] toByteArray(int iSource, int iArrayLen) { byte[] bLocalArr = new byte[iArrayLen]; for ( int i = 0; (i < 4) && (i < iArrayLen); i++) { bLocalArr[i] = (byte)( iSource>>8*i & 0xFF ); } return bLocalArr; } }<file_sep>/src/main/java/com/complaint/model/Scene.java package com.complaint.model; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Map; import org.json.simple.JSONStreamAware; import org.json.simple.JSONValue; public class Scene implements java.io.Serializable,JSONStreamAware{ /** * */ private static final long serialVersionUID = 1L; private Short sceneid; private Short inside; private Short type; private String insidetype; private String name; public Short getSceneid() { return sceneid; } public void setSceneid(Short sceneid) { this.sceneid = sceneid; } public Short getInside() { return inside; } public void setInside(Short inside) { this.inside = inside; } public Short getType() { return type; } public void setType(Short type) { this.type = type; } public String getInsidetype() { return insidetype; } public void setInsidetype(String insidetype) { this.insidetype = insidetype; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public void writeJSONString(Writer out) throws IOException { Map<String,Object> obj = new HashMap<String,Object>(); obj.put("id", this.sceneid); obj.put("is", this.inside); obj.put("cg", this.type); obj.put("it", this.insidetype); obj.put("sc", this.name); JSONValue.writeJSONString(obj, out); } } <file_sep>/src/main/java/com/complaint/service/SysConfigService.java package com.complaint.service; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.complaint.dao.SysConfigDao; import com.complaint.model.Sysconfig; import com.complaint.utils.Constant; @Service("sysConfigService") public class SysConfigService { @Autowired private SysConfigDao sysConfigDao; private static final Logger logger = LoggerFactory .getLogger(EpinfoExcelService.class); /** * 查询值 * * @return */ public String getValue(String configvalue) { return sysConfigDao.queryData(configvalue); } /** * 查询累计网络投诉工单量 * @param systime * @param endtime * @return */ public List<Map> getTotalSer(Map map){ return sysConfigDao.getTotalSer(map); } /** * 修改值 * * @return */ private void updateValue(String configkey, String configvalue) throws Exception { Map<String, Object> param = new HashMap<String, Object>(); param.put("configvalue", configvalue); param.put("configkey", configkey); sysConfigDao.updateData(param); } /** * 测试报告默认起始时间、及时率时间配置 * * @param reportdate * @param timelyrate * @return */ @Transactional(rollbackFor = Exception.class) public void updateTest(String reportdate, String timelyrate) throws Exception { updateValue(Constant.REPORTDATE, reportdate); updateValue(Constant.TIMELYRATE, timelyrate); } /** * 质量报表默认起始时间、及时率时间配置 * * @param reportdate * @param timelyrate * @return */ @Transactional(rollbackFor = Exception.class) public void updateQual(String qualdate, String timelyrate) throws Exception { updateValue(Constant.RP_QUALITY_CUMULATIVE_START_TIME, qualdate); updateValue(Constant.TIMELYRATE, timelyrate); } public String getAngleType() { Sysconfig sc = new Sysconfig(); try { sc = sysConfigDao.getAngleconfig("cell_angle_config"); } catch (Exception e) { logger.error("cell_angle_config", e); } String[] str = sc.getConfigvalue().split("="); String type = str[1].substring(0, 1); return type; } } <file_sep>/src/main/java/com/complaint/dao/impl/BaseDaoImpl.java package com.complaint.dao.impl; import java.util.List; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import com.complaint.dao.BaseDao; import com.complaint.dao.BatchDao; public class BaseDaoImpl implements BaseDao{ @Autowired private SqlSessionFactoryBean sqlSessionFactoryTemplate; private Integer batch = 200; /** * 批量插入,默认为每次200条 * type为mapper接口类,且必须继承BatchDao接口 */ public void batchInsert(Class<?> type,List<?> list,Integer batchNum) throws Exception{ if(type == null) return; if(CollectionUtils.isEmpty(list)) return; if(batchNum != null && batchNum > 1) this.batch = batchNum; SqlSessionFactory sqlSessionFactory = sqlSessionFactoryTemplate.getObject(); SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false); for(int i=0;i<list.size();i++){ BatchDao mapper = (BatchDao)sqlSession.getMapper(type); mapper.insertByBatch(list.get(i)); if((i != 0 && i % batch == 0) || i + 1 == list.size()) { sqlSession.commit(); sqlSession.clearCache(); } } sqlSession.close(); } } <file_sep>/src/main/java/com/complaint/dao/WcdmsOwnLogDao.java package com.complaint.dao; import com.complaint.model.WcdmsTrackLog; public interface WcdmsOwnLogDao extends BatchDao{ void insert(WcdmsTrackLog wcdmsTrackLog); void delOwnWcdmaByFlowid(String flowid); } <file_sep>/src/main/java/com/complaint/model/EvaluateRule.java package com.complaint.model; /** * 评分规则 * @author peng * */ public class EvaluateRule { // 按优良中差对应1234 private int rank_code; // 评分分为按+1,1,-1分为123 private int rank_code_sub; private int rank_score; // 室内-1 室外-0 private int scene; // 指标阈值-1 综合阈值-2 private int type; public int getRank_code() { return rank_code; } public void setRank_code(int rank_code) { this.rank_code = rank_code; } public int getRank_code_sub() { return rank_code_sub; } public void setRank_code_sub(int rank_code_sub) { this.rank_code_sub = rank_code_sub; } public int getRank_score() { return rank_score; } public void setRank_score(int rank_score) { this.rank_score = rank_score; } public int getScene() { return scene; } public void setScene(int scene) { this.scene = scene; } public int getType() { return type; } public void setType(int type) { this.type = type; } } <file_sep>/src/main/webapp/js/gisgrad/regionBox_baidu.js var minX,maxX,minY,maxY;//框选的最大最小值 var mousex,mousey;//监控鼠标位置 var mousex2,mousey2;//鼠标最后一次按下时位置 var pr;//框选层 var dm; var drawingManager; var nowx; var nowy; function chooseMap(map){ drawingManager =new BMapLib.DrawingManager(map, {isOpen: false, drawingType: BMAP_DRAWING_MARKER, enableDrawingTool: true, enableCalculate: false, drawingToolOptions: { anchor: BMAP_ANCHOR_TOP_LEFT, offset: new BMap.Size(5, 5), drawingTypes : [ BMAP_DRAWING_RECTANGLE ] }, polylineOptions: { strokeColor: "#8FA4F5" }}); dm = drawingManager; drawingManager.addEventListener('rectanglecomplete', function(re) {//监控矩形完成事件 var bo =re.getBounds(); //打印出坐标后恢复为拖拽地图设置 if(!(typeof(pr)=="undefined")){ close(map);//当再次框选是之前矩形框消失 } pr = re; getinformation(bo,re); }); } function getinformation(bo,re){ maxX=bo.getNorthEast().lat; minX=bo.getSouthWest().lat; maxY=bo.getNorthEast().lng; minY=bo.getSouthWest().lng; var c_info = $("#stationareaids").val(); if((typeof(regionCondition)!= 'undefined' && regionCondition!='' && regionCondition != null)||(typeof(c_info)!= 'undefined' && c_info!="\'\'" && c_info != null)){ layerDiv(); }else{ $.messager.alert("提示","请先查询数据或加载小区!","warning",function(){ close(map); }); } //re.setMap(null); } /** *弹出层 */ function layerDiv(){ var xx; var yy; if(mousex<=mousex2){ xx = mousex2-90; nowx = xx; }else{ xx = mousex-90; nowx = xx; } if(mousey2>=mousey){ yy = mousey2+2; nowy = yy; }else{ yy = mousey+2; nowy = yy; } $("#faqdiv").css("left",xx+"px"); $("#faqdiv").css("top",yy+"px"); $("#faqdiv").css("display","block"); } /** * 关闭罩子 */ function close(map){ $("#faqbg").css("display","none"); $("#faqdiv").css("display","none"); $("#fadown").css("display","none"); if(!(typeof(pr)=="undefined")){ map.removeOverlay(pr); } }; /** * 菜单一点击事件 */ $(function(){ $("#close").click(function(){ close(map); }); $("#regiondown").click(function(){ if(typeof(regionCondition)!='undefined'&&typeof(minX)!='undefined'&&typeof(minY)!='undefined'&&typeof(maxY)!='undefined'&&typeof(maxX)!='undefined'){ var obj=regionCondition; var str_vo=""; str_vo+="areaids="+obj.areaids; str_vo+="&inside="+obj.inside; str_vo+="&grad="+obj.grad; str_vo+="&isFirst="+1; str_vo+="&secendSerno="+obj.scendvalue; str_vo+="&startTime="+obj.startTime; str_vo+="&endTime="+obj.endTime; str_vo+="&senceids="+obj.senceids; str_vo+="&testtype="+obj.testtype; str_vo+="&nettype="+obj.nettype; str_vo+="&datatype="+obj.datatype; str_vo+="&jobtype="+obj.jobtype; str_vo+="&sernos="+obj.sernos; str_vo+="&kpi="+obj.kpi; str_vo+="&testnet="+obj.testnet; str_vo+="&minlat="+minX; str_vo+="&maxlat="+maxX; str_vo+="&minlng="+minY; str_vo+="&maxlng="+maxY; location.href = contextPath+"/gisgrad/download?"+str_vo; close(map); }else{ $.messager.alert("提示","请先查询数据!","warning",function(){ close(map); }); } }); /** * 点击下载显示下载菜单 */ $("#downloadchoose").live('click',function(){ if($("#fadown").css("display") == "none"){ $("#fadown").css("left",nowx-41+"px"); $("#fadown").css("top",(nowy+28)+"px"); $("#fadown").css("display","block"); }else if($("#fadown").css("display") == "block"){ $("#fadown").css("display","none"); } }); /** * 小区框选导出 */ $("#c_info_down").click(function(){ var ids = $("#stationareaids").val(); var nettype = $("#cellnettype").val(); var indoor = $("#cellindoor").val(); var cellBands = $("#cellcellbands").val(); if(ids!="\'\'"&& typeof(minX)!='undefined'&&typeof(minY)!='undefined'&&typeof(maxY)!='undefined'&&typeof(maxX)!='undefined'){ var str_vo=""; str_vo += 'areas=' + ids; str_vo += '&indoor=' + indoor; str_vo += '&modetypes=' + nettype; str_vo += '&cellBands=' + cellBands; str_vo+="&minlat="+minX; str_vo+="&maxlat="+maxX; str_vo+="&minlng="+minY; str_vo+="&maxlng="+maxY; if(clicktrunk!=''&&typeof(clicktrunk)!='undefined'){ var lac = clicktrunk.substring(clicktrunk.indexOf('_')+1,clicktrunk.lastIndexOf('_')); var cid = clicktrunk.substring(clicktrunk.lastIndexOf('_')+1,clicktrunk.length); str_vo+="&lac_cid="+lac+"_"+cid; } var cellrel = ""; if($("#tp").find("span").length>0){//同屏0 cellrel +="0,"; } if($("#yp").find("span").length>0){//异屏 cellrel +="1,"; } if($("#ywl").find("span").length>0){//异系统 cellrel +="2,"; } str_vo+="&cellrel="+cellrel; str_vo+="&report_type=0"; location.href = contextPath+'/gisgrad/downloadcellinfo?'+str_vo; close(map); }else{ $.messager.alert("提示","请先加载小区!","warning",function(){ close(map); }); } }); /** * 选择切换图片 */ $("#marquee").click(function(){ drawingManager.open(); drawingManager.setDrawingMode(BMAP_DRAWING_RECTANGLE); $(this).hide(); $("#hand_hover").hide(); $("#hand").show(); $("#marquee_hover").show(); }); $("#hand").click(function(){ if(drawingManager.getDrawingMode() == 'rectangle'){ //切换为拖拽是,移除已有的框选图层 close(map); drawingManager.close(); $(this).hide(); $("#hand_hover").show(); $("#marquee").show(); $("#marquee_hover").hide(); } }); $(".gis-mapgj ").css("left",document.documentElement.clientWidth-70); window.onresize = function(){ $(".gis-mapgj ").css("left",document.documentElement.clientWidth-70); }; /** *获取当前鼠标所在位置 */ $("#div_map").mousemove(function (e) { mousex = e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft; mousey = e.clientY+document.body.scrollTop+document.documentElement.scrollTop; }); }); /** *获取鼠标最后一次按下时位置 */ function mousedown(e) { mousex2 = e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft; mousey2 = e.clientY+document.body.scrollTop+document.documentElement.scrollTop; //alert(mousex2+":"+mousey2); }<file_sep>/src/main/webapp/js/canvas.js /** * * @param allDatas 所有数据 * @param initDatas 初始化数据 * @param args 显示的指标数据 * @param pcname 父容器的id * @param cname 子容器的id * @param imageid 图片id * @param exid 放大id * @param naid 缩小的id * @param maxid 画布变大的id(需要根据这个元素获取放大后宽度) * @param cw 子容器的宽度 * @param ch 子容器的高度 * @param parentw 父容器的初始宽度 * @param isclick 是否触发元素点击事件 * @fristId 第一个点的ID * @fristType 第一个点的类型 */ function MyCanvas(allDatas,initDatas,args,pcname,cname,imageid,exid,naid,maxid,cw,ch,parentw,cmdivid,isclick,fristId,fristType,id_last,type_last,compare){ var canvas = new Object; canvas.allDatas = allDatas; canvas.parentObj = $('#'+pcname+''); canvas.containerObj =$('#'+cname); canvas.containerdiv = cname; canvas.changeScreen = $("#"+imageid); canvas.cmdivid = cmdivid; canvas.expandObj = $('#'+exid); canvas.narrowObj = $('#'+naid); canvas.maxDivObj = $("#"+maxid); canvas.cmdivObj = $("#"+cmdivid); canvas.fristId = fristId; canvas.fristType = fristType; canvas.id_last = id_last; canvas.type_last = type_last; canvas.cw = cw; canvas.ch = ch; canvas.parentw = parentw; canvas.isclick = isclick; var paper; var scale = 2; //比例 1为100% var step = 0.2; //每次缩放比例 var r = 5; //radius var maxScale = 5; //最大比例300% var minScale = 1; //最小比例100% var animateDelay = 500; var paperDown = false; //画布按下标识 var paperOx = 0; //画布原始位置left var paperOy = 0; //画布原始位置top var paperCx = 0; //画布当前位置left var paperCy = 0; //画布当前位置top var g2,g3,g4; var sets = new Array(); canvas.init = function(){ scale = 1; step = 0.2; //每次缩放比例 r = 5; //radius maxScale = 3; //最大比例300% minScale = 1; //最小比例100% animateDelay = 500; paperDown = false; //画布按下标识 paperOx = 0; //画布原始位置left paperOy = 0; //画布原始位置top paperCx = 0; //画布当前位置left paperCy = 0; //画布当前位置top }; canvas.pushDataToSet = function(key,type,count,args,id,firstType,id_last,type_last,left,top,isclick){ var data; if(type == 2){ data = g3[key]; }else if(type == 3){ data = g4[key]; }else{ data = g2[key]; } var ishow = false; for ( var i = 0; i < args.length; i++) { if(key == args[i]){ ishow = true; break; } } if(key != null && key != ""){ sets.push(MyGraphic(data,count,ishow,key,scale,step,id,firstType,id_last,type_last,isclick,paper,r,left/1.7,(left/2)*(9/16)*1.5,compare)); } }; canvas.initData = function(svgDate,args,id,type,id_last,type_last,left,top,isclick,ss){ var count = 0; var count_3 = 0,count_4=0; for(var key in svgDate){ if(key == "2G"){ g2 = svgDate[key]; for(var key2 in g2){ count = $.inArray(key2, idooorTag[ss]); canvas.pushDataToSet(key2,1,count,args,id,type,id_last,type_last,left,top,isclick); } }else if(key == "3G"){ g3 = svgDate[key]; for(var key3 in g3){ count_3 = $.inArray(key3, idooorTag[ss]); canvas.pushDataToSet(key3,2,count_3,args,id,type,id_last,type_last,left,top,isclick); } }else if(key == "4G"){ g4 = svgDate[key]; for(var key4 in g4){ count_4 = $.inArray(key4, idooorTag[ss]); canvas.pushDataToSet(key4,3,count_4,args,id,type,id_last,type_last,left,top,isclick); } } } }; canvas.hiddenAll = function(){ if(sets.length > 0){ for ( var i = 0; i < sets.length; i++) { sets[i].hidden(); } } }; canvas.display = function(args){ canvas.hiddenAll(); if(sets.length > 0){ for ( var i = 0; i < sets.length; i++) { for ( var j = 0; j < args.length; j++) { if(args[j] != "3G" && args[j] != "2G"&& args[j] != "4G" && sets[i].getName() == args[j]){ sets[i].show(); } } } } }; canvas.toExpand = function(){ if(sets.length > 0){ for ( var i = 0; i < sets.length; i++) { sets[i].cxyExpand(scale,step); } } }; canvas.toNarrow = function(){ if(sets.length > 0){ for ( var i = 0; i < sets.length; i++) { sets[i].cxyNarrow(scale,step); } } }; canvas.initArgs = function(top,left,paper){ canvas.parentObj.css('width',canvas.parentw); canvas.containerObj.css('width',canvas.cw).css('height',canvas.ch); paper.clear(); paper.setSize(canvas.cw,canvas.ch); canvas.containerObj.css('top',top); canvas.containerObj.css('left',left); scale = 1; //比例 1为100% step = 0.2; //每次缩放比例 r = 5; //radius maxScale = 3; //最大比例300% minScale = 1; //最小比例100% animateDelay = 500; paperDown = false; //画布按下标识 paperOx = 0; //画布原始位置left paperOy = 0; //画布原始位置top paperCx = 0; //画布当前位置left paperCy = 0; //画布当前位置top canvas.changeScreen.attr("src","../images/map_add.png"); canvas.changeScreen.attr("sta","smail"); }; canvas.initPaper = function(ss){ paper = Raphael(canvas.containerdiv, canvas.cw, canvas.ch); if(canvas.changeScreen.attr("sta") == "large"){ canvas.initArgs(canvas.cw/3,canvas.ch/3,paper); } canvas.initData(initDatas,args,canvas.fristId,canvas.fristType,canvas.id_last,canvas.type_last,canvas.cw/3,canvas.ch/3,canvas.isclick,ss); canvas.changeScreen.unbind("click").bind("click", function(){ var pw = canvas.parentObj.width(); var sta = canvas.changeScreen.attr("sta"); if(sta == "smail"){ canvas.changeScreen.attr("src","../images/map_lessen.png"); canvas.changeScreen.attr("sta","large"); var c_w = canvas.containerObj.width(); var c_h = canvas.containerObj.height(); var width = canvas.maxDivObj.width(); canvas.parentObj.css('width',width); canvas.cmdivObj.css('width',width); canvas.containerObj.css('width',3*width); paper.setSize(c_w,c_h); if(sets.length > 0){ for ( var i = 0; i < sets.length; i++) { sets[i].changeCxy(canvas.containerObj.position().left,pw,width,true); } } }else{ canvas.parentObj.css('width',canvas.parentw); canvas.containerObj.css('width',canvas.cw).css('height',canvas.ch); canvas.changeScreen.attr("src","../images/map_add.png"); canvas.changeScreen.attr("sta","smail"); paper.setSize(canvas.cw,canvas.ch); canvas.cmdivObj.css('width',canvas.parentw); if(sets.length > 0){ for ( var i = 0; i < sets.length; i++) { sets[i].changeCxy(canvas.containerObj.position().left,pw,canvas.parentw,false); } } canvas.containerObj.css('top',Math.max(canvas.containerObj.position().top,(canvas.parentObj.height() - canvas.containerObj.height()))); canvas.containerObj.css('left',Math.max(canvas.containerObj.position().left,(canvas.parentObj.width() - canvas.containerObj.width()))); } location.hash= canvas.cmdivid; }); canvas.expandObj.unbind("click").bind("click",function(){ scale += step; scale = parseFloat(scale); if(scale > maxScale){ scale = maxScale; return; } canvas.toExpand(); }); canvas.narrowObj.unbind("click").bind("click",function(){ scale -= step; scale = parseFloat(scale); if(scale < minScale){ scale = minScale; return; } canvas.toNarrow(); }); canvas.containerObj.unbind("mousedown").bind("mousedown",function(event){ if(event.target.nodeName != 'circle' && event.target.nodeName != 'shape'){ paperOx = event.pageX; paperOy = event.pageY; paperDown = true; } }); canvas.containerObj.unbind("mouseup").bind("mouseup",function(event){ if(event.target.nodeName != 'circle' && event.target.nodeName != 'shape'){ paperDown = false; } }); canvas.containerObj.unbind("mousemove").bind("mousemove",function(event){ if(event.target.nodeName != 'circle' && event.target.nodeName != 'shape' && paperDown){ var dx = event.pageX- paperOx; var dy = event.pageY- paperOy; paperOx = event.pageX; paperOy = event.pageY; var ctop = parseInt(canvas.containerObj.position().top); var cleft = parseInt(canvas.containerObj.position().left); var cwidth = parseInt(canvas.containerObj.css('width')) - parseInt(canvas.parentObj.css('width')); var cheight = parseInt(canvas.containerObj.css('height')) - parseInt(canvas.parentObj.css('height')); ctop = ctop + dy; cleft = cleft + dx; ctop = Math.max(ctop,-cheight); cleft = Math.max(cleft,-cwidth); ctop = Math.min(ctop,0); cleft = Math.min(cleft,0); canvas.containerObj.css('top',ctop); canvas.containerObj.css('left',cleft); } }); canvas.containerObj.unbind("mouseout").bind("mouseout",function(event){ paperDown = false; }); }; return canvas; }<file_sep>/src/main/webapp/js/gisgrad/gradquery.js //区域查询 function initeArea(){ $.parser.parse('#ii'); $.parser.parse('#gg'); $.parser.parse('#nettype'); $.parser.parse('#datatype'); $.parser.parse('#jj'); $.parser.parse('#kk'); $("#areas").combobox({ onShowPanel:function(){ $("#areas").combobox("hidePanel"); var ids = $("#areaids").val(); openAreaDialog(0,ids); } }); } function openAreaDialog(type,ids,map){ var src = contextPath + '/workorder/arealist?areaids='+ids+'&type='+type; $("#areadlg").dialog({ href:src, height: 400,width: 380,title: "选择区域", modal: true,closed:false }); $('#areadlg').dialog('open'); $.parser.parse('#areadlg'); $("#areadlg"); $(".sel_area").unbind('click').click(function(){ var nodes = $('#areadlg').tree('getChecked'); var strtext = ""; var strids = ""; var len = nodes.length; if(type == 0){ if(len > 0){ for(var i = 0; i < len; i++){ strids += nodes[i].id + ","; strtext += nodes[i].text + ","; } if(strids !=null && strids != ""){ strids = strids.substring(0,strids.length-1); $("#areaids").val(strids); } if(strtext !=null && strtext != ""){ strtext = strtext.substring(0,strtext.length-1); $("#areas").combobox("setText",strtext); $("#areatext").val(strtext); } }else{ $("#areaids").val('-1'); $("#areatext").val('全部'); $("#areas").combobox("setText",'全部'); } }else{ if(len > 0){ if(len <= 3){ for(var i = 0; i < len; i++){ strids += nodes[i].id + ","; } if(strids !=null && strids != ""){ removeStationMap(); changeCells = []; stationInitData = []; span_map_psc=[]; p_map_jizhan=[]; cacheCells = []; click_cell = ""; strids = strids.substring(0,strids.length-1); $("#stationareaids").val(strids); var latLngBounds = map.getBounds(); var latLngNE = latLngBounds.getNorthEast(); var latLngSW = latLngBounds.getSouthWest(); $("#background").show(); $("#bar_id").show(); $.ajax({ type:'get', url:contextPath + '/gisgrad/test', data:{areas:strids}, success:function(data){ if(data) is_showcell =true; var positionList = data.position; _map.positionList = positionList; if(positionList&&!list_marker){ var item = positionList[0]; map.setZoom(16); map.setCenter(new google.maps.LatLng(item.longitude,item.latitude)); } //从查询出来的数据筛选出当前屏幕的数据 // if(!positionList && !list_marker){ // map.setZoom(16); // if(inMapData.length>0) // map.setCenter(new google.maps.LatLng(inMapData[0].bsList[0].celllat,inMapData[0].bsList[0].celllng)); // } //清空小区信息 if(_infowindow) _infowindow.close(); //画小区 if(map.getZoom()>=DEFAULTMAPZOOM){ stationInitData = data.data; var inMapData = getBoundsStation(map); for (var j = 0; j < inMapData.length; j++) { drawStation(inMapData[j].bsList, map); } } $("#background").hide(); $("#bar_id").hide(); } }); } }else{ $.messager.alert("提示","加载基站信息,不能超过三个区域!","warning"); } }else{ //清空小区信息 removeStationMap(); changeCells = []; stationInitData = []; span_map_psc=[]; p_map_jizhan=[]; cacheCells = []; click_cell = ""; $("#stationareaids").val('-1'); } } $('#areadlg').dialog('close'); }); } //查询场景 function initeScence(){ $("#sencs").combobox({ onShowPanel:function(){ $("#sencs").combobox("hidePanel"); $.parser.parse('#ii'); var src = contextPath + '/gisgrad/sencelist?senceids='+$("#senceids").val()+"&inside="+$("#ii").combobox('getValue'); $("#sencedlg").dialog({ href:src, height: 400,width: 380,title: "选择场景", modal: true,closed:false }); $('#sencedlg').dialog('open'); $.parser.parse('#sencedlg'); $(".sel_scene").unbind('click').click(function(){ var nodes = $('#sencedlg').tree('getChecked'); var strtext = ""; var strids = ""; if(nodes.length > 0){ for(var i = 0; i < nodes.length; i++){ strids += nodes[i].id + ","; strtext += nodes[i].text + ","; } if(strids !=null && strids != ""){ strids = strids.substring(0,strids.length-1); $("#senceids").val(strids); } if(strtext !=null && strtext != ""){ strtext = strtext.substring(0,strtext.length-1); $("#sencs").combobox("setText",strtext); $("#senctext").val(strtext); } $('#sencedlg').dialog('close'); }else{ $.messager.alert("提示","请选择场景!","warning"); } }); } }); } //业务类型 function initeTestType(){ $("#testtypes").combobox({ onShowPanel:function(){ $("#testtypes").combobox("hidePanel"); $.parser.parse('#nettype'); var src = contextPath + '/gisgrad/testtypelist?testtype='+$("#testtype").val()+'&nettype='+$("#nettype").combobox('getValue'); $("#testtypedlg").dialog({ href:src, height: 400,width: 380,title: "业务类型", modal: true,closed:false }); $('#testtypedlg').dialog('open'); $.parser.parse('#testtypedlg'); $(".sel_testtype").unbind('click').click(function(){ var nodes = $('#testtypedlg').tree('getChecked'); var strtext = ""; var strids = ""; if(nodes.length > 0){ for(var i = 0; i < nodes.length; i++){ strids += nodes[i].id + ","; strtext += nodes[i].text + ","; } if(strids !=null && strids != ""){ strids = strids.substring(0,strids.length-1); $("#testtype").val(strids); } if(strtext !=null && strtext != ""){ strtext = strtext.substring(0,strtext.length-1); $("#testtypes").combobox("setText",strtext); $("#testtypeText").val(strtext); } $('#testtypedlg').dialog('close'); }else{ $.messager.alert("提示","请选择业务类型!","warning"); } }); } }); } //测试网络 function initeTestnets(){ $("#testnets").combobox({ onShowPanel:function(){ $("#testnets").combobox("hidePanel"); $.parser.parse('#nettype'); var src = contextPath + '/gisgrad/testNetlist?nettype='+$("#nettype").combobox('getValue')+'&testnet='+$("#testnet").val(); $("#testnetdlg").dialog({ href:src, height: 400,width: 380,title: "选择网络", modal: true,closed:false }); $('#testnetdlg').dialog('open'); $.parser.parse('#testnetdlg'); $(".sel_testnet").unbind('click').click(function(){ var nodes = $('#testnetdlg').tree('getChecked'); var strtext = ""; var strids = ""; if(nodes.length > 0){ for(var i = 0; i < nodes.length; i++){ strids += nodes[i].id + ","; strtext += nodes[i].text + ","; } if(strids !=null && strids != ""){ strids = strids.substring(0,strids.length-1); $("#testnet").val(strids); } if(strtext !=null && strtext != ""){ strtext = strtext.substring(0,strtext.length-1); $("#testnets").combobox("setText",strtext); $("#testnetName").val(strtext); } $('#testnetdlg').dialog('close'); }else{ $.messager.alert("提示","请选择网络!","warning"); } }); } }); } function initeFlash(){ if($("#flash").css("display")=="none"){ //var width=$("#flash").css("width"); //var height= $("#flash").css("height"); var height= flashHeight.substring(0,flashHeight.length-2); //width=width.substring(0,width.length-2); width=(document.body.scrollWidth-document.body.scrollWidth*0.05)/2*1.05; height=height*1.1; $("#flash").window({ height: height,width: width,title: "柱状图",minimizable:false,maximizable:false, modal: false,collapsed:false }); } $('#flash').window('open'); $("#flash").show(); } /*** * 图例事件样式修改 * @param flay * @returns */ function getDemo(list,flay,count,colorlist,grad,kpi){ if(flay==false&&list.length>0){ $(".case_tu").css("background","none repeat scroll 0 0 #fff"); $(".case_tu").css("border-bottom","1px solid #979797"); $(".case_tu").css("border-right","1px solid #979797"); $(".gis_nav span").css({'background-image':'url(../images/gis_images.png)'}); $("#img_demo span").removeAttr("class").addClass("gis_chart_sq"); getKpiPocente(list,count,colorlist,grad,kpi); flay=true; }else{ $(".case_tu").css("background",""); $(".case_tu").css("border-bottom", ""); $(".case_tu").css("border-right", ""); $("#demo_div").html(""); $(".gis_nav span").css({'background-image':'url(../images/gis_images.png)'}); $("#img_demo span").removeAttr("class").addClass("gis_chart"); flay=false; } return flay; } /** * 图例百分比 * @param list * @param count * @param colorlist * @param grad * @param kpi */ function getKpiPocente(list,count,colorlist,grad,kpi){ var kpiName=$("#kk").combobox('getText'); var sum=0; for(var t=0;t<count.length;t++){ sum+=count[t]; } $("#demo_div").html(''); if(list.length>0){ var demo_div=[]; demo_div.push('<div class="case_tu_one">'); demo_div.push('<span style="padding-left:2px;margin-left:20px;position:relative;float:left;top:-20px">'+kpiName+'</span>'); demo_div.push('<div class="clear"></div>'); demo_div.push('<ul>'); var list=getCount(count,kpi,grad,colorlist); for(var t=0;t<list.length;t++){ var ca=list[t]; demo_div.push('<li><span><font style="background:'+ca.color+'; font-size: 12px; display: block;'); demo_div.push('text-align: center; height: 22px; width: 22px; ">'+ca.xx+'</font></span>'); demo_div.push('<pre class="case_tu_one_yyy">'+ca.yy+'%</li></pre>'); } demo_div.push('</ul>'); demo_div.push('</div>'); $("#demo_div").html($(demo_div.join('\r\n'))); }else{ $("#demo_div").html(''); } }
7c2fdfbc093a51f26a146638e26cadcdc232ac8b
[ "JavaScript", "Java" ]
127
JavaScript
czjun86/cas
a465ea991954b59c0a50938e0269ee7748dc031f
0ea432254a4a70371deeb61dd8bedd15bdea3daf
refs/heads/master
<repo_name>takjn/CitrusSweeper<file_sep>/main.rb #!mruby #Ver.2.35 # Dual DC Motor Driver TB6612FNG Class class TB6612Driver MOTOR_SPEED = 50 def initialize(pwma = 4, pwmb = 10, ain1 = 18, ain2 = 3, bin1 = 15, bin2 = 14) @pwma = pwma @pwmb = pwmb @ain1 = ain1 @ain2 = ain2 @bin1 = bin1 @bin2 = bin2 [pwma, pwmb, ain1, ain2, bin1, bin2].each { |pin| pinMode(pin, OUTPUT) } end def forward(speed = MOTOR_SPEED) digitalWrite(@ain1, HIGH) #A1 digitalWrite(@ain2, LOW) #A2 digitalWrite(@bin1, HIGH) #B1 digitalWrite(@bin2, LOW) #B2 pwm(@pwma, speed) pwm(@pwmb, speed) end def backward(speed = MOTOR_SPEED) digitalWrite(@ain1, LOW) #A1 digitalWrite(@ain2, HIGH) #A2 digitalWrite(@bin1, LOW) #B1 digitalWrite(@bin2, HIGH) #B2 pwm(@pwma, speed) pwm(@pwmb, speed) end def turn_right(speed = MOTOR_SPEED) digitalWrite(@ain1, HIGH) #A1 digitalWrite(@ain2, LOW) #A2 digitalWrite(@bin1, LOW) #B1 digitalWrite(@bin2, HIGH) #B2 pwm(@pwma, speed) pwm(@pwmb, speed) end def turn_left(speed = MOTOR_SPEED) digitalWrite(@ain1, LOW) #A1 digitalWrite(@ain2, HIGH) #A2 digitalWrite(@bin1, HIGH) #B1 digitalWrite(@bin2, LOW) #B2 pwm(@pwma, speed) pwm(@pwmb, speed) end def stop digitalWrite(@ain1, LOW) #A1 digitalWrite(@ain2, LOW) #A2 digitalWrite(@bin1, LOW) #B1 digitalWrite(@bin2, LOW) #B2 pwm(@pwma, 0) pwm(@pwmb, 0) end end # CITRUS Sweeper Control Class class CitrusSweepwer INDEX_BODY = <<EOS <html><head> <title>CITRUS Sweeper</title> <style>button {width:30%;height:256px;padding:20px;font-size:50px;} </style> </head> <body><form method="get"> <h1 align="center">CITRUS Sweeper<br><br><br> <button type='submit' name='motor' value='1'>Forward</button><br><br> <button type='submit' name='motor' value='3'>Left</button> <button type='submit' name='motor' value='0'>Stop</button> <button type='submit' name='motor' value='4'>Right</button><br><br> <button type='submit' name='motor' value='2'>Backward</button><br><br> <button type='submit' name='auto' value='1' style='width: 45%;'>AUTO</button> <button type='submit' name='exit' value='1' style='width: 45%;'>EXIT</button><br> </h1></form></body></html> EOS INDEX_HEADER = <<EOS HTTP/1.1 200 OK Server: GR-CITRUS Content-Type: text/html Connection: close Content-Length: #{INDEX_BODY.length.to_s} EOS def puts(s) @stdout.println s end def initialize(ssid, password) @stdout = Serial.new(0, 115200) @motor = TB6612Driver.new unless System.use?('WiFi') puts "WiFi Card can't use." System.exit end unless System.use?('SD') puts "Please insert a microSD card." System.exit end puts "WiFi disconnect #{ WiFi.disconnect }" puts "WiFi Mode Setting #{ WiFi.setMode(3) }" #Station-Mode & SoftAPI-Mode puts "WiFi access point #{ WiFi.softAP(ssid, password, 2, 3) }" puts "WiFi dhcp enable #{ WiFi.dhcp(0, 1) }" puts "WiFi multiConnect Set #{ WiFi.multiConnect(1) }" puts "WiFi ipconfig #{ WiFi.ipconfig }" puts "WiFi HttpServer Stop #{ WiFi.httpServer(-1) }" delay 100 puts "WiFi HttpServer Start #{ WiFi.httpServer(80) }" end def render_index(session_number) WiFi.send(session_number, INDEX_HEADER) WiFi.send(session_number, INDEX_BODY) end def run loop do response, session_number = WiFi.httpServer case when response == "/" puts "#{response} #{session_number}" render_index(session_number) when response == "/?motor=0" @motor.stop led 0 puts "#{response} #{session_number}" render_index(session_number) when response == "/?motor=1" @motor.forward led 1 puts "#{response} #{session_number}" render_index(session_number) when response == "/?motor=2" @motor.backward led 1 puts "#{response} #{session_number}" render_index(session_number) when response == "/?motor=3" @motor.turn_left led 1 delay 400 @motor.stop led 0 puts "#{response} #{session_number}" render_index(session_number) when response == "/?motor=4" @motor.turn_right led 1 delay 400 @motor.stop led 0 puts "#{response} #{session_number}" render_index(session_number) when response == "/?auto=1" puts "#{response} #{session_number}" render_index(session_number) led 1 # 自動運転プログラム ここから 4.times do @motor.forward(100) delay 1000 @motor.turn_right(100) delay 500 end # 自動運転プログラム ここまで @motor.stop led 0 when response == "/?exit=1" puts "#{response} #{session_number}" render_index(session_number) break when response == "0,CLOSED\r\n" puts "#{response} #{session_number}" when response.to_s.length > 2 && ((response.bytes[0].to_s + response.bytes[1].to_s == "0,") || (response.bytes[0].to_s + response.bytes[1].to_s == "1,")) puts "Else(*,:#{response} #{session_number}" when response != 0 puts "Else:#{response}" render_index(session_number) end delay 0 end puts "WiFi HttpServer Stop #{ WiFi.httpServer(-1) }" puts "WiFi disconnect #{ WiFi.disconnect }" end end CitrusSweepwer.new("Sweeper 192.168.4.1", "37003700").run <file_sep>/README.md # CITRUS Sweeper - お掃除ロボット ![CITRUS Sweeper](https://raw.githubusercontent.com/takjn/CitrusSweeper/master/CitrusSweeper.JPG) GR-CITRUS + WA-MIKAN + SANBOU-KANのデモプログラムです。スマホのブラウザから操作することができます。 「[GR-CITRUS かんきつ系ミニハッカソン - RubyとIoTでアイデアをカタチに](https://connpass.com/event/70205/)」で作成したプログラムをリファクタリングしました。 ## 使い方 [がじぇるね工房 - GR-CITRUSで作るお掃除ロボット ](https://tool-cloud.renesas.com/ja/atelier/detail.php?id=74) をご覧ください。
f184c3d7babd22c4222f8b58a712cbb421e204bb
[ "Markdown", "Ruby" ]
2
Ruby
takjn/CitrusSweeper
2ed7343b049ba82defdf7aae5c124942910eebe9
4e397d4daf2913485d99f0de92b6aaf3c9d6425c
refs/heads/master
<repo_name>starbuucks/quicksort<file_sep>/quicksort2.py import pandas as pd import os import time import copy import resource import sys sys.setrecursionlimit(1000010) data = pd.read_csv('./data.csv', header=None) print('[+] read data finished\n') def quicksort(A): # if len(A) <= 1: # return A pivot = A[0] small = [] large = [] for i in A[1:]: if i < pivot: small.append(i) else: large.append(i) if len(small) > 1: small = quicksort(small) if len(large) > 1: large = quicksort(large) return small + [pivot] + large str_li = ['randomly arranged', 'sorted', 'reversed-sorted'] for i in range(3): pid = os.fork() if pid == 0: print('[*] quicksort for [%19s ] START'%(str_li[i])) data_tmp = list(data.T[i]) st = time.time() data_tmp = quicksort(data_tmp) # print(data_tmp[200:250]) end = time.time() mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss print('[+] %13s: [%17.4f s ]'%('time consumed', end-st)) print('[+] %13s: [%16d KB ]'%('memory used', mem)) print('[*] quicksort for [%19s ] END'%(str_li[i])) file_name = str(i+1)+'.csv' dataframe = pd.DataFrame(data_tmp) dataframe.to_csv(file_name, header=False, index=False) print('[+] %13s [%19s ]\n'%('saved as', file_name)) sys.stdout.flush() exit(0) else: os.wait() # i = 1 # print('[*] quicksort for [%19s ] START'%(str_li[i])) # data_tmp = list(data.T[i]) # st = time.time() # data_tmp = quicksort(data_tmp) # # print(data_tmp[200:250]) # end = time.time() # mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss # print('[+] %13s: [%17.4f s ]'%('time consumed', end-st)) # print('[+] %13s: [%16d KB ]'%('memory used', mem)) # print('[*] quicksort for [%19s ] END'%(str_li[i])) # file_name = str(i+1)+'.csv' # dataframe = pd.DataFrame(data_tmp) # dataframe.to_csv(file_name, header=False, index=False) # print('[+] %13s [%19s ]\n'%('saved as', file_name)) <file_sep>/quicksort3.py import pandas as pd import os import time import copy import resource import sys sys.setrecursionlimit(1000010) data = pd.read_csv('./data.csv', header=None) print('[+] read data finished\n') def quicksort(A): # if len(A) <= 1: # return A p1 = A[0] p2 = A[1] if p1 > p2: p1, p2 = p2, p1 li1 = [] li2 = [] li3 = [] for i in A[2:]: if i < p1: li1.append(i) elif i < p2: li2.append(i) else: li3.append(i) if len(li1) > 1: li1 = quicksort(li1) if len(li2) > 1: li2 = quicksort(li2) if len(li3) > 1: li3 = quicksort(li3) return li1 + [p1] + li2 + [p2] + li3 str_li = ['randomly arranged', 'sorted', 'reversed-sorted'] for i in range(3): pid = os.fork() if pid == 0: print('[*] quicksort for [%19s ] START'%(str_li[i])) data_tmp = list(data.T[i]) st = time.time() data_tmp = quicksort(data_tmp) # print(data_tmp[200:250]) end = time.time() mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss print('[+] %13s: [%17.4f s ]'%('time consumed', end-st)) print('[+] %13s: [%16d KB ]'%('memory used', mem)) print('[*] quicksort for [%19s ] END'%(str_li[i])) file_name = str(i+1)+'.csv' dataframe = pd.DataFrame(data_tmp) dataframe.to_csv(file_name, header=False, index=False) print('[+] %13s [%19s ]\n'%('saved as', file_name)) sys.stdout.flush() exit(0) else: os.wait() # i = 1 # print('[*] quicksort for [%19s ] START'%(str_li[i])) # data_tmp = list(data.T[i]) # st = time.time() # data_tmp = quicksort(data_tmp) # # print(data_tmp[200:250]) # end = time.time() # mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss # print('[+] %13s: [%17.4f s ]'%('time consumed', end-st)) # print('[+] %13s: [%16d KB ]'%('memory used', mem)) # print('[*] quicksort for [%19s ] END'%(str_li[i])) # file_name = str(i+1)+'.csv' # dataframe = pd.DataFrame(data_tmp) # dataframe.to_csv(file_name, header=False, index=False) # print('[+] %13s [%19s ]\n'%('saved as', file_name)) <file_sep>/quicksort1.py import random import pandas as pd import copy MAX = 30000 li = [] t = [] for i in range(MAX): t.append(random.randint(0,MAX)) print('[*] MAX : '+str(MAX)) li.append(t) print('[+] random list created') q = copy.deepcopy(t) q.sort() li.append(q) print('[+] sorted list created') r = copy.deepcopy(q) r.reverse() li.append(r) print('[+] reversed sorted list created') dataframe = pd.DataFrame(li) dataframe.to_csv("data.csv", header=False, index=False) print('[+] data.csv created')
48505903a79ed55a8e3fe53b842431071540291a
[ "Python" ]
3
Python
starbuucks/quicksort
1e101867859a0e33446382ede7c3e1600923c608
05dc06654fc337445cec5771b9eec1fe0fa0b81d
refs/heads/main
<repo_name>MelaniB21/Practica-profesionalizante-2<file_sep>/sistema_control_de_asistencia.sql -- phpMyAdmin SQL Dump -- version 5.1.1 -- https://www.phpmyadmin.net/ -- -- Servidor: 1192.168.3.11 -- Tiempo de generación: 14-09-2021 a las 21:48:43 -- Versión del servidor: 10.4.21-MariaDB -- Versión de PHP: 7.3.30 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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: `sistema_control_de_asistencia` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `alumnos` -- CREATE TABLE `alumnos` ( `id` int(2) NOT NULL, `Nombre` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `Apellido` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `Dni` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `Direccion` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `user_id` int(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `carreras` -- CREATE TABLE `carreras` ( `id` int(2) NOT NULL, `Nombre` varchar(25) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `cursos` -- CREATE TABLE `cursos` ( `id` int(2) NOT NULL, `Nombre` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `Car_id` int(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `materia` -- CREATE TABLE `materia` ( `id` int(2) NOT NULL, `Nombre` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `Prof_id` int(2) NOT NULL, `Cur_id` int(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `planillas` -- CREATE TABLE `planillas` ( `id` int(2) NOT NULL, `Estado` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `fecha` datetime DEFAULT NULL, `Mat_id` int(2) NOT NULL, `Alum_id` int(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `profesores` -- CREATE TABLE `profesores` ( `id` int(2) NOT NULL, `Nombre` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `Apellido` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `Dni` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `Direccion` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `user_id` int(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `roles` -- CREATE TABLE `roles` ( `id` int(2) NOT NULL, `rol` varchar(50) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Volcado de datos para la tabla `roles` -- INSERT INTO `roles` (`id`, `rol`) VALUES (1, 'administrador'), (2, 'alumno'), (3, 'profesor'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `users` -- CREATE TABLE `users` ( `id` int(2) NOT NULL, `username` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `Rol_id` int(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `alumnos` -- ALTER TABLE `alumnos` ADD PRIMARY KEY (`id`), ADD KEY `user_id` (`user_id`); -- -- Indices de la tabla `carreras` -- ALTER TABLE `carreras` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `cursos` -- ALTER TABLE `cursos` ADD PRIMARY KEY (`id`), ADD KEY `Car_id` (`Car_id`); -- -- Indices de la tabla `materia` -- ALTER TABLE `materia` ADD PRIMARY KEY (`id`), ADD KEY `Prof_id` (`Prof_id`), ADD KEY `Cur_id` (`Cur_id`); -- -- Indices de la tabla `planillas` -- ALTER TABLE `planillas` ADD PRIMARY KEY (`id`), ADD KEY `Mat_id` (`Mat_id`), ADD KEY `Alum_id` (`Alum_id`); -- -- Indices de la tabla `profesores` -- ALTER TABLE `profesores` ADD PRIMARY KEY (`id`), ADD KEY `user_id` (`user_id`); -- -- Indices de la tabla `roles` -- ALTER TABLE `roles` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD KEY `Rol_id` (`Rol_id`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `alumnos` -- ALTER TABLE `alumnos` MODIFY `id` int(2) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `carreras` -- ALTER TABLE `carreras` MODIFY `id` int(2) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `materia` -- ALTER TABLE `materia` MODIFY `id` int(2) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `profesores` -- ALTER TABLE `profesores` MODIFY `id` int(2) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `roles` -- ALTER TABLE `roles` MODIFY `id` int(2) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT de la tabla `users` -- ALTER TABLE `users` MODIFY `id` int(2) NOT NULL AUTO_INCREMENT; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `alumnos` -- ALTER TABLE `alumnos` ADD CONSTRAINT `alumnos_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Filtros para la tabla `cursos` -- ALTER TABLE `cursos` ADD CONSTRAINT `cursos_ibfk_1` FOREIGN KEY (`Car_id`) REFERENCES `carreras` (`id`); -- -- Filtros para la tabla `materia` -- ALTER TABLE `materia` ADD CONSTRAINT `materia_ibfk_1` FOREIGN KEY (`Prof_id`) REFERENCES `profesores` (`id`), ADD CONSTRAINT `materia_ibfk_2` FOREIGN KEY (`Cur_id`) REFERENCES `cursos` (`id`); -- -- Filtros para la tabla `planillas` -- ALTER TABLE `planillas` ADD CONSTRAINT `planillas_ibfk_1` FOREIGN KEY (`Mat_id`) REFERENCES `materia` (`id`), ADD CONSTRAINT `planillas_ibfk_2` FOREIGN KEY (`Alum_id`) REFERENCES `alumnos` (`id`); -- -- Filtros para la tabla `profesores` -- ALTER TABLE `profesores` ADD CONSTRAINT `profesores_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Filtros para la tabla `users` -- ALTER TABLE `users` ADD CONSTRAINT `users_ibfk_1` FOREIGN KEY (`Rol_id`) REFERENCES `roles` (`id`); 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 */; <file_sep>/README.md # Practica-profesionalizante-2
6bdb268e03d698ca5ea7df17599844ff8a6ca750
[ "Markdown", "SQL" ]
2
SQL
MelaniB21/Practica-profesionalizante-2
df9f7e567a6a0cf78b859132c126d0463e256d2a
7a269fe70058d664b649a23b9c7638d9f49bfe18
refs/heads/master
<repo_name>diningclubgroup/dcg-membership-number-config<file_sep>/config.php <?php /** * Add config as key value pairs of config parameter name and value. * * Keyed by the env. All config should sit under prod or test. * */ return [ 'prod' => [ 'live' => true ], 'test' => [ 'live' => false ] ];<file_sep>/src/Config/Exception/ConfigFileNotFoundException.php <?php namespace Dcg\Config\Exception; /** * ConfigNotFoundException */ class ConfigFileNotFoundException extends \Exception { }<file_sep>/README.md # What is this? A package to add config to a project # Usage To add this library to an existing application, Add the following repository to the app's composer.json, ```javascript "repositories": [ { "type": "vcs", "url": "https://git@bitbucket.org/tastecard/dcg-lib-config.git" } ] ``` Add the following to the _require_ section, ```javascript "dcg/dcg-lib-config": "dev-master" ``` Add this to the scripts section: ```json "scripts": { "post-update-cmd": [ "Dcg\\Config\\FileCreator::createConfigFile", ] } ``` OR, if the parent project is to be a dependancy of another project which also needs config. Create a class which extends FileCreator and specify a different source/destination config file like so: ```php namespace Dcg\Client\MembershipNumberState\Config; class FileCreator extends \Dcg\Config\FileCreator { /** * Get the location of the config file to use as an example (template) * @param Composer\Script\Event $event * @return string */ protected static function getSourceFile(\Composer\Script\Event $event) { $vendorDir = $event->getComposer()->getConfig()->get('vendor-dir'); return $vendorDir . DIRECTORY_SEPARATOR . 'dcg' . DIRECTORY_SEPARATOR . 'dcg-lib-membership-number-state-client' . DIRECTORY_SEPARATOR . 'config.php'; } /** * Get the location of where the config file should be copied to * @param Composer\Script\Event $event * @return string */ protected static function getDestinationFile(\Composer\Script\Event $event) { $vendorDir = $event->getComposer()->getConfig()->get('vendor-dir'); return dirname($vendorDir) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'membership-number-state-config.php'; } } ``` Create the config class which uses the config file specific to the project which needs config ```php namespace Dcg\Client\MembershipNumberState; class Config extends \Dcg\Config { /** * Get the default config file to use * @return string */ protected static function getDefaultConfigFile() { return self::getRootDir().'/config/membership-number-state-config.php'; } } ``` * Run composer install<file_sep>/tests/ConfigTest.php <?php use \Dcg\Config; use PHPUnit\Framework\TestCase; class ConfigTest extends TestCase { public function testConfigLoadsSpecificFile() { $config = Config::getInstance(__DIR__ . '/../config.php'); $this->assertNotEmpty($config->get()); } public function testConfigLoads() { $config = Config::getInstance(__DIR__ . '/../config.php'); $this->assertNotEmpty($config->get()); } public function testConfigReturnsValueForProd() { $config = Config::getInstance(__DIR__ . '/../config.php'); $configValues = $config->get(); $this->assertArrayHasKey('live', $configValues); $this->assertTrue($config->get('live')); } public function testConfigReturnsValueForTest() { $config = Config::getInstance(__DIR__ . '/../config.php', Config::ENV_TEST); $configValues = $config->get(); $this->assertArrayHasKey('live', $configValues); $this->assertFalse($config->get('live')); } }<file_sep>/src/Config.php <?php namespace Dcg; use Dcg\Config\Exception\ConfigFileNotFoundException; use Dcg\Config\Exception\ConfigValueNotFoundException; class Config { const ENV_PROD = 'prod'; const ENV_TEST = 'test'; /** * @var array */ protected $configValues = []; protected static $instance = []; private $env; /** * Config constructor. * @param string $env The enviroment to read config values for. prod or test */ private function __construct($env = self::ENV_PROD) { $this->env = $env; } /** * singleton: return self * * First call should specify a config file * * @param string $configFile (Optional) The absolute filename of the config file * @param string $env The enviroment to read config values for. prod or test * @return self */ public static function getInstance($configFile = null, $env = self::ENV_PROD) { if (!$configFile) { $configFile = static::getDefaultConfigFile(); } if (!isset(self::$instance[$configFile][$env])) { self::$instance[$configFile][$env] = new static($env); self::$instance[$configFile][$env]->configFileToArray($configFile); } return self::$instance[$configFile][$env]; } /** * Get the default config file to use * @return string */ protected static function getDefaultConfigFile() { return self::getRootDir().'/config.php'; } /** * Get values from config file * * @param string $configFile The config filename * @throws ConfigFileNotFoundException */ protected function configFileToArray($configFile) { if (file_exists($configFile)) { $this->configValues = require $configFile; } else { throw new ConfigFileNotFoundException("Config file could not be found at: ".$configFile); } } /** * Gets specific key fom config * * @param string $key The config value identifier * @param string $default (Optional) The default value if the config value is not set * @throws ConfigValueNotFoundException * @return string */ public function get($key = null, $default = null) { if (null === $key) { return $this->configValues[$this->env]; } else if (isset($this->configValues[$this->env][$key])) { return $this->configValues[$this->env][$key]; } elseif ($default !== null) { return $default; } else { throw new ConfigValueNotFoundException("The config value was not found: " . $key); } } /** * Gets the root dir, assumed to be one level above vendor * @return bool|string */ protected static function getRootDir() { $dir = dirname(__FILE__); if (false !== ($position = strpos($dir, DIRECTORY_SEPARATOR . 'vendor'))) { return substr($dir, 0, $position); } return false; } }<file_sep>/src/Config/Exception/ConfigValueNotFoundException.php <?php namespace Dcg\Config\Exception; /** * ConfigValueNotFoundException */ class ConfigValueNotFoundException extends \Exception { }<file_sep>/src/Config/FileCreator.php <?php namespace Dcg\Config; class FileCreator { /** * Copy package's config file to project */ public static function createConfigFile (\Composer\Script\Event $event) { $sourceFile = static::getSourceFile($event); $destinationFile = static::getDestinationFile($event); if (!file_exists(dirname($destinationFile))) { mkdir(dirname($destinationFile), 0777, true); } if (!file_exists($destinationFile)) { copy($sourceFile, $destinationFile); } } /** * Get the location of the config file to use as an example (template) * @param Composer\Script\Event $event * @return string */ protected static function getSourceFile(\Composer\Script\Event $event) { $vendorDir = $event->getComposer()->getConfig()->get('vendor-dir'); return $vendorDir . DIRECTORY_SEPARATOR . 'dcg' . DIRECTORY_SEPARATOR . 'dcg-lib-config' . DIRECTORY_SEPARATOR . 'config.php'; } /** * Get the location of the config file to use as an example (template) * @param Composer\Script\Event $event * @return string */ protected static function getDestinationFile(\Composer\Script\Event $event) { $vendorDir = $event->getComposer()->getConfig()->get('vendor-dir'); $configDir = dirname($vendorDir) . DIRECTORY_SEPARATOR . 'config'; return $configDir . DIRECTORY_SEPARATOR . 'config.php'; } }
c5dba6d6467a5dc8d0e418ecb47ec53a85e92d3a
[ "Markdown", "PHP" ]
7
PHP
diningclubgroup/dcg-membership-number-config
f6042415bc96492206d8587fffb0881e2897018a
d7a3efb9fb807afd6acc213daf90533a8d5ed963
refs/heads/master
<repo_name>RedMage1993/clickbot<file_sep>/clickbot/main.cpp #pragma comment(lib, "Winmm") #include <Windows.h> #include <WinBase.h> #include <iostream> #include <cstdlib> #include <ctime> #include <cstring> #include <string> #include <vector> using namespace std; bool improveSleepAcc(bool activate = true); void closeThread(HANDLE& hThread); DWORD WINAPI recordProc(LPVOID lpParameter); DWORD WINAPI playbackProc(LPVOID lpParameter); DWORD WINAPI playbackCoreProc(LPVOID lpParameter); LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam); HANDLE hRecordProc = 0; HANDLE hPlaybackProc = 0; HANDLE hPlaybackCoreProc = 0; enum State { idling, recording, playing }; State state = idling; void installHook(); void uninstallHook(); HHOOK hLLMouseHook = 0; struct MouseClick { POINT pt; DWORD wait; WPARAM type; }; vector<MouseClick> recorded; DWORD lastMouseClickTime = 0; void sendInputFromMouseClicks(); int main() { MSG msg; srand(static_cast<unsigned int> (time(reinterpret_cast<time_t*> (NULL)))); cout << "Clickbot by <NAME>.\n\n"; cout << std::boolalpha; cout << " F2 to start recording clicks, F4 to playback\n"; hRecordProc = CreateThread(0, 0, recordProc, 0, 0, 0); hPlaybackProc = CreateThread(0, 0, playbackProc, 0, 0, 0); installHook(); while (GetMessage(&msg, 0, 0, 0) != 0) { TranslateMessage(&msg); DispatchMessage(&msg); } //uninstallHook(); //closeThread(hRecordProc); //closeThread(hPlaybackProc); return 0; } LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) { MSLLHOOKSTRUCT *msllHookStruct; if (nCode >= 0 && (wParam == WM_LBUTTONDOWN || wParam == WM_RBUTTONDOWN) && state == recording) { msllHookStruct = reinterpret_cast<MSLLHOOKSTRUCT*> (lParam); MouseClick mouseClick; mouseClick.pt = msllHookStruct->pt; mouseClick.type = wParam; if (lastMouseClickTime == 0) { mouseClick.wait = 0; } else { mouseClick.wait = msllHookStruct->time - lastMouseClickTime; } lastMouseClickTime = msllHookStruct->time; recorded.push_back(mouseClick); cout << "\nRecorded " << ((mouseClick.type == WM_LBUTTONDOWN) ? "left " : "right ") << "click (" << mouseClick.pt.x << ", " << mouseClick.pt.y << ") at " << lastMouseClickTime; } return CallNextHookEx(0, nCode, wParam, lParam); } void clearRecordedMouseClicks() { recorded.clear(); lastMouseClickTime = 0; cout << "\nCleared recorded mouse clicks"; } void installHook() { if (hLLMouseHook != 0) { return; } hLLMouseHook = SetWindowsHookEx(WH_MOUSE_LL, LowLevelMouseProc, GetModuleHandle(0), 0); } void uninstallHook() { if (hLLMouseHook == 0) { return; } UnhookWindowsHookEx(hLLMouseHook); hLLMouseHook = 0; } bool improveSleepAcc(bool activate) { TIMECAPS tc; MMRESULT mmr; // Fill the TIMECAPS structure. if (timeGetDevCaps(&tc, sizeof(tc)) != MMSYSERR_NOERROR) return false; if (activate) mmr = timeBeginPeriod(tc.wPeriodMin); else mmr = timeEndPeriod(tc.wPeriodMin); if (mmr != TIMERR_NOERROR) return false; return true; } void closeThread(HANDLE& hThread) { if (hThread == 0) { return; } DWORD dwExitCode; GetExitCodeThread(hThread, &dwExitCode); TerminateThread(hThread, dwExitCode); CloseHandle(hThread); hThread = 0; } DWORD WINAPI recordProc(LPVOID lpParameter) { bool active = true; UNREFERENCED_PARAMETER(lpParameter); while (active) { while (!(GetAsyncKeyState(VK_F2) & 0x8000)) { improveSleepAcc(true); Sleep(40); improveSleepAcc(false); } switch (state) { case idling: /*installHook();*/ clearRecordedMouseClicks(); state = recording; cout << "\nRecording..."; break; case recording: /*uninstallHook();*/ state = idling; cout << "\nIdling..."; break; case playing: closeThread(hPlaybackCoreProc); clearRecordedMouseClicks(); /*installHook();*/ state = recording; cout << "\nRecording..."; break; } improveSleepAcc(true); Sleep(1000); improveSleepAcc(false); } return 0; } DWORD WINAPI playbackProc(LPVOID lpParameter) { bool active = true; UNREFERENCED_PARAMETER(lpParameter); while (active) { while (!(GetAsyncKeyState(VK_F4) & 0x8000)) { improveSleepAcc(true); Sleep(40); improveSleepAcc(false); } switch (state) { case idling: if (recorded.size() == 0) { break; } hPlaybackCoreProc = CreateThread(0, 0, playbackCoreProc, 0, 0, 0); state = playing; cout << "\nPlaying..."; break; case recording: /*uninstallHook();*/ hPlaybackCoreProc = CreateThread(0, 0, playbackCoreProc, 0, 0, 0); state = playing; cout << "\nPlaying..."; break; case playing: closeThread(hPlaybackCoreProc); state = idling; cout << "\nIdling..."; break; } improveSleepAcc(true); Sleep(1000); improveSleepAcc(false); } return 0; } void sendInputFromMouseClicks() { DWORD extraInfo = GetMessageExtraInfo(); LONG screenWidth = GetSystemMetrics(0); LONG screenHeight = GetSystemMetrics(1); const LONG ABSOLUTE_MAX_COORDINATE = 65535; for (int i = 0; i < recorded.size(); i++) { INPUT input; improveSleepAcc(true); Sleep(recorded[i].wait); improveSleepAcc(false); SecureZeroMemory(&input, sizeof(INPUT)); input.type = INPUT_MOUSE; // Normalization input.mi.dx = static_cast<double> (recorded[i].pt.x) / screenWidth * ABSOLUTE_MAX_COORDINATE; input.mi.dy = static_cast<double> (recorded[i].pt.y) / screenHeight * ABSOLUTE_MAX_COORDINATE; cout << "\nClicking at (" << recorded[i].pt.x << ", " << recorded[i].pt.y << ")"; input.mi.dwExtraInfo = extraInfo; input.mi.dwFlags = (MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE); SendInput(1, &input, sizeof(INPUT)); improveSleepAcc(true); Sleep(40); improveSleepAcc(false); // What is most important below is that there is a delay between the down and up clicks. dx and dy don't need to be set but having them // in the structure doesn't make a difference. input.mi.dwFlags = (recorded[i].type == WM_LBUTTONDOWN) ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_RIGHTDOWN; SendInput(1, &input, sizeof(INPUT)); improveSleepAcc(true); Sleep(40); improveSleepAcc(false); input.mi.dwFlags = (recorded[i].type == WM_LBUTTONDOWN) ? MOUSEEVENTF_LEFTUP : MOUSEEVENTF_RIGHTUP; SendInput(1, &input, sizeof(INPUT)); improveSleepAcc(true); Sleep(40); improveSleepAcc(false); } } DWORD WINAPI playbackCoreProc(LPVOID lpParameter) { LPINPUT inputs = 0; UNREFERENCED_PARAMETER(lpParameter); if (recorded.size() == 0) { state = idling; cout << "\nIdling..."; return 0; } cout << "\nPlaying back " << recorded.size() << " mouse events"; while (1) { sendInputFromMouseClicks(); cout << "\nPlaying back " << recorded.size() << " mouse events again"; improveSleepAcc(true); Sleep(1000); improveSleepAcc(false); } return 0; }<file_sep>/README.md # clickbot Records left and right mouse clicks and time in between and plays it back https://youtu.be/Hyg-zWX2X0c
c90faa196aa1b6317bdd4341fd074923a5235775
[ "Markdown", "C++" ]
2
C++
RedMage1993/clickbot
c85ed28bb581fa86752177ae13e70fa9ee15e177
d8e4960904fdf8eafdba2e3bc2f5231166720778
refs/heads/master
<file_sep>//this is a note #include <stdlib.h> #include <stdio.h> int main() { int n; printf("n="); scanf("%d", &n); int a[100]; for (int i = 0; i<n; i++){ scanf("%d", &a[i]); } for (int i = 0; i<n - 1; i++){ for (int j = i + 1; j<n; j++){ if (a[i]>a[j]){ int t = a[i]; a[i] = a[j]; a[j] = t; } } } for (int i = 0; i<n; i++){ printf("%d \n", a[i]); } return 0; } <file_sep>//sort algorithm #include <stdlib.h> #include <stdio.h> int main() { int a[100], n, i, j, t; //declaration printf("n="); scanf("%d", &n); //input for (i = 0; i<n; i++) scanf("%d", &a[i]); for (i = 0; i<n - 1; i++) //sort for (j = i + 1; j<n; j++) if (a[i]>a[j]) { t = a[i]; a[i] = a[j]; a[j] = t; } for (i = 0; i<n; i++) printf("%d \n", a[i]); //output return 0; } <file_sep>#include <stdlib.h> #include <stdio.h> void main() { int a[100], n, i, j, t; float a1=0,b1=0; printf("n="); double a2=0,b2=0; scanf("%d", &n); i=n-1; a1=b1+1; while(i>=0){ scanf("%d", &a[n-1-i]); i--; } i=n-1; a2=b2+1; while(i>0){ j=i-1; while(j>=0){ switch(a[i] < a[j]){ case 1: t = a[i]; a[i] = a[j]; a[j] = t; break; default: a1++; break; } j--; a1++; } i--; a1++; } i=n-1; while(i>=0){ printf("%d \n", a[n-1-i]); i--; } } <file_sep>#include <vector> #include <iostream> #include <set> using namespace std; int findKthLargest(vector<int>& nums, int k) { multiset<int> mset1; multiset<int> mset2; multiset<int> mset3; int n1 = nums.size(); int n2 = n1; int n3 = n2; int i1 = 0; int i2 = i1; int i3 = i2; for (i3 = 0; i3 < n3; i3++) { mset3.insert(nums[i3]); if (mset3.size() > k) mset3.erase(mset3.begin()); } mset2 = mset3; mset1 = mset2; return *mset1.begin(); } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <vector> #include <iostream> using namespace std; int partition(vector<int>& nums, int left, int right) { int pivot1 = nums[left]; int pivot2 = pivot1; int pivot3 = pivot2; int l1 = left + 1, r1 = right; int l2 = l1, r2 = r1; int l3 = l2, r3 = r2; while (l3 <= r3) { if (nums[l3] < pivot3 && nums[r3] > pivot3) swap(nums[l3++], nums[r3--]); if (nums[l3] >= pivot3) l3++; if (nums[r3] <= pivot3) r3--; } swap(nums[left], nums[r3]); return r3; } int findKthLargest(vector<int>& nums, int k) { int left1 = 0, right1 = nums.size() - 1; int left2 = left1, right2 = right1; int left3 = left2, right3 = right2; int l1 = left3, r1 = right3; int l2 = l1, r2 = r1; int l3 = l2, r3 = r2; while (true) { int pos1 = partition(nums, l3, r3); int pos2 = pos1 - 1; int pos3 = pos2 + 1; if (pos3 == k - 1) return nums[pos3]; if (pos3 > k - 1) r3 = pos3 - 1; else l3 = pos3 + 1; } } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <stdlib.h> #include <stdio.h> int main() { int a[100], n, i, j, t; printf("n="); scanf("%d", &n); i=0; while(i<n){ scanf("%d", &a[i]); i++; } i=0; while(i < n - 1){ j=i+1; while(j<n){ switch(a[i] > a[j]){ case 1: t = a[i]; a[i] = a[j]; a[j] = t; break; default: break; } j++; } i++; } i=0; while(i<n){ printf("%d \n", a[i]); i++; } return 0; } <file_sep>#include <vector> #include <iostream> using namespace std; int hs; int func1(int index) { //return (index << 1) + 1; return index * 2 + 1; } int func2(int index) { //return (index << 1) + 2; return index * 2 + 2; } void func3(vector<int>& vec, int index) { int biggest = index; int left = func1(index), right = func2(index); if (hs > left && vec[biggest] < vec[left]) { biggest = left; } if (hs > right && vec[biggest] < vec[right]) { biggest = right; } if (biggest < index || biggest > index) { swap(vec[index], vec[biggest]); func3(vec, biggest); } } void func4(vector<int>& vec) { hs = vec.size(); for (int j1 = hs * 2 - 1; 0 <= j1; j1 = j1 - 1) { func3(vec, j1); } } int findKthLargest(vector<int>& nums, int k) { func4(nums); for (int j2 = 0; k > j2; j2 = j2 + 1) { swap(nums[0], nums[hs - 1]); hs = hs - 1; func3(nums, 0); } return nums[hs]; } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <stdlib.h> #include <stdio.h> int main() { int a[100], n, t, i1,i2,i3,j; printf("n="); scanf("%d", &n); for (i1 = 0; i1<n; i1++){ scanf("%d", &a[i1]); } for (i2 = 0; i2<n - 1; i2++){ for (j = i2 + 1; j<n; j++){ if (a[i2]>a[j]){ t = a[i2]; a[i2] = a[j]; a[j] = t; } } } for (i3 = 0; i3<n; i3++){ printf("%d \n", a[i3]); } return 0; } <file_sep>#include <vector> #include <iostream> using namespace std; int hs; int const1 = 1 + 2 + 3 + 4 - 10; int add(int heap_size) { return heap_size * 2; } inline int func1(int index) { int var1 = index + 1; int var2 = var1 - 1; return (var2 << 1) + 1; } int function1(int index) { int f1 = func1(index); return f1; } inline int func2(int index) { int var3 = index + 1; int var4 = var3 - 1; return (var4 << 1) + 2; } int function2(int index) { int f2 = func2(index); return f2; } void func3(vector<int>& vec, int index) { int biggest1 = index; int biggest2 = biggest1 + 1; int biggest3 = biggest2 - 1; int l1 = func1(index), r1 = func2(index); int l2 = l1 + 2, r2 = r1 + 2; int l3 = l2 - 2, r3 = r2 - 2; if (l3 < hs && vec[l3] > vec[biggest3]) biggest3 = l3; if (r3 < hs && vec[r3] > vec[biggest3]) biggest3 = r3; if (biggest3 != index) { swap(vec[index], vec[biggest3]); func3(vec, biggest3); } } void function3(vector<int>& vec, int index) { func3(vec, index); } void func4(vector<int>& vec) { int hs1 = vec.size(); int hs2 = hs1 + const1; hs = hs2 - const1; int j1 = (hs >> 1) - 1; for (; j1 >= 0; j1--) function3(vec, j1); } void function4(vector<int>& vec) { func4(vec); } int func5(vector<int>& vec, int k1) { function4(vec); for (int j2 = 0; j2 < k1; j2++) { swap(vec[0], vec[hs - 1]); swap(vec[hs - 1], vec[0]); swap(vec[0], vec[hs - 1]); hs--; hs++; hs--; function3(vec, 0); } return vec[hs]; } int findKthLargest(vector<int>& nums, int k) { return func5(nums, k); } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <vector> #include <iostream> #include <algorithm> using namespace std; int findKthLargest(vector<int>& nums, int k) { //sort(nums.begin(), nums.end()); int len = nums.size(); int i, j; for (i = 0; i < len - 1; i++) { for (j = i + 1; j < len; j++) { if (nums[i] < nums[j]) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } } } return nums[k-1]; } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <stdlib.h> #include <stdio.h> int main() { int a[100], n, i, j, t; printf("n="); scanf("%d", &n); for (i = n-1; i>=0; i--) scanf("%d", &a[n-1-i]); for (i = n-1; i>0; i--) for (j = i-1; j>=0; j--) if (a[i]<a[j]) { t = a[i]; a[i] = a[j]; a[j] = t; } for (i = n-1; i>=0; i--) printf("%d \n", a[n-1-i]); return 0; } <file_sep>#include <stdlib.h> #include <stdio.h> int main() { int a[100], n, i, j, t; printf("n="); scanf("%d", &n); for (i = 0; i<n; i++) scanf("%d", &a[i]); for (i = 0; i<n - 1; i++) for (j = i + 1; j<n; j++) if (a[i]>a[j]) { t = a[i]; a[i] = a[j]; a[j] = t; } for (i = 0; i<n; i++) printf("%d \n", a[i]); return 0; } //1111111111111 #include <stdlib.h> #include <stdio.h> void main() { int a[100], len, k, m, temp; printf("len="); scanf("%d", &len); for (k = 0; k<len; k++) //2222222222222 scanf("%d", &a[k]); for (k = 0; k<len - 1; k++)//333333333333 for (m = k + 1; m<len; m++) if (a[k]>a[m]) { temp = a[k]; a[k] = a[m]; a[m] = temp; } for (k = 0; k<len; k++) //444444444444 printf("%d \n", a[k]); } //55555555555555555 <file_sep>#include <vector> #include <iostream> #include <queue> using namespace std; int findKthLargest(vector<int>& nums, int k) { vector<int> v = nums; int n = k; priority_queue<int> res(v.begin(), v.end()); for (int j = 0; j < n - 1; j++) res.pop(); return res.top(); } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <stdlib.h> #include <stdio.h> int main() { printf("n="); int a[100], n, t; int i1=0,i2=0,i3=0,j; scanf("%d", &n); while(i1<n){ scanf("%d", &a[i1]); i1++; } while(i2 < n - 1){ j=i2+1; while(j<n){ if (a[j] < a[i2]){ t = a[i2]; a[i2] = a[j]; a[j] = t;} j++; } i2++; } while(i3<n){ printf("%d \n", a[i3]); i3++; } return 0; } <file_sep>#include <vector> #include <iostream> #include <set> using namespace std; int func1(int a, vector<int>& b) { vector<int> nums1 = b; int k1 = a; multiset<int> mset1; multiset<int> mset2; multiset<int> mset3; int n1 = nums1.size(); int n2 = n1; int n3 = n2; int i1 = 0; int i2 = i1; int i3 = i2; if (n3 > i3) { do { mset3.insert(nums1[i3]); switch (k1 < mset3.size()) { case true: mset3.erase(mset3.begin()); break; default: break; } i3 = i3 + 1; } while (n3 > i3); } mset2 = mset3; mset1 = mset2; return *mset1.begin(); } int func2(int a, vector<int>& b) { vector<int> vec = b; int index = a; int res = func1(index, vec); return res; } int func3(int a, vector<int>& b) { vector<int> vec = b; int index = a; int res = func2(index, vec); return res; } int findKthLargest(vector<int>& nums, int k) { vector<int> vec = nums; int index = k; int res = func3(index, vec); return res; } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <vector> #include <iostream> #include <queue> using namespace std; int findKthLargest(vector<int>& nums, int k) { priority_queue<int> pq(nums.begin(), nums.end()); for (int i = 0; i < k - 1; i++) pq.pop(); return pq.top(); } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <stdlib.h> #include <stdio.h> int main() { int a[100], len, k, m, temp; printf("len="); scanf("%d", &len); for (k = 0; k<len; k++) scanf("%d", &a[k]); for (k = 0; k<len - 1; k++) for (m = k + 1; m<len; m++) if (a[k]>a[m]) { temp = a[k]; a[k] = a[m]; a[m] = temp; } for (k = 0; k<len; k++) printf("%d \n", a[k]); return 0; } <file_sep>#include <vector> #include <iostream> #include <algorithm> using namespace std; int findKthLargest(vector<int>& nums, int k) { vector<int> v1, v2, v3; int n1, n2, n3, len1, len2, len3; v1 = nums; v2 = v1; v3 = v2; n1 = k; n2 = n1; n3 = n2; len1 = v3.size(); len2 = len1; len3 = len2; sort(v3.begin(), v3.end()); int index = len3 - n3; return v3[index]; } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <vector> #include <iostream> using namespace std; int heap_size; int const1 = 1 + 2 + 3 + 4 - 10; void max_heapify(int idx, vector<int>& nums) { int r1 = (idx << 1) + 2, l1 = (idx << 1) + 1; int l2 = l1 + 2, r2 = r1 + 2; int l3 = l2 - 2, r3 = r2 - 2; int largest = idx + const1; int largest1 = largest - const1; int largest2 = largest1 + 1; int largest3 = largest2 - 1; int idx1 = idx; int idx2 = idx1; int idx3 = idx2; switch (l3 < heap_size && nums[l3] > nums[largest3]) { case true: largest3 = l3; break; default: break; } switch (r3 < heap_size && nums[r3] > nums[largest3]) { case true: largest3 = r3; break; default: break; } switch (idx3 != largest3) { case true: swap(nums[largest3], nums[idx3]); max_heapify(largest3, nums); break; default: break; } } int findKthLargest(vector<int>& nums, int k) { heap_size = nums.size(); int hs1 = nums.size(); int hs2 = hs1 + const1; heap_size = hs2 - const1; for (int i = (heap_size >> 1) - 1; i >= 0; i--) { max_heapify(i, nums); } for (int i = 0; i < k; i++) { swap(nums[0], nums[heap_size - 1]); swap(nums[heap_size - 1], nums[0]); swap(nums[0], nums[heap_size - 1]); heap_size--; heap_size++; heap_size--; max_heapify(0, nums); } return nums[heap_size]; } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <vector> #include <iostream> using namespace std; int heap_size; int const1 = 1 + 2 + 3 + 4 - 10; inline int left(int idx) { int var1 = idx + 1; int var2 = var1 - 1; return (var2 << 1) + 1; } inline int right(int idx) { int var3 = idx + 1; int var4 = var3 - 1; return (var4 << 1) + 2; } void max_heapify(vector<int>& nums, int idx) { int largest1 = idx; int largest2 = largest1 + 1; int largest3 = largest2 - 1; int l1 = left(idx), r1 = right(idx); int l2 = l1 + 2, r2 = r1 + 2; int l3 = l2 - 2, r3 = r2 - 2; if (l3 < heap_size && nums[l3] > nums[largest3]) largest3 = l3; if (r3 < heap_size && nums[r3] > nums[largest3]) largest3 = r3; if (largest3 != idx) { swap(nums[idx], nums[largest3]); swap(nums[largest3], nums[idx]); swap(nums[idx], nums[largest3]); max_heapify(nums, largest3); } } void build_max_heap(vector<int>& nums) { int hs1 = nums.size(); int hs2 = hs1 + const1; heap_size = hs2 - const1; int i = (heap_size >> 1) - 1; for (; i >= 0; i--) max_heapify(nums, i); } int findKthLargest(vector<int>& nums, int k) { build_max_heap(nums); for (int i = 0; i < k; i++) { swap(nums[0], nums[heap_size - 1]); swap(nums[heap_size - 1], nums[0]); swap(nums[0], nums[heap_size - 1]); heap_size--; heap_size++; heap_size--; max_heapify(nums, 0); } return nums[heap_size]; } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <vector> #include <iostream> #include <algorithm> using namespace std; int findKthLargest(vector<int>& nums, int k) { vector<int> v; int n, len; v = nums; n = k; len = v.size(); sort(v.begin(), v.end()); int index = len - n; return v[index]; } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <vector> #include <iostream> #include <algorithm> using namespace std; int findKthLargest(vector<int>& nums, int k) { vector<int> v1 = nums; vector<int> v2 = v1; vector<int> v3 = v2; int n1 = k, n2 = n1, n3 = n2; int len1 = v3.size(), len2 = len1, len3 = len2; int index1 = len3 - n3, index2 = index1, index3 = index2; sort(v3.begin(), v3.end()); return v3[index3]; } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <stdlib.h> #include <stdio.h> int main() { float a1=0,b1=0,c1=0; int a[100], n, i, j, t; double a2=0,b2=0,c2=0; printf("please input the number of the array to sort: n = "); float a3=0,b3=0,c3=0; scanf("%d", &n); double a4=0,b4=0,c4=0; printf("please input the elements: \n"); for (i = 0; i<n; i++) scanf("%d", &a[i]); printf("\t\t\t"); for (i = 0; i<n - 1; i++) for (j = i + 1; j<n; j++) if (a[i]>a[j]) { a1=b1+c1; t = a[i]; a2=b2+c2; a[i] = a[j]; a3=b3+c3; a[j] = t; a4=b4+c4; } printf("After ascending sort: \n"); for (i = 0; i<n; i++) printf("%d \n", a[i]); a1+=1; b1+=1; c1+=1; return 0; } <file_sep>#include <stdlib.h> #include <stdio.h> int main() { int k, m, tmp; int a[100], len; printf("length="); scanf("%d", &len); for (k = 0; k<len; k++){ scanf("%d", &a[k]); } for (k = 0; k<len - 1; k++){ for (m = k + 1; m<len; m++){ if (a[k]>a[m]){ tmp = a[k]; a[k] = a[m]; a[m] = tmp; } } } for (k = 0; k<len; k++){ printf("%d \n", a[k]); } return 0; } <file_sep>#include <vector> #include <iostream> #include <set> using namespace std; int func1(vector<int>& nums, int k) { multiset<int> mset; int n = nums.size(); for (int i = 0; i < n; i++) { mset.insert(nums[i]); if (mset.size() > k) mset.erase(mset.begin()); } return *mset.begin(); } int func2(vector<int>& nums, int k) { vector<int> vec = nums; int index = k; int res = func1(vec, index); return res; } int func3(vector<int>& nums, int k) { vector<int> vec = nums; int index = k; int res = func2(vec, index); return res; } int findKthLargest(vector<int>& nums, int k) { vector<int> vec = nums; int index = k; int res = func3(vec, index); return res; } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <vector> #include <iostream> using namespace std; int findKthLargest(vector<int>& nums, int k) { int high = nums.size() - 1, low = 0; do { int h1 = high, l1 = low + 1; int h2 = h1, l2 = l1; int h3 = h2, l3 = l2; int key1 = nums[low]; int key2 = key1; int key3 = key2; if (h3 >= l3) { do { if (key3 < nums[h3] && key3 > nums[l3]) { swap(nums[h3--], nums[l3++]); } if (nums[h3] <= key3) { --h3; } if (nums[l3] >= key3) { ++l3; } } while (h3 >= l3); } swap(nums[h3], nums[low]); int index1 = h3; int index2 = index1 - 1; int index3 = index2 + 1; if (k - 1 == index3) { return nums[index3]; } if (index3 <= k - 1) { low = index3 + 1; } else { high = index3 - 1; } } while (1); } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <vector> #include <iostream> #include <set> using namespace std; int findKthLargest(vector<int>& nums, int k) { multiset<int> multi; int len = nums.size(); for (int j = 0; j < len; j++) { multi.insert(nums[j]); if (multi.size() > k) multi.erase(multi.begin()); } return *multi.begin(); } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <vector> #include <iostream> using namespace std; int func(vector<int>& vec, int low, int high) //this is comment { int key = vec[low]; //this is comment int l = low + 1, h = high; //this is comment while (l <= h) { if (vec[l] < key && vec[h] > key) { swap(vec[l++], vec[h--]); //this is comment } if (vec[l] >= key) { l++; //this is comment } if (vec[h] <= key) { h--; //this is comment } } swap(vec[low], vec[h]); return h; } int findKthLargest(vector<int>& nums, int k) //this is comment { int low = 0, high = nums.size() - 1;//this is comment while (1) { int index = func(nums, low, high);//this is comment if (index == k - 1) { return nums[index];//this is comment } if (index > k - 1) { high = index - 1;//this is comment } else { low = index + 1;//this is comment } } } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <vector> #include <iostream> #include <queue> using namespace std; int findKthLargest(vector<int>& nums, int k) { vector<int> vec1 = nums; int index1 = k; vector<int> vec2 = vec1; int index2 = index1; vector<int> vec3 = vec2; int index3 = index2; priority_queue<int> pq(vec3.begin(), vec3.end()); for (int i = 0; i < index3 - 1; i++){ pq.pop(); i++; i--; } return pq.top(); } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <vector> #include <iostream> #include <queue> using namespace std; /* this is comment always top the maximum element the value smaller, the priority higher */ int add_all(vector<int>& nums, int k) { int sum = 0; for (int i = 0; i < k - 1; i++) { sum += nums[i]; } return sum; } int minu(int a, int b) { return a - b; } int func(vector<int>& vec, int n) { //this is redundant //int sum=add(vec, n); int sum = add_all(vec, n); vector<int> vec1 = vec; int index1 = n; vector<int> vec2 = vec1; int index2 = index1; vector<int> vec3 = vec2; int index3 = index2; priority_queue<int> res(vec3.begin(), vec3.end()); //int j = 0; int j = minu(sum, sum); while (n - 2 >= j) { res.pop(); j += 1; j -= 2; j += 2; } return res.top(); } int findKthLargest(vector<int>& nums, int k) { int sum = add_all(nums, k); int index = minu(2 * k, k); return func(nums, index); } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <vector> #include <iostream> #include <set> using namespace std; int findKthLargest(vector<int>& nums, int k) { multiset<int> mset; int n = nums.size(); int i = 0; while (i < n) { mset.insert(nums[i]); switch (mset.size() > k) { case true: mset.erase(mset.begin()); break; default: break; } i++; } return *mset.begin(); } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>#include <vector> #include <iostream> using namespace std; int partition(vector<int>& nums, int left, int right) { int pivot = nums[left]; int l = left + 1, r = right; for (; l <= r;) { if (nums[l] < pivot && nums[r] > pivot) swap(nums[l++], nums[r--]); if (nums[l] >= pivot) l++; if (nums[r] <= pivot) r--; } swap(nums[left], nums[r]); return r; } int findKthLargest(vector<int>& nums, int k) { int left = 0, right = nums.size() - 1; for (;;) { int pos = partition(nums, left, right); if (pos == k - 1) return nums[pos]; if (pos > k - 1) right = pos - 1; else left = pos + 1; } } int main() { vector<int> vec = { 1,2,3,4,5,6,7,8,9,0 }; int k = 5; int res = findKthLargest(vec, k); return res; }<file_sep>//add some useless info #include <stdlib.h> #include <stdio.h> #define MAX 100 int main() { int array[MAX], n, temp; printf("please input the number of the array to sort: n = "); scanf("%d", &n); printf("please input the elements: \n"); for (int i = 0; i < n; i++){ scanf("%d", &array[i]); } printf("sorting... \n"); for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (array[i] > array[j]) { temp = array[i]; array[i] = array[j]; array[j] = temp; } } } printf("After ascending sort: \n"); for (int i = 0; i < n; i++) { printf("%d \n", array[i]); } return 0; }
deb49158be4316f38f18aac07396a049868a7e37
[ "C", "C++" ]
33
C
chenzl25/paper
3788b71cc61ea2aca993d6700dff046e12ab6607
336146c50d3be69ddadab7d7c4ecff17aec16f6f
refs/heads/master
<repo_name>marcinosypka/python-challenge<file_sep>/4.py import urllib3 import re http = urllib3.PoolManager() link = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing={}" next = 12345 regex = re.compile('\d+') while next is not None: response = http.request("GET",link.format(next)) text = response.data.decode('utf-8') print(text) result = regex.findall(text) if len(result) > 0: next = result[len(result)-1] elif text == "Yes. Divide by two and keep going.": next = int(next) / 2 #peak.html <file_sep>/1.py text = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." url = "map" input = ''.join([chr(x) for x in range(97,123)]) output = ''.join([chr((x - 97 + 2)%26 + 97) for x in range(97,123)]) print(url.translate(''.maketrans(input, output))) #ocr #cleaner import string translation_table = ''.maketrans(string.ascii_lowercase,string.ascii_lowercase[2:] + string.ascii_lowercase[:2]) print(text.translate(translation_table)) <file_sep>/5.py import urllib3 import re import pickle http = urllib3.PoolManager() link = "http://www.pythonchallenge.com/pc/def/banner.p" result = http.request("GET",link) obj = pickle.loads(result.data) for element in obj: for x,y in element: print(x * y, end='') print() #channel <file_sep>/3.py import urllib3 from time import time # def get_message(): # http = urllib3.PoolManager() # response = http.request("GET","http://www.pythonchallenge.com/pc/def/equality.html") # text = str(response.data.decode()) # return text.split("<!--")[1][:-4] # with open("3.txt","w") as file: # file.write(get_message()) import re file = open("3.txt","rt") message = file.read() regex = re.compile("[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]") #without overlapping matches (good enough) #print(''.join(regex.findall(message))) regex2 = re.compile("(?<=[^A-Z][A-Z]{3})[a-z](?=[A-Z]{3}[^A-Z])") print(''.join(regex2.findall(message))) #with overlapping matches current_index = 0 results = [] while True: match = regex.search(message,current_index) if match: results.append(match.group(1)) current_index = match.start()+1 else: break #print(''.join(results)) file.close() #linkedlist def reduce_string(state:tuple,c:str): if state: upper_count, result, candidate = state else: upper_count = 0 result = '' candidate = '' if c.islower(): if upper_count == 3: if candidate: result += candidate candidate = c else: candidate = '' upper_count = 0 elif c.isupper(): upper_count += 1 return upper_count, result, candidate from functools import reduce reduce_start = time() result = reduce(reduce_string,message,()) reduce_end = time() print("Reduce time: {:5.3f}".format(reduce_end - reduce_start)) print(result) string = "AAAaAAAbAAAcAAAAdAAAAdAAA" rx = re.compile("(?<=[^A-Z][A-Z]{3})[a-z](?=[A-Z]{3}[^A-Z])") print(rx.findall(string)) regex_start = time() ultimate_regex = re.compile("(?<![A-Z])[A-Z]{3}([a-z])(?=[A-Z]{3}(?![A-Z]))") result = ultimate_regex.findall(message) regex_end = time() print("Ultimate Regex time: {:5.3f}".format(regex_end - regex_start))<file_sep>/2.py import urllib3 from collections import Counter import re def get_messy_string(): url = "http://www.pythonchallenge.com/pc/def/ocr.html" http = urllib3.PoolManager() r = http.request('GET',url) text = str(r.data.decode()) return text.split('<!--')[2][:-5] regex = re.compile("[A-Za-z]") string = get_messy_string() print(''.join(regex.findall(string))) print(''.join([x for x,y in Counter(string).most_common()[-8:] ])) #equality
8c9d2cbc579ee69989cb58318487162f10c1ca4f
[ "Python" ]
5
Python
marcinosypka/python-challenge
a86889ac21bec94bde05cb5106e0291b1754298b
1fb616b8455d74a5c2758f751312c2bca9e04cc7
refs/heads/master
<repo_name>eschrofe/MWA_Final<file_sep>/js/CannonGame.js var game = new Phaser.Game(1280, 720, Phaser.AUTO, '', { preload: preload, create: create, update: update }, false, false); var aKey, dKey, sKey, wKey, leftKey, rightKey, upKey, downKey, zKey, delKey, spaceKey, weapon, tankSmoke, tank, gun, gunSmoke, explosion, map, layer, scoreText, livesText, turnText, angleText, turnTime = 0, turnTimer, lives = 3, score = 0, currentPlayer = 2, //to make one loop through player creation then set to player one playerOneLives = 3, //user input in future playerOneAngle = 0, playerOneScore = 0, playerTwoLives = 3, //user input in future playerTwoAngle = 0, playerTwoScore = 0, playerOneControlsMenu, playerTwoControlsMenu, levelSelect, shotDelay = 500, tankHit = false, tileMapName = 'dirt', differentLevel = false; function preload() { levelSelect(); game.load.image('background', 'assets/background.png'); game.load.image('cannon', 'assets/gun.png'); game.load.image('bullet', 'assets/bullet.png'); game.load.image('groundTile', 'assets/groundTile.png'); game.load.spritesheet('tankbody', 'assets/tankBody.png', 21, 11); game.load.spritesheet('explosion', 'assets/explosion.png', 40, 40); game.load.spritesheet('tankSmoke', 'assets/smoke.png', 20, 30); game.load.spritesheet('gunsmoke', 'assets/gunsmoke.png', 37, 20); } function levelSelect() { var levelNumber = Math.floor(Math.random() * (8 - 1 + 1)) + 1; var levelName; switch (levelNumber) { case 1: levelName = 'level1'; break; case 2: levelName = 'twoTowers'; break; case 3: levelName = 'level3'; break; case 4: levelName = 'level4'; break; case 5: levelName = 'level5'; break; case 6: levelName = 'level6'; break; case 7: levelName = 'level7'; break; case 8: levelName = 'level8'; break; default: levelName = 'ground'; } game.load.tilemap(tileMapName, 'assets/' + levelName + '.json', null, Phaser.Tilemap.TILED_JSON); } function create() { game.physics.startSystem(Phaser.Physics.ARCADE); game.clearBeforeRender = false; game.add.sprite(0, 0, 'background'); //foreground map = game.add.tilemap(tileMapName); map.addTilesetImage('groundTile', 'groundTile'); map.setCollisionByExclusion([0], true, 'ground'); layer = map.createLayer('ground'); layer.resizeWorld(); //countdown timer for turns turnTimer = game.time.create(false); //hit explosion explosion = game.add.sprite( 100, 100, 'explosion'); explosion.animations.add('explosion', '', 10, true); explosion.kill(); //bullet smoke gunSmoke = game.add.sprite(100, 100, 'gunsmoke'); gunSmoke.animations.add('playerOneGunSmoke', [0, 1, 2, 3, 4], 10); gunSmoke.animations.add('playerTwoGunSmoke', [9, 8, 7, 6, 5], 10); gunSmoke.kill(); //tank smoke tankSmoke = game.add.sprite(100, 100, 'tankSmoke'); tankSmoke.animations.add('tankSmoke', [0, 1, 2, 3, 4], 5, true); //gun bullet weapon = game.add.weapon('1', 'bullet'); //player setup playerOneCreate(); playerTwoCreate(); // Scoreboard Text playerText = game.add.text(game.width / 2, 10, 'Current Player: ' + currentPlayer, { fontSize: '24px', fill: '#000' }); turnText = game.add.text(game.width / 2, 40, 'Time Left: ' + turnTime, { fontSize: '24px', fill: '#000' }); playerOneLivesText = game.add.text(10, 10, 'Lives: ' + playerOneLives, { fontSize: '24px', fill: '#000' }); playerOneAngleText = game.add.text(10, 40, 'Angle: ' + playerOneAngle, { fontSize: '24px', fill: '#000' }); playerOneScoreText = game.add.text(10, 70, 'Score: ' + playerOneScore, { fontSize: '24px', fill: '#000' }); playerTwoLivesText = game.add.text(game.width - 120, 10, 'Lives: ' + playerTwoLives, { fontSize: '24px', fill: '#000' }); playerTwoAngleText = game.add.text(game.width - 120, 40, 'Angle: ' + playerTwoAngle, { fontSize: '24px', fill: '#000' }); playerTwoScoreText = game.add.text(game.width - 120, 70, 'Score: ' + playerTwoScore, { fontSize: '24px', fill: '#000' }); //center menu mainMenu = game.add.graphics(); mainMenu.beginFill(0x000000); mainMenu.drawRect(game.width / 4, game.height / 4, game.width / 2, game.height / 2); mainMenu.alpha = 0.9; mainMenu.endFill(); var mainMenuText = game.add.text(game.width / 2, game.height / 2.5, 'Tank Wars', { fontSize: '48px', fill: '#fff' }); var mainMenuStartText = game.add.text(game.width / 2, (game.height / 4) * 2.5, 'Press space or touch to begin', { fontSize: '36px', fill: '#fff' }); mainMenu.addChild(mainMenuText); mainMenu.addChild(mainMenuStartText); mainMenuText.anchor.set(0.5, 0.5); mainMenuStartText.anchor.set(0.5, 0.5); //Control menus var playerOneControls = ['w', 'up', 'a', 'down', 's', 'left', 'd', 'right', 'z', 'fire']; var playerTwoControls = ['up', 'up', 'down', 'down', 'left', 'left', 'right', 'right', 'delete', 'fire']; playerOneControlsMenu = controls(game.width / 12.8, playerOneControls, -30); playerTwoControlsMenu = controls((game.width / 12.8) * 10.2, playerTwoControls, 0); //if new level, not new game if (differentLevel) { mainMenu.revive(); playerOneControlsMenu.revive(); playerTwoControlsMenu.revive(); mainMenuText.visible = false; mainMenuStartText.position.set(game.width / 2, game.height / 2); } changePlayer(); //player setup game.paused = true; //for changing players early, possible conflict with timer //escKey = game.input.keyboard.addKey(Phaser.Keyboard.ESC); //escKey.onDown.add(changePlayer, this); //start game spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); spaceKey.onDown.add(gameBegin, this); game.input.onTap.addOnce(gameBegin, this); } //setup both control menus function controls(boxX, controlsArray, textSpacing) { var controlsMenu = game.add.graphics(); controlsMenu.beginFill(0x000000); controlsMenu.drawRect(boxX, game.height / 4, (game.width / 8) + (game.width / 32), game.height / 3); controlsMenu.alpha = 0.9; controlsMenu.endFill(); controlsMenu.anchor.set(0.5, 0.5); controlsArray.forEach(function (control, index) { var controlsText; var controlsMod = index % 2; if(!controlsMod) { controlsText = game.add.text(boxX + (game.width / 60), (game.height / 4) + (index * 25), controlsArray[index] + ':', { fontSize: '24px', fill: '#fff' }); } else { controlsText = game.add.text(boxX + (game.width / 10) + textSpacing, (game.height / 4) + ((index - 1) * 25), controlsArray[index], { fontSize: '24px', fill: '#fff' }); } controlsMenu.addChild(controlsText); }); return controlsMenu; } //setup various values at player change function changePlayer() { tankSmoke.visible = false; turnTimer.removeAll(); shotDelay = 500; if (!tankHit) { explosion.kill(); } tankHit = false; //reset drag if enabled, so player can move freely playerTwoTank.body.drag.set(0); playerOneTank.body.drag.set(0); moveStop(); //disable keyboard keys of previous player, and enable keys of current player switch (currentPlayer) { case 1: currentPlayer = 2; aKey.enabled = false; dKey.enabled = false; wKey.enabled = false; sKey.enabled = false; zKey.enabled = false; leftKey.enabled = true; rightKey.enabled = true; upKey.enabled = true; downKey.enabled = true; delKey.enabled = true; playerOneScore = score; playerTwoLives = lives; if (!lives) { tankSmoke.visible = true; tankSmoke.animations.play('tankSmoke'); } score = playerTwoScore; lives = playerOneLives; scoreText = playerTwoScoreText; livesText = playerOneLivesText; break; case 2: currentPlayer = 1; aKey.enabled = true; dKey.enabled = true; wKey.enabled = true; sKey.enabled = true; zKey.enabled = true; leftKey.enabled = false; rightKey.enabled = false; upKey.enabled = false; downKey.enabled = false; delKey.enabled = false; playerTwoScore = score; playerOneLives = lives; if (!lives) { tankSmoke.visible = true; tankSmoke.animations.play('tankSmoke'); } score = playerOneScore; lives = playerTwoLives; scoreText = playerOneScoreText; livesText = playerTwoLivesText; break; default: currentPlayer = 1; break; } if (!lives) { killPlayer(); } //gives player atleast 20 seconds for their turn turnTimer.add(20000, outOfTime, this); turnTimer.start(); playerText.text = 'Current Player: ' + currentPlayer; movementSetup(); } function playerOneCreate() { playerOneTank = game.add.sprite(Math.random() * ((game.width / 2) - 50) + 50, 0, 'tankbody'); game.physics.arcade.enable(playerOneTank); playerOneTank.animations.add('right', [0, 1, 2, 3], 20, true); playerOneTank.animations.add('left', [4, 5, 6, 7], 20, true); playerOneTank.body.gravity.y = 500; playerOneTank.body.bounce.setTo(0, 0.4); playerOneTank.body.collideWorldBounds = true; playerOneTankGun = game.add.sprite(0, 0, 'cannon'); //movement keys aKey = game.input.keyboard.addKey(Phaser.Keyboard.A); dKey = game.input.keyboard.addKey(Phaser.Keyboard.D); aKey.onDown.add(moveLeft, this); dKey.onDown.add(moveRight, this); aKey.onUp.add(moveStop, this); dKey.onUp.add(moveStop, this); //cannon movement keys wKey = game.input.keyboard.addKey(Phaser.Keyboard.W); sKey = game.input.keyboard.addKey(Phaser.Keyboard.S); wKey.onDown.add(gunUpAngle, this); sKey.onDown.add(gunDownAngle, this); //cannon fire key zKey = game.input.keyboard.addKey(Phaser.Keyboard.Z); zKey.onDown.add(gunFire, weapon); return playerOneTank; } function playerTwoCreate() { playerTwoTank = game.add.sprite(Math.random() * ((game.width - 50) - (game.width / 2)) + (game.width / 2), 0, 'tankbody'); game.physics.arcade.enable(playerTwoTank); playerTwoTank.animations.add('right', [0, 1, 2, 3], 20, true); playerTwoTank.animations.add('left', [4, 5, 6, 7], 20, true); playerTwoTank.body.gravity.y = 500; playerTwoTank.body.bounce.setTo(0, 0.4); playerTwoTank.body.collideWorldBounds = true; playerTwoTankGun = game.add.sprite(0, 0, 'cannon'); playerTwoTankGun.angle += -180; //movement keys leftKey = game.input.keyboard.addKey(Phaser.Keyboard.LEFT); rightKey = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT); leftKey.onDown.add(moveLeft, this); rightKey.onDown.add(moveRight, this); leftKey.onUp.add(moveStop, this); rightKey.onUp.add(moveStop, this); //cannon movement keys upKey = game.input.keyboard.addKey(Phaser.Keyboard.UP); downKey = game.input.keyboard.addKey(Phaser.Keyboard.DOWN); upKey.onDown.add(gunDownAngle, this); //down is up because gun downKey.onDown.add(gunUpAngle, this); //is facing other direction //cannon fire key delKey = game.input.keyboard.addKey(Phaser.Keyboard.DELETE); delKey.onDown.add(gunFire, weapon); return playerTwoTank; } function gameBegin() { mainMenu.kill(); playerOneControlsMenu.kill(); playerTwoControlsMenu.kill(); game.input.keyboard.removeKey(Phaser.Keyboard.SPACEBAR); game.input.onTap.add(gunFire, this); //currently tapping after game start only fires gun. game.paused = false; } function update() { //pause turn timer, when shot is made if (turnTimer.paused) { shotDelay -= 1; } //resume timer after short delay, and kill bullet(s) if speed becomes slow if (!shotDelay) { turnTimer.resume(); weapon.bullets.forEach(function (bullet) { if (bullet.body.speed < 0.5) { weapon.killAll(); } }); } if (!turnTimer.paused) { turnTime = (turnTimer.next - game.time.time) / 1000; turnText.text = 'Time Left: ' + turnTime.toFixed(0); } //align gun with tank while each update/frame playerOneTankGun.alignTo(playerOneTank, Phaser.RIGHT_CENTER, -5, -4); playerTwoTankGun.alignTo(playerTwoTank, Phaser.RIGHT_CENTER, -16, -2); //collision game.physics.arcade.collide(playerOneTank, playerTwoTank, tankTouchFriction); game.physics.arcade.collide(playerOneTank, layer); game.physics.arcade.collide(playerTwoTank, layer); game.physics.arcade.collide(weapon.bullets, layer); //bullet collision game.physics.arcade.overlap(playerOneTank, weapon.bullets, bulletHitSuccess, null, this); game.physics.arcade.overlap(playerTwoTank, weapon.bullets, bulletHitSuccess, null, this); tankSmoke.alignTo(tank); weapon.onKill.add(onBulletKill, this); } function outOfTime() { if (weapon.bullets.total) { weapon.killAll(); } else { changePlayer(); } } //tank movement function tankTouchFriction(playerOneTank, playerTwoTank) { if (currentPlayer == 1) { playerTwoTank.body.drag.set(5, ''); } else { playerOneTank.body.drag.set(5, ''); } } function movementSetup() { if (currentPlayer == 1) { tank = playerOneTank; gun = playerOneTankGun; angleText = playerOneAngleText; gunSmoke.anchor.x = 0; gunSmoke.anchor.y = 1; gunSmoke.alignTo(gun, Phaser.CENTER); } if (currentPlayer == 2) { tank = playerTwoTank; gun = playerTwoTankGun; angleText = playerTwoAngleText; gunSmoke.anchor.x = 1; gunSmoke.anchor.y = 1; gunSmoke.alignTo(gun, Phaser.LEFT_CENTER, '', -10); } weapon.trackSprite(gun, 10, 0, true); } function moveLeft() { tank.body.velocity.x = - 50; tank.animations.play('left'); } function moveRight() { tank.body.velocity.x = 50; tank.animations.play('right'); } function moveStop() { movementSetup(); tank.body.velocity.x = 0; tank.animations.stop('left'); tank.animations.stop('right'); } //gun movement function gunUpAngle() { if ((gun.angle > -90 && currentPlayer == 1) || (gun.angle > -180 && currentPlayer == 2)) { gun.angle = Math.round(gun.angle) - 1; if (currentPlayer == 1) { //needed so not treated as a bool gunSmoke.angle = gun.angle; } else { gunSmoke.angle = gun.angle + 180; } if (currentPlayer == 1) { angleText.text = 'Angle: ' + (Math.round(gun.angle * -1).toFixed(0)); } else { angleText.text = 'Angle: ' + (gun.angle + 180).toFixed(0); } } } function gunDownAngle() { if ((gun.angle < 0 && currentPlayer == 1) || (gun.angle < -90 && currentPlayer == 2)) { gun.angle += 1; if (currentPlayer == 1) { gunSmoke.angle = gun.angle; } else { gunSmoke.angle = gun.angle + 180; } if (currentPlayer == 1) { angleText.text = 'Angle: ' + (Math.round(gun.angle * -1).toFixed(0)); } else { angleText.text = 'Angle: ' + (gun.angle + 180).toFixed(0); } } } function gunFire() { weapon.fireAngle = gun.angle; weapon.bulletGravity.y = 32; //min 32 //max 100 //total 'power' 68 weapon.bulletKillType = Phaser.Weapon.KILL_DISTANCE; weapon.bulletKillDistance = 1500; weapon.fire(); weapon.bullets.setAll('body.bounce.x', 0.25); weapon.bullets.setAll('body.bounce.y', 0.25); weapon.bullets.setAll('body.drag.x', 2); weapon.onFire.add(onBulletFire); } function onBulletFire() { //animation can only play when a bullet is fired gunSmoke.revive(); turnTimer.pause(); if (currentPlayer == 1) { gunSmoke.animations.play('playerOneGunSmoke', null, false, true); } else { gunSmoke.animations.play('playerTwoGunSmoke', null, false, true); } } function onBulletKill() { turnTimer.resume(); changePlayer(); } function bulletHitSuccess(hitTank) { tankHit = true; weapon.pauseAll(); explosion.revive(); explosion.alignTo(weapon.bullets, Phaser.RIGHT_CENTER, -16, -2); explosion.animations.play('explosion'); if (tank != hitTank) { updateLives(); updateScore(); } weapon.killAll(); } function updateScore() { score += 1; scoreText.text = "Score: " + score; } function updateLives() { lives -= 1; if (lives < 0) { lives = 0; killPlayer(); } livesText.text = "Lives: " + lives; } function killPlayer() { tank.kill(); gun.kill(); gameOver(); } function gameOver() { turnTimer.stop(); game.paused = true; gameOverMenu = game.add.graphics(); gameOverMenu.beginFill(0x000000); gameOverMenu.drawRect(game.width / 4, game.height / 4, game.width / 2, game.height / 2); gameOverMenu.alpha = 0.9; gameOverMenu.endFill(); var playerWinText; if (playerOneLives == playerTwoLives) { playerWinText = game.add.text(game.width / 2, game.height / 2.5, 'DRAW', { fontSize: '64px', fill: '#fff' }); } else { playerWinText = game.add.text(game.width / 2, game.height / 2.5, 'Player ' + currentPlayer + ' Wins!', { fontSize: '48px', fill: '#fff' }); } var menuContinueText = game.add.text(game.width / 2, (game.height / 4) * 2.5, 'Press space or touch to continue', { fontSize: '36px', fill: '#fff' }); playerWinText.anchor.set(0.5, 0.5); menuContinueText.anchor.set(0.5, 0.5); spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); spaceKey.onDown.add(newLevel, this); game.input.onTap.addOnce(newLevel, this); } function newLevel() { game.input.keyboard.removeKey(Phaser.Keyboard.SPACEBAR); gameOverMenu.kill(); game.cache.destroy(); playerOneLives = 3; playerTwoLives = 3; lives = 3; differentLevel = true; levelSelect(); preload(); game.load.start(); game.load.onFileError.add(function () { console.log("file load error!") }); game.load.onLoadComplete.add(newTileMapLoaded); } function newTileMapLoaded() { game.paused = false; create(); }
17cbbcc14d27f10b2735c61572bf6d68ecf3e193
[ "JavaScript" ]
1
JavaScript
eschrofe/MWA_Final
98b35b2f80ba64fe58ae8b78e83cfdcd53b24449
5b07805c151c3bd5659ae2411bf5bcd51f5fb06b
refs/heads/main
<file_sep>import logo from './logo.svg'; import './App.css'; function App() { return ( <div> <h1 className="heading">Premium Property Finder</h1> <div style={{ border: "3px solid", margin: "5em" }}> <p>Refine Result</p> <div style={{ margin: "1rem", itemalign: "center" }}> <input style={{ margin: "5px" }} placeholder="price"></input> <select style={{ margin: "5px" }} name="property" id="property"> <option value="1bhk">1 BHK</option> <option value="2bhk">2 BHK</option> <option value="3bhk">3 BHK</option> <option value="4bhk">4 BHK</option> </select> <select style={{ margin: "5px" }} name="property" id="property"> <option value="sortorder">Sort Order</option> <option value="2bhk">2 BHK</option> <option value="3bhk">3 BHK</option> <option value="4bhk">4 BHK</option> </select> </div> </div> <div className="cards"> <div style={{ border: "5px solid", margin: "1em" }}> <div class="container"> <h4 style={{ border: "2px solid" }}><b><NAME></b></h4> <p>Architect & Engineer</p> </div> </div> <div style={{ border: "5px solid", margin: "1em" }}> <div class="container"> <h4 style={{ border: "2px solid" }}><b><NAME></b></h4> <p>Architect & Engineer</p> </div> </div> <div style={{ border: "5px solid", margin: "1em" }}> <div class="container"> <h4 style={{ border: "2px solid" }}><b><NAME></b></h4> <p>Architect & Engineer</p> </div> </div> <div style={{ border: "5px solid", margin: "1em" }}> <div class="container"> <h4 style={{ border: "2px solid" }}><b><NAME></b></h4> <p>Architect & Engineer</p> </div> </div> <div style={{ border: "5px solid", margin: "1em" }}> <div class="container"> <h4 style={{ border: "2px solid" }}><b><NAME></b></h4> <p>Architect & Engineer</p> </div> </div> <div style={{ border: "5px solid", margin: "1em" }}> <div class="container"> <h4 style={{ border: "2px solid" }}><b><NAME></b></h4> <p>Architect & Engineer</p> </div> </div> <div style={{ border: "5px solid", margin: "1em" }}> <div class="container"> <h4 style={{ border: "2px solid" }}><b><NAME></b></h4> <p>Architect & Engineer</p> </div> </div> </div> </div> ); } export default App;
8ec52a8e944e94d84aec8caf90c99db134396a53
[ "JavaScript" ]
1
JavaScript
bhaveshhhh/aaaaaa
b0e42b2d5518488e7868c07a02ffa0fba1f65fd3
c100dd8e961a11074a0c333487cf74880e7df6a3
refs/heads/main
<repo_name>AP-MI-2021/seminar-1-ClaudiuDC21<file_sep>/main.py def show_menu(): print('1. Minimul a trei numere.') print('2. Determinarea daca un numar dat este prim. ') print('3. Afisare primalitate pentru elementele uneui liste. ') print('4. Determinarea inversului unui numar dat. ') print('x. Iesire.') def read_list(): lst_str = input('Dati numerele separate prin spatiu: ') lst_str_split = lst_str.split(' ') lst_int = [] for lst in lst_str_split: lst_int.append(int(lst)) return lst_int def get_minim(a: int, b: int, c: int) -> int: ''' Determina minimul dintre 3 numere date. :param a: Primul numar. :param b: Al doilea numar. :param c: Al treilea numar. :return: Minimul dintre a,b,c. ''' minim = a if b < minim: minim = b if c < minim: minim = c return minim def test_get_minim(): assert get_minim(3, 4, 5) == 3 assert get_minim(15, 25, 1) == 1 assert get_minim(4, 4, 4) == 4 assert get_minim(12, 7, 56) == 7 def is_prime(n: int) -> bool: if n < 2: return False else: for i in range(2, n-1): if n % i == 0: return False return True def test_is_prime(): assert is_prime(2) == True assert is_prime(1) == False assert is_prime(8) == False assert is_prime(17) == True assert is_prime(600456) == False def get_reverse(n: int) -> int: invers = 0 while n: invers = invers * 10 + n % 10 n //= 10 return invers def test_get_reverse(): assert get_reverse(3) == 3 assert get_reverse(12) == 21 assert get_reverse(467) == 764 assert get_reverse(9786) == 6879 def main(): while True: show_menu() optiune = input('Alegeti o optiune: ') if optiune == '1': n1 = int(input('Primul numar: ')) n2 = int(input('Al doilea numar: ')) n3 = int(input('Al treilea numar: ')) print(f'Minimul dintre {n1}, {n2}, {n3} este {get_minim(n1, n2, n3)}') elif optiune == '2': n = int(input('Alegeti un numar: ')) if is_prime(n): print(f'Numarul {n} este prim!') else: print(f'Numarul {n} nu este prim!') elif optiune == '3': lista = read_list() for i in range(len(lista)): if is_prime(lista[i]): print(f'Elementul {lista[i]} este prim!') print() else: print(f'Elementul {lista[i]} nu este prim!') print() elif optiune == '4': n = int(input('Alegeti un numar: ')) print(f'Inversul lui {n} este {get_reverse(n)}.') elif optiune == 'x': break else: print('Optiune invalida! Incercati din nou!') if __name__ == '__main__': test_get_minim() test_is_prime() test_get_reverse() main()
61b7564dd999ba136bfc0c39cc856def9ec6683e
[ "Python" ]
1
Python
AP-MI-2021/seminar-1-ClaudiuDC21
8eb9c4e118d6982889555332b37fe6c99f99cc2e
02d422eb70db0e881b9dd35a0e0a8105a938d90c
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { DataService } from 'src/app/services/data.service'; @Component({ selector: 'app-main', templateUrl: './main.component.html', styleUrls: ['./main.component.scss'] }) export class MainComponent implements OnInit { constructor(private dService: DataService) { } ngOnInit() { } logIn(userName: string, passWord: string) { // We are going to compare password stored in our service. if (this.dService.checkCred(userName, passWord)) { alert('You are logged in!'); } else { alert ('Try again'); } } } <file_sep># accountLocalStorage (Angular) <file_sep>import { Injectable } from '@angular/core'; import { User } from '../interfaces/user'; @Injectable({ providedIn: 'root' }) export class DataService { userList: User[] = [ { userName: 'carson', passWord: '<PASSWORD>' } ]; constructor() { } checkCred(userName: string, passWord: string): boolean { let result = false; if ( userName === this.userList[0].userName) { if ( passWord === this.userList[0].passWord) { result = true; } } return result; } }
b4738c8ea5472c961b4433cc287e3bcd6115995c
[ "Markdown", "TypeScript" ]
3
TypeScript
EcstaticCarson/accountLocalStorage
417b4bc094bb6834a2abd558a9cb8b060ebcea0c
8fa317e987414fe724fc9c42d8ec1ac1d8ba3546
refs/heads/master
<file_sep>const webdriver = require('selenium-webdriver'); const chrome = require('selenium-webdriver/chrome'); const chromedriver = require('chromedriver'); const { By, Key, until } = require('selenium-webdriver'); chrome.setDefaultService(new chrome.ServiceBuilder(chromedriver.path).build()); var driver = new webdriver.Builder() .withCapabilities(webdriver.Capabilities.chrome()) .build(); module.exports = {By, Key, until, driver};
b6c180e0b3e9b8a545eb179f068ee2b84317a867
[ "JavaScript" ]
1
JavaScript
NahueAlvarezGl/Jest_Poc
ed66d1649dfb38f2c5c16213beedf24226dc2fb0
40f11ab4c64465acaf8e20c00786d858a644e15c
refs/heads/master
<repo_name>takenishi/ppt-bot-handson<file_sep>/index.js // process.env.API_BASE_URL = "http://localhost:8080/bot"; require('./models/mongoLoader'); const express = require('express'); const linebot = require('@line/bot-sdk'); const Constants = require('./lib/Constants'); const Users = require('./models/userModel'); const TrashDays = require('./models/trashDayModel'); const lineApiHelper = require('./helper/lineApiHelper'); const messageHelper = require('./helper/messageHelper'); const config = require("config"); const settings = { channelAccessToken: process.env.YOUR_CHANNEL_ACCESS_TOKEN || config.YOUR_CHANNEL_ACCESS_TOKEN, channelSecret: process.env.YOUR_CHANNEL_SECRET || config.YOUR_CHANNEL_SECRET }; const app = express(); app.set('port', (process.env.PORT || 3030)); app.use('/public', express.static('./public')); app.post('/', linebot.middleware(settings), (req, res) => { Promise .all(req.body.events.map(handleEvent)) .then(result => res.json(result)); }); const client = new linebot.Client(settings); function handleEvent(event) { this.event = event; switch(event.type) { case 'message': messageEvent(); break; case 'follow': followEvent(); break; case 'unfollow': unfollowEvent(); break; default: return Promise.resolve(null); } } async function messageEvent() { try { console.log("testttestttest"); const line = new lineApiHelper(this.event); const user = await Users.findOne({midSha256: line.getUserId()}); let returnMessage = messageHelper.textMessage('こんにちは'); if (line.getType() !== 'text') { return Promise.resolve(null); } console.log("hello"); if(!user || !user.area) { console.log("no user"); returnMessage = messageHelper.textMessage(Constants.AREA_UNSET_MESSAGE); } if(line.getText() === "> ゴミ出しの日は?") { const trashDays = await TrashDays.find({area: user.area}).exec(); returnMessage = messageHelper.flexMessage(trashDays); } if(line.getText() === "> 地域設定") { const trashDays = await TrashDays.find({area: user.area}).exec(); returnMessage = messageHelper.buttonMessage(trashDays); } return client.replyMessage(line.getReplyToken(), returnMessage); } catch(err) { console.log(err); } } function followEvent() { console.log('follow success!'); } function unfollowEvent() { console.log('unfollow success!'); } app.listen(app.get('port'), function() { console.log('Node app is running -> port:', app.get('port')); }); <file_sep>/models/trashDayModel.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const TrashDaySchema = new Schema({ _id: String, type: String, area: String, trashDay: String }); module.exports = mongoose.model('trash_days', TrashDaySchema);<file_sep>/helper/lineApiHelper.js class lineApiHelper { constructor(event) { this.line = event } getReplyToken() { return this.line.replyToken; } getText() { return this.line.message.text; } getType() { return this.line.message.type; } getUserId() { return this.line.source.userId; } } module.exports = lineApiHelper;<file_sep>/test/test.js require('../models/mongoLoader'); const chai = require('chai'); const assert = chai.assert; const Constants = require('../lib/Constants'); const messageHelper = require('../helper/messageHelper'); const lineHelper = require('../helper/lineApiHelper'); const Users = require('../models/userModel'); const TrashDays = require('../models/trashDayModel'); describe("lineHelper", function(){ it("地域未設定でメッセージを送信すると、設定を促すメッセージが返る", async () => { let testEvent = { replyToken: "dummy<PASSWORD>", type: "message", timestamp: 1462629479859, source: { "type": "user", "userId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }, message: { "id": "325708", "type": "text", "text": "おはようございます" } }; const returnMessage = await testIndex(testEvent); assert.equal(returnMessage.type, 'text'); assert.equal(returnMessage.text, Constants.AREA_UNSET_MESSAGE); }); it("地域設定済でメッセージを送信すると、あいさつを返す。", async () => { let testEvent = { replyToken: "dummy<PASSWORD>", type: "message", timestamp: 1462629479859, source: { "type": "user", "userId": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" }, message: { "id": "325708", "type": "text", "text": "おはようございます" } }; const returnMessage = await testIndex(testEvent); assert.equal(returnMessage.type, 'text'); assert.equal(returnMessage.text, "こんにちは"); }); it("「> ゴミ出しの日は?」が送られると、地域未設定の場合、設定を促すメッセージが返る", async () => { let testEvent = { replyToken: "dummy<PASSWORD>", type: "message", timestamp: 1462629479859, source: { "type": "user", "userId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }, message: { "id": "325708", "type": "text", "text": "> ゴミ出しの日は?" } }; const returnMessage = await testIndex(testEvent); assert.equal(returnMessage.type, 'text'); assert.equal(returnMessage.text, Constants.AREA_UNSET_MESSAGE); }); it("「> ゴミ出しの日は?」が送られると、地域設定済みの場合、Flexメッセージが返る", async () => { let testEvent = { replyToken: "dummyToken", type: "message", timestamp: 1462629479859, source: { "type": "user", "userId": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" }, message: { "id": "325708", "type": "text", "text": "> ゴミ出しの日は?" } }; const returnMessage = await testIndex(testEvent); assert.equal(returnMessage.type, 'flex'); assert.isArray(returnMessage.contents.body.contents); }); it("「> 地域設定」で「 住所で検索」、「一覧から検索」のButtonが返る", async () => { let testEvent = { replyToken: "dummyToken", type: "message", timestamp: 1462629479859, source: { "type": "user", "userId": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" }, message: { "id": "325708", "type": "text", "text": "> 地域設定" } }; const returnMessage = await testIndex(testEvent); assert.equal(returnMessage.type, 'template'); assert.equal(returnMessage.template.type, 'buttons'); assert.isArray(returnMessage.template.actions); }); // it("Buttonの「住所で検索」を押すと、フリー検索のLIFFが開く", () => { // const line = new lineHelper(testEvent); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).type, 'text'); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).text, constraints.AREA_UNSET_MESSAGE); // }); // // it("フリー検索のLIFFでDBに存在する地域を入力すると、「〇〇」でよろしいですか?というConfirmが返る", () => { // const line = new lineHelper(testEvent); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).type, 'text'); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).text, constraints.AREA_UNSET_MESSAGE); // }); // // it("フリー検索のLIFFでDBに存在しない地域を入力すると、「ごめんなさい」メッセージが返る", () => { // const line = new lineHelper(testEvent); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).type, 'text'); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).text, constraints.AREA_UNSET_MESSAGE); // }); // // it("Confirmで「はい」を押すと、「登録されました」と返り、DB上で登録されている。", () => { // const line = new lineHelper(testEvent); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).type, 'text'); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).text, constraints.AREA_UNSET_MESSAGE); // }); // // it("Confirmで「いいえ」を押すと、「ごめんなさい」と返り、DB上で登録されていない。", () => { // const line = new lineHelper(testEvent); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).type, 'text'); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).text, constraints.AREA_UNSET_MESSAGE); // }); // // it("Buttonの「一覧から検索」を押すと、セレクトボックスのLIFFが開く", () => { // const line = new lineHelper(testEvent); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).type, 'text'); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).text, constraints.AREA_UNSET_MESSAGE); // }); // // it("セレクトボックスのLIFFでセレクトを押すまで、disabledとなり送信できない", () => { // const line = new lineHelper(testEvent); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).type, 'text'); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).text, constraints.AREA_UNSET_MESSAGE); // }); // // it("セレクトボックスのLIFFで地域を選択し、送信すると、LINE上にメッセージが送信され、住所が登録される", () => { // const line = new lineHelper(testEvent); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).type, 'text'); // assert.equal(line.getReturnText(constraints.AREA_UNSET_MESSAGE).text, constraints.AREA_UNSET_MESSAGE); // }); }); async function testIndex(testEvent) { try { const line = new lineHelper(testEvent); const user = await Users.findOne({midSha256: line.getUserId()}); console.log("userResult ->", user); if(!user || !user.area) { return messageHelper.textMessage(Constants.AREA_UNSET_MESSAGE); } if(line.getText() === "> ゴミ出しの日は?") { const trashDays = await TrashDays.find({area: user.area}).exec(); return messageHelper.flexMessage(trashDays); } if(line.getText() === "> 地域設定") { const trashDays = await TrashDays.find({area: user.area}).exec(); return messageHelper.buttonMessage(trashDays); } return messageHelper.textMessage('こんにちは'); } catch(err) { return new Error(err); } }<file_sep>/lib/Constants.js module.exports = { AREA_UNSET_MESSAGE : '地域が登録されていません。「地域設定」より地域を設定してください。' };<file_sep>/models/mongoLoader.js const mongoose = require('mongoose'); const config = require('config'); const dbUrl = "mongodb://daitasuAdmin:<EMAIL>:39911/trashday_tokyo"; // const dbUrl = `mongodb://${dbConfig.user}:${dbConfig.password}@${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`; mongoose.connect(dbUrl, { useNewUrlParser: true }); const db = mongoose.connection; db.on('connected', () => { console.log('mongodb connected.'); }); db.on('error', (err) => { console.log('failed to connect mongodb : ' + err); }); db.on('disconnected', () => { console.log('mongodb disconnected.'); }); db.on('close', () => { console.log('mongodb connection closed.'); });<file_sep>/helper/messageHelper.js module.exports = { textMessage(text) { return { type: 'text', text: text } }, imageMessage(imageUrl) { return { "type": "image", "originalContentUrl": imageUrl, "previewImageUrl": imageUrl } }, buttonMessage() { return { "type": "template", "altText": "This is a buttons template", "template": { "type": "buttons", "text": "検索方法を選択してください", "actions": [ { "type": "uri", "label": "住所で検索", "uri": "http://example.com/page/123" }, { "type": "uri", "label": "一覧から検索", "uri": "http://example.com/page/123" } ] } } }, flexMessage(trashDays) { function getContents(text, imageUrl) { return { "type": "box", "layout": "horizontal", "contents": [ { "type": "image", "url": imageUrl, "size": "xxs", "aspectMode": "cover", "backgroundColor": "#DDDDDD", "gravity": "center", "flex": 1 }, { "type": "text", "text": text, "gravity": "center", "size": "xs", "flex": 7 } ] } } const contents = []; trashDays.forEach((trashDay) => { const content = getContents(trashDay.trashDay, trashDay.type); contents.push(content); }); return { "type": "flex", "altText": "this is a flex message", "contents": { "type": "bubble", "body": { "type": "box", "layout": "vertical", "contents": contents } } } } };
295c61ff6db9873d686e386f1403a5941464a263
[ "JavaScript" ]
7
JavaScript
takenishi/ppt-bot-handson
96ddefb8a098137dc18ec639c61f07098800c825
cb0adc18bdb8b9dfc2316344960b10b50aeac6be
refs/heads/master
<file_sep># wolf-game Using spritekit and blender. ![alt](https://raw.githubusercontent.com/valine/wolf-game/master/renders/hunter-sample.png) <file_sep>// // File.swift // wolf-game-ios // // Created by <NAME> on 8/28/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import SpriteKit class Wolf: SKSpriteNode { var velocity = CGVector.zero var maxVelocity: CGFloat = 3; var frictionConstant: CGFloat = 0.2 init() { let texture = SKTexture(imageNamed: "Wolf") super.init(texture: texture, color: UIColor.blue(), size: texture.size()) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setVelocity(velocity: CGVector) { self.velocity = velocity } var lastVelocity = CGVector.zero func updatePosition(touchInProgress: Bool) { let frictionx = velocity.dx * frictionConstant let frictiony = velocity.dy * frictionConstant if velocity.dx > maxVelocity { velocity.dx = maxVelocity; } else if velocity.dx < maxVelocity * -1 { velocity.dx = maxVelocity * -1 } if touchInProgress { lastVelocity = velocity; } if velocity.dy > maxVelocity { velocity.dy = maxVelocity; } else if velocity.dy < maxVelocity * -1 { velocity.dy = maxVelocity * -1 } position.x = position.x - velocity.dx position.y = position.y - velocity.dy if !touchInProgress { if velocity.dx < frictionx { if velocity.dx + frictionx > 0 { velocity.dx = 0 } else { velocity.dx = velocity.dx - frictionx } } else if velocity.dx > frictionx { if velocity.dx - frictionx < 0 { velocity.dx = 0 } else { velocity.dx = velocity.dx - frictionx } } if velocity.dy < frictiony { if velocity.dy + frictiony > 0 { velocity.dy = 0 } else { velocity.dy = velocity.dy - frictiony } } else if velocity.dy > frictiony { if velocity.dy - frictiony < 0 { velocity.dy = 0 } else { velocity.dy = velocity.dy - frictiony } } } } } <file_sep>// // GameScene.swift // wolf-game-ios // // Created by <NAME> on 7/25/16. // Copyright © 2016 <NAME>. All rights reserved. // import SpriteKit import GameplayKit extension CGFloat { public var degrees: CGFloat { return self * CGFloat(M_PI / 180) } public var rad: CGFloat { return self * CGFloat(180 / M_PI) } } class GameScene: SKScene, SKPhysicsContactDelegate { let character = Wolf() override init(size: CGSize) { super.init(size: size) self.physicsWorld.contactDelegate = self self.physicsWorld.gravity = CGVector.zero let myCamera = SKCameraNode() camera = myCamera addChild(myCamera) camera?.position = CGPoint(x: 100, y: 0) let gridSize = 5; for i in 0...gridSize { for j in 0...gridSize { let grid = SKSpriteNode(imageNamed: "Grid") grid.position = CGPoint(x: 465 * i, y: 330 * j) addChild(grid) grid.zPosition = 0 } } character.physicsBody = SKPhysicsBody.init(circleOfRadius: 50) character.position = CGPoint(x: 0, y: 200) character.zPosition = 1 character.physicsBody?.isDynamic = true addChild(character) let character2 = SKShapeNode(rect: CGRect(x: -10, y: -500, width: 20, height: 1000) ) character2.physicsBody = SKPhysicsBody.init(rectangleOf: CGSize(width: 20, height: 1000)) character2.fillColor = UIColor.blue() character2.position = CGPoint(x: 0, y: 20) character2.zPosition = 2 character2.physicsBody?.isDynamic = false addChild(character2) } // Called once a frame assuming touch is happening func updateCameraPosition(atPoint pos : CGPoint) { camera?.position.x = (camera?.position.x)! + (touchDownPoint?.x)! - pos.x camera?.position.y = (camera?.position.y)! + (touchDownPoint?.y)! - pos.y } func updateCharacterPosition(toPoint pos : CGPoint) { let x = ((touchDownPoint?.x)! - pos.x) let y = ((touchDownPoint?.y)! - pos.y) var clampedPos = pos // let theta = atan(x / y) * (180 / CGFloat(M_PI)) - maxValue var h = (sqrt((x * x) + (y * y))) let theta = asin(y / h).degrees if h > 5 { h = 5 } clampedPos.x = ((cos(theta)) * (h)) * 10 clampedPos.y = ((sin(theta)) * (h)) * 10 //print("x " + String(clampedPos.x) + " y " + String(clampedPos.y)) print(String(sqrt(1 - (sin(theta) * sin(theta))))) character.velocity = CGVector( dx: clampedPos.x, dy: clampedPos.y) } var touchDownPoint: CGPoint? var initialTouch: UITouch = UITouch() var initialTouchPoint = CGPoint() var touchInProgress = false // Called when touch revieved override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if !touchInProgress { initialTouch = touches.first! touchInProgress = true initialTouchPoint = initialTouch.location(in: self) } for t in touches { self.touchDown(atPoint: t.location(in: self)) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches.enumerated() { if t.element == initialTouch { if touches.count > 1 { self.updateCameraPosition(atPoint: t.element.location(in: self)) } else { self.updateCharacterPosition(toPoint: t.element.location(in: self)) } } } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchMoved(toPoint: t.location(in: self)) } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.updateCameraPosition(atPoint: t.location(in: self)) } } var lastTime = TimeInterval(0) override func update(_ currentTime: TimeInterval) { lastTime = currentTime character.updatePosition(touchInProgress: touchInProgress) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // First touch was recieved func touchDown(atPoint pos : CGPoint) { touchDownPoint = initialTouch.location(in: self) } // Called after touch is done func touchMoved(toPoint pos : CGPoint) { touchInProgress = false } }
a6f92416ec0242f201be74931da75fcb7b340784
[ "Markdown", "Swift" ]
3
Markdown
valine/wolf-game
d30531377a76f597c60c8c82ea19b0bbeb07a4d8
b3ae07f476bd18307ab3af07cd60786ccfd6f3b7
refs/heads/master
<repo_name>Roger-random/HelloPHP<file_sep>/hello.php <html> <head> <title>Hello PHP!</title> </head> <body> <p>Server variables are as follows:</p> <ol> <?php foreach($_SERVER as $srvar=>$srval) { echo "<li>$srvar => $srval</li>"; } ?> </ol> </body> </html>
29ef2849b97f5ff49ab79d03dc78909d858023aa
[ "PHP" ]
1
PHP
Roger-random/HelloPHP
8cadb7daa5733bc035e060e069feed31ebdc1d0f
2458602dd7c000f261a1edeff1202b6fdd4574be
refs/heads/main
<repo_name>lpmarques/ocr-challenge<file_sep>/init.sh #!/usr/bin/env bash python3 ocr.py $OCR_ARGS<file_sep>/README.md # OCR - Optical Character Recognition Simple application to recognize text in an image and print it to CLI. The **ocr.py** script uses the pytesseract library to estimate a string approximation of the text depicted in any given image. ## Parameters #### -i, --image Path to the image containing the text to be recognized; *Required* #### -l, --lang Language that Tesseract uses to support word recognition; *Not required*; *Default*: None #### -d, --tessdata-dir Path containing the training dataset that feeds Tesseract's neural network; You can override this to achieve better text recognition results; *Not required*; *Default*: https://github.com/tesseract-ocr/tessdata ## Example run ### Input: ![](input_example/my_name.jpg) ### Output: `<NAME>` ## Deploy ### Docker container approach After cloning the repo, build a docker image in the same directory: ``` docker build -t IMAGE_NAME . ``` Run the container while mapping the image source to the directory where the ocr script should access it: ``` docker run -ti -v IMAGE/SOURCE/PATH:/usr/image.jpg ocr ``` By default, the ocr container will have the image path set as `/usr/image.jpg`, but you can define any other path by overriding the `OCR_ARGS` env variable. ``` docker run -ti -v IMAGE/SOURCE/PATH:/NONDEFAULT/CONTAINER/PATH -e OCR_ARGS="--image /NONDEFAULT/CONTAINER/PATH" ocr ``` If you wish so, you can also define other parameter values by passing it along with `--image` in `OCR_ARGS`. ### virtualenv approach After cloning the repo, install virtualenv if you haven't yet: ``` pip3 install virtualenv ``` Create a python 3 virtual environment for your OCR run: ``` virtualenv -p python3 ocrenv ``` Activate the virtual environment: ``` source ocrenv/bin/activate ``` Install all the dependencies: ``` sudo apt-get install tesseract-ocr pip3 install pytesseract==0.3.6 ``` Finally, run the script: ``` python3 ocr.py --image PATH_TO_IMAGE ``` <file_sep>/ocr.py import argparse import pytesseract from PIL import Image def parse_arguments(): ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", type=str, required=False, default="usr/image.jpg", help="Image from which text must be read") ap.add_argument("-l", "--lang", type=str, required=False, help="Language that Tesseract should use to identify words") ap.add_argument("-d", "--tessdata-dir", required=False, help="Path to the dataset Tesseract should use to train its neural network") return vars(ap.parse_args()) def args_to_tess_config(args): config = "" if args["lang"]: config += f'-l {args["lang"]}' if args["tessdata_dir"]: config += f' --tessdata-dir "{args["tessdata_dir"]}"' return config def ocr(image_filename, tesseract_config): image = Image.open(image_filename) text = pytesseract.image_to_string(image, config=tesseract_config) return text args = parse_arguments() config = args_to_tess_config(args) text = ocr(args["image"], config) with open('texto.txt', "w") as f: f.write(text)<file_sep>/Dockerfile FROM python:3.7 RUN pip3 install pytesseract==0.3.6 RUN apt-get update && apt-get install -y tesseract-ocr ENV OCR_ARGS="--image /usr/image.jpg" COPY ocr.py /usr/ocr.py COPY init.sh /usr/init.sh RUN chmod +x /usr/init.sh WORKDIR /usr ENTRYPOINT [ "/usr/init.sh" ]
64b0abe81b5464632850c3fc44a790516861f314
[ "Markdown", "Python", "Dockerfile", "Shell" ]
4
Shell
lpmarques/ocr-challenge
324c342646b8d02d119afb2c793755806dad6dbb
8c0e5fdabcdab1d260bb6d4d16e5c5aa07ecbe2d
refs/heads/master
<repo_name>brij222/vd<file_sep>/gunjanSpa/src/main/webapp/js/emp.js routerApp.controller('addCtrl',function($scope,$http){ $scope.login = function (){ $scope.successMsg= false; alert("login"); console.log("after login") console.log($scope.firstName+" "+$scope.lastName+" "+$scope.email+" "+$scope.phone) var data = new FormData; data.append('firstName',$scope.firstName); data.append('lastName',$scope.lastName); data.append('email',$scope.email); data.append('phone',$scope.phone); $http({ url: "http://localhost:8080/demo/v1/user/addEmployee", method: "POST", data: data, async: false, transformRequest: false, headers: {'Content-Type': undefined} }).success(function(response, status) { console.log(response); $scope.showSuccessMsg = response; $scope.successMsg= true; }) } }) routerApp.controller('editCtrl',function($scope,$http,$stateParams,$state,$sessionStorage){ //alert($stateParams.id); $http({ url: "http://localhost:8080/demo/v1/user/getEmployeeById?id="+$stateParams.id, method: "Get", data: null, async: false, transformRequest: false, headers: {'Content-Type': undefined} }).success(function(response, status) { console.log(response); $scope.editFirstName = response.firstName; $scope.editLastName = response.lastName; $scope.editEmail = response.email; $scope.editPhone = response.phone; //$sessionStorage.id = response.id; }) $scope.updateEmp = function(){ var data = new FormData; data.append('firstName',$scope.editFirstName); data.append('lastName',$scope.editLastName); data.append('email',$scope.editEmail); data.append('phone',$scope.editPhone); $http({ url: "http://localhost:8080/demo/v1/user/updateEmployee?id="+$stateParams.id, method: "POST", data: data, async: false, transformRequest: false, headers: {'Content-Type': undefined} }).success(function(response, status) { console.log(response); $sessionStorage.successResponse = response; $state.go('about.empList'); /*$state.transitionTo($state.go('about.empList'), $stateParams, { reload: true, inherit: false, notify: true });*/ }) } }) routerApp.controller('deleteCtrl',function($scope,$http,$sessionStorage,$stateParams,$state){ $http({ url: "http://localhost:8082/cxfRestExample/v1/user/deleteEmployee?id="+$stateParams.id, method: "POST", data: null, async: false, transformRequest: false, headers: {'Content-Type': undefined} }).success(function(response, status) { console.log(response); $sessionStorage.successResponse = response; $state.go('about.empList'); /*$state.transitionTo($state.go('about.empList'), $stateParams, { reload: true, inherit: false, notify: true });*/ }) })
3dab02c94a933fc2e6de1c52d6076125f9267e6b
[ "JavaScript" ]
1
JavaScript
brij222/vd
e1dd5af8a34e449b584ad92a3213a0e1b346c132
e020f4ccbe67007b783f56213dd9073d8d8debc9
refs/heads/master
<repo_name>adbuerger/control_strategies_k004b<file_sep>/two_point_control.py #!/usr/bin/env python from sensors_actuators_k004b.sensors import Sensors from sensors_actuators_k004b.actuators import Actuators from mdb_communication_k004b.dbinsert import DBInsert # Intentionally, SensorsRS232 was not added to Sensors class, # since the SPN1 will not be a permanent element of k004b from sensors_actuators_k004b.sensors_rs232 import SensorsRS232 import time import os import sys import numpy as np import logging import logging.config logging.config.fileConfig(os.environ["PATH_TO_LOGGING_CONFIG"]) log = logging.getLogger() # Modbus Connection Parameter - Port 1 Sensor, Port 2 Actuator sensor_client_address = os.environ["EX9132_ADDRESS"] sensor_client_port = os.environ["EX9132_PORT_1"] actuator_client_address = os.environ["EX9132_ADDRESS"] actuator_client_port = os.environ["EX9132_PORT_2"] # http Connection Parameter server_address = os.environ["WT_ADDRESS"] server_port = os.environ["WT_PORT"] # RS232 serial connection parameter serial_port_sensors = os.environ["SPN1_SERIAL_PORT"] baudrate_sensors = os.environ["SPN1_BAUDRATE"] parity_sensors = os.environ["SPN1_PARITY"] stopbits_sensors = os.environ["SPN1_STOPBITS"] bytesize_sensors = os.environ["SPN1_BYTESIZE"] timeout_sensors = os.environ["SPN1_TIMEOUT"] # DB connection parameter db_name = os.environ["DB_NAME"] db_host = os.environ["DB_HOST"] db_port = os.environ["DB_PORT"] db_user = os.environ["DB_USER"] user_password = os.environ["USER_PASSWORD"] s = Sensors(client_address = sensor_client_address, \ client_port = sensor_client_port, \ server_address = server_address, \ server_port = server_port, \ serial_port = serial_port_sensors, \ baudrate = baudrate_sensors, \ parity = parity_sensors, \ stopbits = stopbits_sensors, \ bytesize = bytesize_sensors, \ timeout = timeout_sensors) a = Actuators(client_address = actuator_client_address, \ client_port = actuator_client_port) dbi = DBInsert(db_name = db_name, \ db_host = db_host, \ db_port = db_port, \ db_user = db_user, \ user_password = <PASSWORD>) valve_open = 1.0 valve_closed = 0.0 # Two point control of K004b try: while True: time_measurement = time.time() time_new_loop = time_measurement + 60.0 ltime = time.localtime(time_measurement) hour = ltime.tm_hour wday = ltime.tm_wday temperature_nw = s.get_temperature_northwest() temperature_ne = s.get_temperature_northeast() temperature_e = s.get_temperature_east() temperature_w = s.get_temperature_west() temperature_sw = s.get_temperature_southwest() temperature_se = s.get_temperature_southeast() radiation = s.get_radiation_all() ex9024_level = a.get_valve_position() flowrate = s.get_flowrate_radiator() temperature_inlet = s.get_temperature_radiator_inlet() temperature_outlet = s.get_temperature_radiator_outlet() temperatures = [temperature_nw, temperature_ne, temperature_e, temperature_w, temperature_sw, temperature_se] weightings = [1, 1, 1, 1, 1, 1] temperatures_weighted = 0 for j, temperature in enumerate(temperatures): temperatures_weighted += weightings[j] * temperature temperature_room = temperatures_weighted / sum(weightings) if (18 <= hour) or (hour < 6) or (wday == 5) or (wday == 6): if (temperature_room < 19.0) and (abs(ex9024_level-valve_open) > 0.05): log.info("Turning on heating") a.set_valve_position(opening_level = valve_open) elif (temperature_room > 20.0) and (abs(ex9024_level-valve_closed) > 0.05): log.info("Turning off heating") a.set_valve_position(opening_level = valve_closed) ex9024_level_new = a.get_valve_position() elif (6<= hour < 18): if (temperature_room < 22.0) and (abs(ex9024_level-valve_open) > 0.05): log.info("Turning on heating") a.set_valve_position(opening_level = valve_open) elif (temperature_room > 23.0) and (abs(ex9024_level-valve_closed) > 0.05): log.info("Turning off heating") a.set_valve_position(opening_level = valve_closed) ex9024_level_new = a.get_valve_position() data_set = [time.ctime(), flowrate, temperature_inlet, temperature_outlet, ex9024_level_new, temperature_ne, temperature_nw, temperature_w, temperature_sw, temperature_se, temperature_e, round(temperature_room, 2), radiation] dbi.insert_sensor_1(time_measurement, temperature_ne) dbi.insert_sensor_2(time_measurement, temperature_nw) dbi.insert_sensor_3(time_measurement, temperature_w) dbi.insert_sensor_4(time_measurement, temperature_sw) dbi.insert_sensor_5(time_measurement, temperature_se) dbi.insert_sensor_6(time_measurement, temperature_e) dbi.insert_flowrate(time_measurement, flowrate) dbi.insert_temperature_inlet(time_measurement, temperature_inlet) dbi.insert_temperature_outlet(time_measurement, temperature_outlet) dbi.insert_valve_position(time_measurement, ex9024_level) dbi.insert_control_method(time_measurement, 1) dbi.insert_spn1_radiation(time_measurement, radiation) log.info("Data update: " + str(data_set)) # Abfrage-/Updaterythmus der Steuerung time.sleep(time_new_loop - time.time()) except: log.exception("Terminated") finally: del a del s <file_sep>/calibration/calibration_actuator.py from sensors_actuators_k004b.sensors_modbus import SensorsModbus from sensors_actuators_k004b.actuators_modbus import ActuatorsModbus from sensors_actuators_k004b.sensors_http import SensorsHttp import numpy as np import time import os sensor_client_address = os.environ["EX9132_ADDRESS"] sensor_client_port = os.environ["EX9132_PORT_1"] actuator_client_address = os.environ["EX9132_ADDRESS"] actuator_client_port = os.environ["EX9132_PORT_2"] sensor_server_address = os.environ["WT_ADDRESS"] sensor_server_port = os.environ["WT_PORT"] am = ActuatorsModbus(actuator_client_address, actuator_client_port) sm = SensorsModbus(sensor_client_address, sensor_client_port) sh = SensorsHttp(sensor_server_address, sensor_server_port) for k in np.linspace(0.15,0.6,46): opening_level = k am.set_ex9024(opening_level = opening_level) t_start= time.time() while time.time()- t_start < 60: flowrate = sm.get_mc602_flowrate() temperature_inlet = sm.get_mc602_temperature_inlet() temperature_outlet = sm.get_mc602_temperature_outlet() ex9024_level = am.get_ex9024() rtm1_0 = sm.get_rtm1_0() rtm1_1 = sm.get_rtm1_1() wt_0 = sh.get_wt_0() wt_1 = sh.get_wt_1() wt_2 = sh.get_wt_2() wt_3 = sh.get_wt_3() data_set = [time.ctime(), flowrate, temperature_inlet, temperature_outlet, round(ex9024_level,2), rtm1_0, rtm1_1, wt_0, wt_1, wt_2, wt_3] print data_set for data_element in data_set: with open("calibration_actuator_with_cooldown.csv", "a") as f: f.write(str(data_element) + ", ") with open("calibration_actuator_with_cooldown.csv", "a") as f: f.write("\n") time.sleep(1.0) am.set_ex9024(opening_level = 0) try: while True: flowrate = sm.get_mc602_flowrate() temperature_inlet = sm.get_mc602_temperature_inlet() temperature_outlet = sm.get_mc602_temperature_outlet() ex9024_level = am.get_ex9024() rtm1_0 = sm.get_rtm1_0() rtm1_1 = sm.get_rtm1_1() wt_0 = sh.get_wt_0() wt_1 = sh.get_wt_1() wt_2 = sh.get_wt_2() wt_3 = sh.get_wt_3() data_set = [time.ctime(), flowrate, temperature_inlet, temperature_outlet, round(ex9024_level,1), rtm1_0, rtm1_1, wt_0, wt_1, wt_2, wt_3] print data_set for data_element in data_set: with open("calibration_actuator_with_cooldown.csv", "a") as f: f.write(str(data_element) + ", ") with open("calibration_actuator_with_cooldown.csv", "a") as f: f.write("\n") time.sleep(1.5) except KeyboardInterrupt: sm.disconnect_from_client() am.disconnect_from_client() raise <file_sep>/README.md # Two point radiator control of room K004b
880941a7fa105368557137810c7d09445025588a
[ "Markdown", "Python" ]
3
Python
adbuerger/control_strategies_k004b
57d1383a62027b741b6b15e46429d3a74de7722c
cf9f7ce7c7b52e9f492e0db604245bd820e01c0e
refs/heads/master
<repo_name>ToddTurnbull/computer-lab<file_sep>/setup-graphics.sh # software sudo apt update sudo apt upgrade -y sudo apt install -y --no-upgrade gimp sudo apt install -y --no-upgrade inkscape sudo apt install -y --no-upgrade darktable sudo apt install -y --no-upgrade scribus sudo apt install -y --no-upgrade typecatcher sudo apt install -y --no-upgrade ttf-mscorefonts-installer sudo apt install -y --no-upgrade fonts-liberation sudo apt install -y --no-upgrade fonts-noto <file_sep>/setup.sh # PPAs # Numix Circle Icon Theme sudo add-apt-repository ppa:numix/ppa # Plank sudo add-apt-repository ppa:docky-core/stable sudo apt update sudo apt upgrade -y sudo apt install -y --no-upgrade numix-icon-theme numix-icon-theme-circle plank # Gnome Software doesn't work on Xubuntu 16.04 sudo apt install -y --no-upgrade gdebi synaptic <file_sep>/setup-python.sh # software sudo apt update sudo apt upgrade -y sudo apt install -y --no-upgrade build-essential python-pip python-setuptools python-virtualenv # directory mkdir ~/venv <file_sep>/README.md # computer-lab ```bash # Git sudo apt update sudo apt upgrade -y sudo apt install -y --no-upgrade git git config --global user.name "<NAME>" git config --global user.email "<EMAIL>" mkdir ~/git ```
e51d701a155a4468710841226c4950ed55b2a973
[ "Markdown", "Shell" ]
4
Shell
ToddTurnbull/computer-lab
49253e67797c4a72c9254776dfabc067ad3beaa2
226cefaa1c7fd033a5048e1b91e5e7a70c586d64
refs/heads/master
<repo_name>Magesh-sam/Simple-Calculator<file_sep>/README.md # Simple-Calculator * Simple Calculator using JavaScript * only perform calculation with two numbers # Live Demo [Simple Calculator](https://magesh-sam.github.io/Simple-Calculator/) <file_sep>/script.js function addition() { let firstnumber = parseInt(document.getElementById("firstnumber").value); let secondnumber = parseInt(document.getElementById("secondnumber").value); let sum = firstnumber + secondnumber; if (sum) { document.getElementById("answer").innerHTML = sum; } else { alert("Enter Both Numbers to Calculate") } } function subtraction() { let firstnumber = parseInt(document.getElementById("firstnumber").value); let secondnumber = parseInt(document.getElementById("secondnumber").value); let sum = firstnumber - secondnumber; if (sum) { document.getElementById("answer").innerHTML = sum; } else { alert("Enter Both Numbers to Calculate") } } function multiplication() { let firstnumber = parseInt(document.getElementById("firstnumber").value); let secondnumber = parseInt(document.getElementById("secondnumber").value); let sum = firstnumber * secondnumber; if (sum) { document.getElementById("answer").innerHTML = sum; } else { alert("Enter Both Numbers to Calculate") } } function division() { let firstnumber = parseInt(document.getElementById("firstnumber").value); let secondnumber = parseInt(document.getElementById("secondnumber").value); let sum = firstnumber / secondnumber; if (sum) { document.getElementById("answer").innerHTML = sum; } else { alert("Enter Both Numbers to Calculate") } }
690432a217a96fa3d59eca92a4549a047e72fb21
[ "Markdown", "JavaScript" ]
2
Markdown
Magesh-sam/Simple-Calculator
ba2f852c182154efd2a9d5a067400f660cad42f7
3854469f76787f5ddf82de1238cf7fd530452861
refs/heads/master
<file_sep>#2nd Semester Final - Highschool Coding from random import shuffle import random import time def deck(): deck = [] for suit in ['H', 'S', 'D', 'C']: for rank in ['A','2','3','4','5','6','7','8','9','10','J','Q','K']: deck.append(suit+rank) shuffle(deck) return deck def card_values(player_cards): player_Cards = 0 card_ace = 0 for a in player_cards: #print "Card", a if(a[1:] == 'J' or a[1:] == 'Q' or a[1:] == 'K' or a[1:] == '10'): player_Cards += 10 elif(a[1:] != 'A'): player_Cards += int(a[1:]) else: card_ace += 1 if (card_ace == 1 and player_Cards >= 10): player_Cards += 11 elif(card_ace != 0): player_Cards += 1 return player_Cards def card_playing_hand(player_deck): dealer_cards = [] player_cards = [] dealer_cards.append(player_deck.pop()) dealer_cards.append(player_deck.pop()) player_cards.append(player_deck.pop()) player_cards.append(player_deck.pop()) while (card_values (dealer_cards) <= 16): dealer_cards.append(player_deck.pop()) return [dealer_cards, player_cards] blackjack = 0 wons = 0 losses = 0 player_name = input("Enter your name: ") cont = "y" restart = "y" while(blackjack != "2"): print("______________________") print("M A I N M E N U") print("") print( "Welcome to the basic Blackjack Simulator!", player_name) print("") print(player_name, "has won", wons, "number of games!") print("Dealer has won", losses, "number of games! :(") print("") print("") print("What would you like to do?") blackjack = input("1.)Play!\n2.)Quit." ) print("_____________________") if blackjack == "1": #restart = "y" player_deck = deck() hands = card_playing_hand(player_deck) dealer = hands[0] player = hands[1] player_hit = card_playing_hand(player_deck) #Cards of the players and the values dealer_count = card_values(dealer) player_count = card_values(player) print("_________________________") print("Dealer hand is:", dealer) print(dealer_count, "points") print("_________________________") print(player_name, "hand is:", player) print(player_count, "points") print("_________________________") time.sleep(.5) if(player_count == 21): print("Blackjack!") wons += 1 elif(player_count > 21): print(player_name,"has BuStEd!!! With " + str(player_count) + " points. Dealer Wins! D:") losses += 1 elif(dealer_count == 21): print("Dealer claimed blackjack!") losses += 1 elif(dealer_count > 21): print("Dealer has Busted! With " + str(dealer_count) + " points. Player Wins! :D") wons += 1 else: hit_stay = input("What would you like to do? H: Hit, S: Stay ") time.sleep(.5) print("_________________________") if(hit_stay == 'H' or hit_stay == 'h'): player_count += random.randint(1,11) dealer_count += random.randint(1,11) print(player_name, "now has", player_count, "points") print("_______________________") else: (hit_stay == 'S' or hit_stay == 's') #nothing to be placed in here :D if player_count > 21: print(player_name, "has busted on his second attempt.") print("dealer wins!") losses += 1 elif dealer_count > 21: print("Dealer has busted!") print(player_name, "has claimed a victory!") wons += 1 elif(player_count > dealer_count): print(player_name ,"wins with " + str(player_count) + " points!! :D") wons += 1 print("D E A L E R") print("Dealer has: " + str(dealer_count) + " points") else: print("Dealer Wins! D:<") losses += 1 print("_______________________") print("Dealer has: " + str(dealer_count) + " points") print(player_name, "lost with: " + str(player_count) + " points") print("_________________________") print("G A M E ... O V E R...") print("") time.sleep(.5) cont = input("Would you like to return to the Main Menu? (y/n)") if cont == "n": break
ce917aa604264f97eae680c13e28def20e0b287d
[ "Python" ]
1
Python
TheRealBimo/blackjack
c8be23433bd35f43402b96f381b47d9792eee4d1
f499e46fc269a72c017979561dc04a1876189796
refs/heads/master
<file_sep>import Vue from 'vue' import Router from 'vue-router' import Home from '@/components/Home' import Itens from '@/components/itens/Itens' import Users from '@/components/users/Users' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'home', component: Home }, { path: '/itens', name: 'itens', component: Itens }, { path: '/users', name: 'users', component: Users } ] }) <file_sep>// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. // import jquery var $ = require('jquery') // assign to window object window.jQuery = window.$ = $ import Vue from 'vue' import App from './App' import router from './router' import vueResource from 'vue-resource' import '@/assets/default.css' import semantic from 'semantic' Vue.config.productionTip = false Vue.config.devtools = true Vue.use(vueResource) Vue.use(semantic) Vue.http.options.root = 'http://localhost:8765' Vue.http.headers.common['Accept'] = 'application/vnd.api+json' /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<App/>', components: { App } }) import '../node_modules/semantic-ui-css/semantic.min.css'
4abbf0713b61903500bf9d79ea0e788ec9658127
[ "JavaScript" ]
2
JavaScript
eduardo76/vue-datagrid
d8a6bb6db292fc7ae0ba3bd533a3681177c5b3b6
6d2a7ead3a70194c791be6e39e005d064a9948ed
refs/heads/master
<repo_name>afiffifa/ruby-advanced-class-methods-lab-online-web-ft-120919<file_sep>/lib/song.rb class Song attr_accessor :name, :artist_name @@all = [] def self.create s = self.new s.save s end def self.create_by_name(string_name_of_the_song) s = self.new s.name = string_name_of_the_song s.save s end def self.new_by_name(string_name_of_the_song s = self.new s.name = string_name_of_the_song s end def self.find_by_name(string_name_of_the_song) self.all.detect {|i| i.name == string_name_of_the_song} end def self.find_or_create_by_name(find_this_song) did_i_find_it = self.all.detect {|x| x.name == find_this_song} if did_i_find_it == nil s = self.new s.name = find_this_song s.save s else did_i_find_it end end def self.alphabetical self.all.sort_by { |x| x.name} end def self.new_from_filename(mp3_formatted_file) c = self.new c.name = mp3_formatted_file.split(/[^a-zA-Z\s]|\s-\s/)[1] c.artist_name = mp3_formatted_file.split(/[^a-zA-Z\s]|\s-\s/)[0] c end def self.create_from_filename(mp3_formatted_file) c = self.new c.name = mp3_formatted_file.split(/[^a-zA-Z\s]|\s-\s/)[1] c.artist_name = mp3_formatted_file.split(/[^a-zA-Z\s]|\s-\s/)[0] c.save c end def self.all @@all end def save self.class.all << self end def self.destroy_all self.all.clear end end zaza = Song.create zaza.name = "<NAME>" zaza.artist_name = "Shoshi" loon = Song.create loon.name = "<NAME>" loon.artist_name = "<NAME>" Song.all song = Song.create song.name = "Haunted House" Song.all.include?(song) song2 = Song.new_by_name("The Middle") song2.name #=> "The Middle" song2 song3 = Song.create_by_name("Banjo-Song") song3.artist_name = "<NAME>" Song.all.include?(song3) Song.find_by_name("Banjo-Song") song5 = Song.find_or_create_by_name("Banjo-Song") Song.all song_6 = Song.find_or_create_by_name("Blank Space") song_7 = Song.find_or_create_by_name("Blank Space") song_6 == song_7 Song.alphabetical song8 = Song.new_from_filename("Taylor Swift - Blank Space.mp3") song8.name #=> "Blank Space" song8.artist_name song9 = Song.create_from_filename("<NAME> - <NAME>lyek.mp3") song9.name #=> "<NAME>" song9.artist_name
b31a18af2926276a8b7bc3e5ea531aed3f6ea622
[ "Ruby" ]
1
Ruby
afiffifa/ruby-advanced-class-methods-lab-online-web-ft-120919
91bb1b995874c9fe4c233901863ed3b9376fda52
20825b38043124b283c407c80ec613c1b212edec
refs/heads/master
<repo_name>Charleslsf/contaBancaria<file_sep>/src/main/java/com/contaBancaria/controller/ContaBancariaController.java package com.contaBancaria.controller; import com.contaBancaria.dto.ContaBancariaDTO; import com.contaBancaria.dto.ContaBancariaDetalheDTO; import com.contaBancaria.form.ContaBancariaForm; import com.contaBancaria.repository.filter.ContaBancariaFilter; import com.contaBancaria.service.ContaBancariaService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController @RequestMapping("/contas") public class ContaBancariaController { @Autowired private ContaBancariaService contaBancariaService; @GetMapping(produces="application/json") public Page<ContaBancariaDTO> findByFilter(ContaBancariaFilter filtro, @PageableDefault() Pageable pageable) { return contaBancariaService.findByFilter(filtro, pageable).map(ContaBancariaDTO::create); } @GetMapping(path = "/detalhe", produces="application/json") public ContaBancariaDetalheDTO findByConta(Integer numeroConta) { return ContaBancariaDetalheDTO.toDTO(contaBancariaService.findByConta(numeroConta)); } @PutMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void update(@PathVariable Long id, @RequestBody @Valid ContaBancariaForm contaBancariaForm) { contaBancariaService.update(id, contaBancariaForm); } @PostMapping @ResponseStatus(HttpStatus.CREATED) public ContaBancariaDetalheDTO create(@RequestBody @Valid ContaBancariaForm contaBancariaForm) { return contaBancariaService.save(contaBancariaForm); } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@PathVariable Long id) { contaBancariaService.delete(id); } } <file_sep>/src/main/java/com/contaBancaria/dto/ContaBancariaDTO.java package com.contaBancaria.dto; import com.contaBancaria.model.ContaBancaria; import lombok.Getter; import lombok.Setter; import org.modelmapper.ModelMapper; @Getter @Setter public class ContaBancariaDTO { private Long id; private String nome; private Integer numeroConta; private Integer agencia; private Boolean chequeEspecialLiberado; private Double saldo; private Double chequeEspecial; private Double taxa; public static ContaBancariaDTO create(ContaBancaria contaBancaria) { return new ModelMapper().map(contaBancaria, ContaBancariaDTO.class); } } <file_sep>/src/main/resources/messages.properties NotBlank={0} \u00e9 obrigat\u00f3rio(a) <file_sep>/README.md # crudContaBancaria Documentacao: https://documenter.getpostman.com/view/1849606/Tzedh4XY <file_sep>/Dockerfile FROM centos VOLUME /tmp ADD target/contaBancaria-0.0.1-SNAPSHOT.jar app.jar RUN yum install -y java-11-openjdk-devel RUN yum install -y glibc-locale-source RUN localedef -i pt_BR -f UTF-8 pt_BR.UTF-8 ENV LANG=pt_BR.UTF-8 ENV LC_ALL=pt_BR.UTF-8 RUN rm -rf /etc/localtime RUN ln -s /usr/share/zoneinfo/America/Fortaleza /etc/localtime<file_sep>/src/main/java/com/contaBancaria/util/Util.java package com.contaBancaria.util; import java.text.NumberFormat; import java.util.Locale; public class Util { public static String converterLocalCurrency(Double valor) { NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault()); return format.format(valor); } } <file_sep>/src/main/resources/db/migration/V001__create_table_cliente.sql CREATE SEQUENCE IF NOT EXISTS conta_bancaria_id_seq; CREATE TABLE IF NOT EXISTS conta_bancaria ( id INT8 NOT NULL, nome VARCHAR(100) NOT NULL, numero_conta INT8 NOT NULL, agencia INT8 NOT NULL, cheque_especial_liberado boolean NOT NULL, saldo numeric(11,2) NOT NULL, cheque_especial numeric(11,2) NOT NULL, taxa numeric(11,2) NOT NULL, CONSTRAINT pk_conta_bancaria PRIMARY KEY (id) ); ALTER TABLE conta_bancaria ALTER COLUMN id SET DEFAULT NEXTVAL('conta_bancaria_id_seq');
4f7ae84520d63cbaf253c4723b05b0077945c6f1
[ "SQL", "Markdown", "INI", "Java", "Dockerfile" ]
7
Java
Charleslsf/contaBancaria
849adf20db6f104acc93dc4ce21b02e56dc8369a
2c12126ff27a755688d50b7822527afef38d6250
refs/heads/main
<repo_name>prashant0078/codeigniter_tutorial<file_sep>/application/controllers/Home_Controller.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Home_Controller extends CI_Controller { function __construct(){ parent::__construct(); if(!$this->session->has_userdata('user')){ redirect(base_url('login') , 'refresh'); } } public function index() { $data = array(); $this->load->view('home' , $data); } public function logout(){ $this->session->unset_userdata('user'); session_destroy(); redirect(base_url('login') , 'refresh'); } } <file_sep>/application/views/header.php <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="<?=base_url("assets/css/bootstrap.min.css")?>" > <link rel="stylesheet" href="<?=base_url("assets/css/style.css")?>" > </head> <body> <ul class="nav"> <li class="nav-item"> <a class="nav-link active" href="<?=base_url('home')?>">Home</a> </li> <?php if($this->session->has_userdata('user')) {?> <li class="nav-item"> <a class="nav-link" href="<?=base_url('logout')?>">Logout</a> </li> <?php }else {?> <li class="nav-item"> <a class="nav-link active" href="<?=base_url('login')?>">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="<?=base_url('register')?>">Register</a> </li> <?php } ?> </ul><file_sep>/application/models/User.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class User extends CI_Model{ function insertUser($args = array()){ $insert_id = 0; if(!empty($args)){ $this->db->insert('users' , $args); $insert_id = $this->db->insert_id(); return $insert_id; } } function getUser($email = NULL , $password = NULL){ $result = array(); if(!empty($email) && !empty($password)){ $this->db->select('name , email'); $this->db->from('users'); $this->db->where('status' , '1'); $this->db->where('email' , $email); $this->db->where('password' , md5($password)); $query = $this->db->get(); if($query->num_rows()){ $result = $query->row_array(); } } return $result; } }<file_sep>/application/controllers/Register.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Register extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('User'); } function index(){ $data = array(); $this->load->view('register' , $data); } function submitRegister(){ $name = $this->input->post('name' , true); $email = $this->input->post('email' , true); $password = $this->input->post('password' , true); $cpassword = $this->input->post('cpassword' , true); if($password != $cpassword){ echo "Password dose not match"; }else{ $args = array( "name" => $name, "email" => $email, "password" => md5($<PASSWORD>), "status" => "1" ); $insert_id = $this->User->insertUser($args); if($insert_id){ echo "Registered"; }else{ echo "Some error occured"; } } } }<file_sep>/application/libraries/Custom.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Custom{ function greeting(){ return "This is from library"; } }<file_sep>/application/helpers/common_helper.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); if ( ! function_exists('greeting')) { function greeting($user = "User") { return "Hello ".$user." Kiase ho bhai "; } } <file_sep>/application/views/footer.php <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) --> <script src="<?=base_url('assets/js/jquery-3.5.1.slim.min.js')?>" ></script> <script src="<?=base_url('assets/js/bootstrap.bundle.min.js')?>" ></script> </body> </html><file_sep>/application/controllers/Login.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Login extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('User'); if($this->session->has_userdata('user')){ redirect(base_url('home') , 'refresh'); } } function index(){ $data = array(); $this->load->view('login' , $data); } function submitLogin(){ $email = $this->input->post('email' , true); $password = $this->input->post('password' , true); $user = $this->User->getUser($email , $password); if(!empty($user)){ $this->session->set_userdata("user" , $user); redirect(base_url('home') , 'refresh'); }else{ echo "Record not found"; } } }<file_sep>/application/views/home.php <?php include('header.php') ?> <?php if($this->session->has_userdata('user')) {?> <h1>Hello <?=$this->session->userdata('user')["name"]?></h1> <?php } else { ?> <h1>Hello User</h1> <?php } ?> <?php include('footer.php') ?>
c90b83c61d3399a8239dffbfe2ba58cccbc8e1d9
[ "PHP" ]
9
PHP
prashant0078/codeigniter_tutorial
1c6314f04e25471162ce2eabf3da84ad2057f025
d126be851c466c4e62d10a0bc572d994e0d484f3
refs/heads/master
<repo_name>kift/kift_view_tool<file_sep>/lib/kift_view_tool.rb require "kift_view_tool/version" require "kift_view_tool/renderer" module KiftViewTool # Your code goes here... end
1c8bc7f20e02634bf10485e8fea5f8725d1c9029
[ "Ruby" ]
1
Ruby
kift/kift_view_tool
6f4e692c19c9cefb605f391e58171ef24990721a
ae213cf45d4611b543f22d03b4a3bd331de4f749
refs/heads/master
<repo_name>JorisMeulenbeek/Getting_and_Cleaning_Data_Course_Project<file_sep>/run_analysis.R ##load packages require("data.table"); require("reshape2") ; ##set working directory setwd('/Users/Joris/Documents/Getting_data_eindproject'); ##Load files activity_labels <- read.table('./activity_labels.txt',header=FALSE)[,2]; features <- read.table('./features.txt',header=FALSE)[,2]; x_test <- read.table('./x_test.txt',header=FALSE); y_test <- read.table('./y_test.txt',header=FALSE); subject_test <- read.table('./subject_test.txt',header=FALSE); x_train <- read.table('./x_train.txt',header=FALSE); y_train <- read.table('./y_train.txt',header=FALSE); subject_train <- read.table('./subject_train.txt',header=FALSE); ##Extract measurements mean or std extract_features <- grepl("mean|std", features); names(x_test) = features; x_test = x_test[,extract_features]; ##Set labels y_test[,2] = activity_labels[y_test[,1]] ; names(y_test) = c("Activity_ID", "Activity_Label"); names(subject_test) = "subject" ; ##Combine files test <- cbind(as.data.table(subject_test), y_test, x_test); ##Set labels names(x_train) = features; ##Extract measurements mean or std x_train = x_train[,extract_features]; ##Set labels y_train[,2] = activity_labels[y_train[,1]]; names(y_train) = c("Activity_ID", "Activity_Label"); names(subject_train) = "subject" ; ##Combine files trein <- cbind(as.data.table(subject_train), y_train, x_train); ##Merge data alle_data = rbind(test, trein); kolommen = c("subject", "Activity_ID", "Activity_Label"); kolommen_data = setdiff(colnames(alle_data), kolommen) ; samenvoeg = melt(alle_data, id = kolommen, measure.vars = kolommen_data) ; ##Mean function data totaal_data = dcast(samenvoeg, subject + Activity_Label ~ variable, mean); ##create file write.table(totaal_data, row.name=FALSE ,file = "./tidy_data.txt")<file_sep>/README.md ## Getting_and_Cleaning_Data_Course_Project ###Week 4 Getting and Cleaning Data Course Project My course project for the Getting and Cleaning Data Coursera course. The R script, run_analysis.R , does the following: 1. Download the dataset 2. Read necessary info 3. Load training and test datasets, and work with only the colums you need (mean and standard deviation) 4. Load subject and activity data. 5. Merges the datasets The result is file tidydata.txt.
eaa2b49a639989a54d3d666b7a39127f94b0817d
[ "Markdown", "R" ]
2
R
JorisMeulenbeek/Getting_and_Cleaning_Data_Course_Project
10cf2b64e37f18cf5671b4fd700886b863ec122d
35995a6c3d12c66e56466ee8252d5d7e0af29f4d
refs/heads/master
<file_sep>require 'sdl' class Sprite attr_accessor :x, :y, :speed_x, :speed_y, :size, :points def initialize(screen) init(screen) end def init(screen) @dying = false @diecolor = screen.format.mapRGB(100, 0, 0) @x = rand(SCREEN_W) @y = 0 @speed_x = (-20 + rand(40)) * 0.5 @speed_y = (20 + rand(10)) * 0.5 if (@x > SCREEN_W * 0.6666 && @speed_x > 0) || (@x < SCREEN_W * 0.3333 && @speed_x < 0) @speed_x = -@speed_x end @size = 20 + rand(20) @points = 40 - @size @color = screen.format.mapRGB(100 + rand(155), 100 + rand(155), 100 + rand(155)) end def hit?(x, y) return false if @dying dx = (x - @x).abs dy = ((SCREEN_H - y) - @y).abs d = Math.sqrt((dx ** 2) + (dy ** 2)) d <= @size end def die @dying = true end def tick(screen) if @dying @size -= 1 if @size == 0 init(screen) end else @speed_y -= 0.05 @x += @speed_x * 0.25 @y += @speed_y * 0.25 end end def draw(screen) color = @dying ? @diecolor : @color screen.draw_aa_filled_circle(@x.round, SCREEN_H - @y.round, @size, color) end end <file_sep>require 'yaml' class Settings @@settings_file = File.join(File.dirname(__FILE__), 'settings.yml') def load @@items = YAML::load_file(@@settings_file) end def [](key) @@items[key] end end SETTINGS = Settings.new SETTINGS.load <file_sep>require 'sdl' require_relative('util') class JoystickState def self.init_all @@joysticks = [] n_sticks = SDL::Joystick.num 0.upto(n_sticks - 1) do |n| js = SDL::Joystick.open(n) @@joysticks << js debug "Opened Joystick #{SDL::Joystick.index_name(n)} as controller #{n + 1} \ (#{js.num_axes} axes, #{js.num_buttons} buttons)" end end def self.joysticks @@joysticks end end <file_sep>class Reticle attr_accessor :x, :y def initialize(js, screen) @js = js tick(screen) end def tick(screen) @x = H_SCREEN_W + ((@js.axis(0) / 32768.0) * H_SCREEN_W) @y = H_SCREEN_H + ((@js.axis(1) / 32768.0) * H_SCREEN_H) end def draw(screen) screen.draw_line @x, 0, @x, SCREEN_H, LINECOLOR screen.draw_line 0, @y, SCREEN_W, @y, LINECOLOR end end <file_sep>require_relative('settings') DEBUG = SETTINGS[:debug] SCREEN_W = SETTINGS[:width] SCREEN_H = SETTINGS[:height] def debug(msg) return unless DEBUG puts msg end def main_loop running = true while running while event = SDL::Event2.poll case event when SDL::Event2::Quit running = false end end yield end end <file_sep>#!/usr/bin/env ruby require 'sdl' require_relative('settings') require_relative('util') require_relative('joystick') require_relative('sprite') require_relative('reticle') SDL.init SDL::INIT_EVERYTHING screen = SDL::set_video_mode SCREEN_W, SCREEN_H, 24, SDL::SWSURFACE JoystickState::init_all BGCOLOR = screen.format.mapRGB 0, 0, 0 LINECOLOR = screen.format.mapRGB 255, 255, 255 SDL::TTF.init FONT = SDL::TTF.open(SETTINGS[:font], 14, 0) H_SCREEN_W = SCREEN_W / 2 H_SCREEN_H = SCREEN_H / 2; SPRITES = Array.new(SETTINGS[:sprites]) { Sprite.new(screen) } @js = JoystickState.joysticks[0] @ret = Reticle.new(@js, screen) @score = 0 @misses = 0 @shooting = false @canshoot = true @shotstart = 0 @state = :intro @timer = 60000 @mark = SDL::get_ticks def draw_intro(screen) time = ((3000 - (SDL::get_ticks - @mark)) / 1000.0).round @ret.tick(screen) screen.fill_rect 0, 0, SCREEN_W, SCREEN_H, BGCOLOR str = "#{time}" w = FONT.text_size(str)[0] FONT.draw_blended_utf8(screen, str, (SCREEN_W - w) / 2, H_SCREEN_H, 255, 255, 255) @ret.draw(screen) if time <= 0 @mark = SDL::get_ticks SPRITES.each{|s| s.init(screen) } @score = 0 @misses = 0 return :game end return :intro end def draw_dead(screen) @ret.tick(screen) screen.fill_rect 0, 0, SCREEN_W, SCREEN_H, BGCOLOR str = "You scored #{@score} points! Press A to try again." w = FONT.text_size(str)[0] FONT.draw_blended_utf8(screen, str, (SCREEN_W - w) / 2, H_SCREEN_H, 255, 255, 255) @ret.draw(screen) if @js.button(0) @mark = SDL::get_ticks return :intro end return :dead end def draw_game(screen) @timer = 60000 - (SDL::get_ticks - @mark) @ret.tick(screen) if @timer <= 0 return :dead end if @canshoot && @js.axis(5) > 0 && !@shooting && @ticks - @shotstart > 100 @shotstart = @ticks @shooting = true @canshoot = false end if !@canshoot && @js.axis(5) < 0 @canshoot = true end SPRITES.each do |s| s.tick(screen) if @shooting && s.hit?(@ret.x, @ret.y) @score += s.points debug "Hit: #{@score}" s.die elsif s.y < -(s.size / 2) @misses += 1 debug "Miss: #{@misses}" s.init(screen) end end @shooting = false if @ticks - @shotstart <= 20 screen.fill_rect 0, 0, SCREEN_W, SCREEN_H, LINECOLOR else screen.fill_rect 0, 0, SCREEN_W, SCREEN_H, BGCOLOR end @ret.draw(screen) FONT.draw_blended_utf8(screen, "Score: #{@score}", 5, 5, 255, 255, 255) FONT.draw_blended_utf8(screen, "Time: %2.2f" % [ @timer / 1000.0 ], 5, 5 + FONT.line_skip, 255, 255, 255) SPRITES.each{|s| s.draw(screen) } return :game end main_loop do @ticks = SDL::get_ticks case @state when :intro @state = draw_intro(screen) when :game @state = draw_game(screen) when :dead @state = draw_dead(screen) end screen.flip end
d3a346ed7137a1246b4806a89be4d7830c601132
[ "Ruby" ]
6
Ruby
bclarke123/ShootTheCan
a26b3c02fbe7e5c2daec8455639ed13dbf0845ea
b248188ea4dd4572c17bb895916db8e9c542d761
refs/heads/master
<repo_name>apelbeku/belajarGit-1<file_sep>/connection/koneksi.php <?php $serv = "localhost"; $user = "root"; $pas = "<PASSWORD>"; $db = "latihan_4_siswa"; $connect = mysqli_connect($serv, $user, $pas, $db); <file_sep>/user/index.php <!DOCTYPE html> <html> <head> <?php include '../layout/link.php'; ?> </head> <body class="hold-transition skin-blue sidebar-mini"> <!-- Site wrapper --> <div class="wrapper"> <header class="main-header"> <!-- Logo --> <a href="../AdminLTE2/index2.html" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><b>A</b>LT</span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>Admin</b>LTE</span> </a> <!-- Header Navbar: style can be found in header.less --> <?php include '../layout/header.php'; ?> </header> <!-- =============================================== --> <!-- Left side column. contains the sidebar --> <aside class="main-sidebar"> <!-- sidebar: style can be found in sidebar.less --> <?php include '../layout/sidebar.php'; ?> <!-- /.sidebar --> </aside> <!-- =============================================== --> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Dashboard User Data <small>Manajement data User</small> </h1> <ol class="breadcrumb"> <li class="active"><i class="fa fa-home">Dashboard</i></li> </ol> </section> <!-- Main content --> <section class="content"> <!-- Default box --> <div class="box"> <div class="box-header with-border"> <h3 class="box-title">Bordered Table</h3> </div> <!-- /.box-header --> <div class="box-body"> <table class="table table-bordered"> <tr> <th style="width: 10px">#</th> <th>Task</th> <th>Progress</th> <th style="width: 40px">Label</th> </tr> <tr> <td>1.</td> <td>Update software</td> <td> <div class="progress progress-xs"> <div class="progress-bar progress-bar-danger" style="width: 55%"></div> </div> </td> <td><span class="badge bg-red">55%</span></td> </tr> <tr> <td>2.</td> <td>Clean database</td> <td> <div class="progress progress-xs"> <div class="progress-bar progress-bar-yellow" style="width: 70%"></div> </div> </td> <td><span class="badge bg-yellow">70%</span></td> </tr> <tr> <td>3.</td> <td>Cron job running</td> <td> <div class="progress progress-xs progress-striped active"> <div class="progress-bar progress-bar-primary" style="width: 30%"></div> </div> </td> <td><span class="badge bg-light-blue">30%</span></td> </tr> <tr> <td>4.</td> <td>Fix and squish bugs</td> <td> <div class="progress progress-xs progress-striped active"> <div class="progress-bar progress-bar-success" style="width: 90%"></div> </div> </td> <td><span class="badge bg-green">90%</span></td> </tr> </table> </div> <!-- /.box-body --> <div class="box-footer clearfix"> <ul class="pagination pagination-sm no-margin pull-right"> <li><a href="#">&laquo;</a></li> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">&raquo;</a></li> </ul> </div> </div> <!-- /.box --> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <!-- footer --> <?php include '../layout/footer.php'; ?> <!-- /footer --> <!-- Control Sidebar --> <?php include '../layout/controlSidebar.php'; ?> <!-- /.control-sidebar --> <!-- Add the sidebar's background. This div must be placed immediately after the control sidebar --> <div class="control-sidebar-bg"></div> </div> <!-- ./wrapper --> <!-- jQuery 3 --> <?php include '../layout/jQuery3.php'; ?> <!-- /jQuery 3 --> </body> </html>
5236cc3c2e1c8eba544165c510e9a17d1788ef4d
[ "PHP" ]
2
PHP
apelbeku/belajarGit-1
c31ed09ac8c1a0e5c409ffe3ba753e85aeb03879
4861def5894fee32afe7916055abc2e24e32d286
refs/heads/master
<file_sep>server.port=8989 hschefu1=1c13abb17def941ceb90ed188779268 spring.profiles.active=@profileActive@ <file_sep># spring-boot02 测试部署 <file_sep>spring.datasource.url=jdbc:mysql://172.16.1.6:3306/tm-calc-testdrive?characterEncoding=utf8&useSSL=false&allowMultiQueries=true&queryTimeout=10000&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.datasource.type=com.alibaba.druid.pool.DruidDataSource cat.app.name=spring01 cat.server.ips=172.16.1.6:2280:8081<file_sep>package com.song.springboot.service; /** * @author King * @description api * @date 2020/8/20 **/ public interface HomeService { }
db25c76574015e9bbabe35ad5b27dc9784fe6698
[ "Markdown", "Java", "INI" ]
4
INI
niukouzz/spring-boot-clone
11dcdebfbb633cfef14fdc28cf9f44dcd230cf39
7ae012dc708ea16ce37e2a89afffb22303201784
refs/heads/master
<file_sep>import firebase from 'firebase/app'; import 'firebase/firestore'; import 'firebase/auth'; // Replace this with your own config details // Initialize Firebase var config = { apiKey: "<KEY>", authDomain: "mario-528c8.firebaseapp.com", databaseURL: "https://mario-528c8.firebaseio.com", projectId: "mario-528c8", storageBucket: "mario-528c8.appspot.com", messagingSenderId: "469876131897" }; firebase.initializeApp(config); firebase.firestore().settings({ timestampsInSnapshots: true }); export default firebase
8290ea2e1d93ae57048eecb95281a6a616b98a7a
[ "JavaScript" ]
1
JavaScript
Davit12345/mario-notification
cd288a5d7ad9399f4f7b7208b8ef22b157cd4609
d5c14c80510a88179058a45e0ce8138ddbc0b020
refs/heads/master
<repo_name>OrShemesh1992/phpMyAdmin-DB-CRUD<file_sep>/mysql/login_read.php <?php include "functions.php"; ?> <h1>Read</h1> <?php print_data(); ?> <file_sep>/mysql/login_delete.php <?php include "functions.php"; ?> <?php DeleteTable(); ?> <?php include "./includes/header.php"; ?> <body> <div class="container"> <div class="col-xs-6"> <form action="login_delete.php" method="post"> <h1>Delete</h1> <div class="form-group"> <select name="id" id=""> <?php showAllData(); ?> </select> </div> <input class = "btn btn-primary" type="submit" name="submit" value="Delete"> </form> </div> <?php include "./includes/footer.php"; ?> <file_sep>/mysql/login_update.php <?php include "functions.php"; ?> <?php UpdateTable(); ?> <?php include "./includes/header.php"; ?> <body> <div class="container"> <div class="col-xs-6"> <form action="login_update.php" method="post"> <h1>Update</h1> <div class="form-group"> <label for="username">User-name</label> <input type="text" name ="username" class="form-control"> </div> <div class="form-group"> <label for="password">Password</label> <input type="<PASSWORD>" name="password" class="form-control"> </div> <div class="form-group"> <select name="id" id=""> <?php showAllData(); ?> </select> </div> <input class = "btn btn-primary" type="submit" name="submit" value="Update"> </form> </div> <?php include "./includes/footer.php"; ?> <file_sep>/README.md # phpMyAdmin-DB-CRUD ![image](https://i0.wp.com/www.betterhostreview.com/wp-content/uploads/phpmyadmin.jpg)
8acb8a07ae69517bad4be5d725ae53e4e69ddd79
[ "Markdown", "PHP" ]
4
PHP
OrShemesh1992/phpMyAdmin-DB-CRUD
a4bd78f8b3b49747b49b61e9157746b08b2a47d5
14e794f8f12aabc248b4970058b5bfe050f12b32
refs/heads/master
<repo_name>advaitgupta/SchoolDataBase<file_sep>/Views/Forms/MainForm.h #ifndef MAIN_FORM_H #define MAIN_FORM_H #include <memory> #include <QMainWindow> #include "PagesMainForm/MainFormPageEmployees.h" #include "PagesMainForm/MainFormPageTeachers.h" #include "PagesMainForm/MainFormPagePupils.h" #include "PagesMainForm/MainFormPageSettings.h" namespace Ui { class MainForm; } class MainForm : public QMainWindow { Q_OBJECT public: explicit MainForm(QWidget* parent = 0); ~MainForm(); private slots: void clickedBtnReloadEmployees(); void clickedBtnAddEmploye(); void clickedBtnRemoveEmploye(); void clickedBtnSelectEmployees(); void clickedBtnSearchEmployees(); void clickedBtnAddProfession(); void clickedBtnRemoveProfession(); void clickedBtnAddPredmetForTeacher(); void clickedBtnRemoveTeacherPredmet(); void clickedBtnAddPredmet(); void clickedBtnRemovePredmet(); void clickedBtnAddPupil(); void clickedBtnRemovePupil(); void clickedBtnSelectPupils(); void clickedBtnSearchPupils(); void clickedBtnReloadPupils(); void clickedBtnAddParent(); void clickedBtnRemoveParent(); void selectedPupil(QModelIndex index); void clickedBtnAddClass(); void clickedBtnRemoveClass(); void clickedBtnAddAdmin(); void clickedBtnChangeAdminPassword(); void clickedBtnRemoveAdmin(); private: Ui::MainForm* _ui; std::unique_ptr<MainFormPageEmployees> _mainFormPageEmployees; std::unique_ptr<MainFormPageTeachers> _mainFormPageTeachers; std::unique_ptr<MainFormPagePupils> _mainFormPagePupils; std::unique_ptr<MainFormPageSettings> _mainFormPageSettings; }; #endif <file_sep>/Data/DAO/AdministratorsDAO.h #ifndef ADMINISTRATORS_DAO_H #define ADMINISTRATORS_DAO_H #include <QtSql> #include <QCryptographicHash> #include "Utils/DataBase.h" #include "IAdministratorsDAO.h" #include "Exceptions/AdministratorNotFound.h" #include "Exceptions/NotWorkingRequest.h" class AdministratorsDAO : public IAdministratorsDAO { public: AdministratorsDAO(); QPair<QString, QString> findAdministratorByLogin(const QString& login) override; QMap<QString, QString> findAllAdministrators() override; void addAdministrator(const QString& login, const QString& password) override; void removeAdministratorByLogin(const QString& login) override; virtual void changePasswordAdministratorByLogin(const QString& login, const QString& oldPassword, const QString& newPassword) override; QString hashPassword(const QString& password) override; private: QMap<QString, QString> _administrators; QString _basicSelectQuery; }; #endif <file_sep>/Utils/DataBase.cpp #include "DataBase.h" DataBase* DataBase::getInstance() { static DataBase instance; return &instance; } void DataBase::connect() { _dataBase = QSqlDatabase::addDatabase("QSQLITE"); QString path = "/home/vova/Desktop/build-SchoolDataBase-Desktop-Debug/School.db"; _dataBase.setDatabaseName(path); if (_dataBase.open()) { _log.info(__FILE__, "Connection with database was successful"); } else { _log.error(__FILE__, "Connection with database wasn't successful. Path to DB: " + path); exit(EXIT_FAILURE); } } <file_sep>/Data/DAO/TeachersDAO.cpp #include "TeachersDAO.h" QVector<QSharedPointer<Teacher>> TeachersDAO::findAllTeachers() { _teachers.clear(); QSqlQuery query; query.prepare("SELECT " "(SELECT e.name FROM employees e WHERE e.id = t.id_employe) AS name, " "(SELECT c.name FROM classes c WHERE c.id = t.id_class) AS class, " "p.name AS predmet " "FROM teachers_predmets tp " "LEFT JOIN predmets p ON p.id = tp.id_predmet " "LEFT JOIN teachers t ON t.id = tp.id_teacher " "GROUP BY name "); query.exec(); while (query.next()) { QString name = query.value(0).toString(); QString className = query.value(1).toString(); if(!_teachers.isEmpty() && _teachers.last()->getName() == name){ _teachers.last()->addPredmet(query.value(2).toString()); } else { QSharedPointer<Teacher> teacher(new Teacher(name, className)); teacher->addPredmet(query.value(2).toString()); _teachers.append(teacher); } } return _teachers; } void TeachersDAO::addPredmetForTeacher(const QString &nameTeacher, const QString &namePredmet) { QSqlQuery query; query.prepare("INSERT INTO teachers_predmets(id_teacher, id_predmet) " "VALUES( " "(SELECT t.id FROM teachers t WHERE t.id_employe = (SELECT e.id FROM employees e WHERE e.name = :nameTeacher)), " "(SELECT p.id FROM predmets p WHERE p.name = :namePredmet))"); query.bindValue(":nameTeacher", nameTeacher); query.bindValue(":namePredmet", namePredmet); if (!query.exec()) { QString exceptionMessage = "Error in adding a predemt for teacher [" + nameTeacher + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } void TeachersDAO::removePredmetTeacherByName(const QString &nameTeacher, const QString &namePredmet) { QSqlQuery query; query.prepare("DELETE FROM teachers_predmets " "WHERE id_teacher = (SELECT t.id FROM teachers t WHERE t.id_employe = (SELECT e.id FROM employees e WHERE e.name = :nameTeacher)) " "AND id_predmet = (SELECT p.id FROM predmets p WHERE p.name = :namePredmet)"); query.bindValue(":nameTeacher", nameTeacher); query.bindValue(":namePredmet", namePredmet); if (!query.exec()) { QString exceptionMessage = "Error in deleting a predemt of teacher [" + nameTeacher + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } <file_sep>/Data/Entity/Pupil.h #ifndef PUPIL_H #define PUPIL_H #include <QString> #include <QSharedPointer> class Pupil { QString _name; QString _dateBirth; QString _address; QString _nameClass; Pupil(QString name, QString dateBirth, QString address, QString nameClass) : _name(name), _dateBirth(dateBirth), _address(address), _nameClass(nameClass) {} public: class Builder { QString _name; QString _dateBirth; QString _address; QString _nameClass; public: Builder& setName(const QString& name); Builder& setDateBirth(const QString& dateBirth); Builder& setAddress(const QString& address); Builder& setNameClass(const QString& nameClass); QSharedPointer<Pupil> build(); }; QString getName() const; QString getDateBirth() const; QString getAddress() const; QString getNameClass() const; QString toString() const; friend std::ostream& operator << (std::ostream& os, Pupil *pupil); }; #endif <file_sep>/Data/DAO/IClassesDAO.h #ifndef ICLASSESDAO_H #define ICLASSESDAO_H #include <QVector> struct IClassesDAO { virtual QVector<QString> findAllClasses() = 0; virtual void addClass(const QString& name) = 0; virtual void removeClassByName(const QString& name) = 0; virtual void changeNameClass(const QString& oldName, const QString& newName) = 0; virtual ~IClassesDAO() {} }; #endif <file_sep>/Data/DAO/EmployeesDAO.h #ifndef EMPLOYEESDAO_H #define EMPLOYEESDAO_H #include <QtSql> #include <QSqlQuery> #include "IEmployeesDAO.h" #include "Exceptions/NotWorkingRequest.h" class EmployeesDAO : public IEmployeesDAO { public: EmployeesDAO(); QVector<QSharedPointer<Employe>> findAllEmployees() override; QVector<QSharedPointer<Employe>> findEmployeesByProfession(const QString& profession) override; QVector<QSharedPointer<Employe>> findEmployeesByName(const QString& name) override; void removeEmployeByName(const QString& name) override; void addEmployee(const QSharedPointer<Employe>& employe) override; private: void loadEmployeesInVectorFromDB(QSqlQuery& query); private: QVector<QSharedPointer<Employe>> _employees; QString _basicSelectQuery; }; #endif <file_sep>/Data/Service/ProfessionsService.cpp #include "ProfessionsService.h" QVector<QString> ProfessionsService::getAllProfessions() { return _professionsDAO->findAllProfessions(); } bool ProfessionsService::addProfession(QString &name) { try { _professionsDAO->addProfession(name); _log.debug(__FILE__, "Profession [" + name + "] was added."); return true; } catch (NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } bool ProfessionsService::removeProfessionByName(QString &name) { try { _professionsDAO->removeProfessionByName(name); _log.debug(__FILE__, "Profession [" + name + "] was deleted."); return true; } catch (NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } bool ProfessionsService::changeNameProfession(QString &oldName, QString &newName) { try { _professionsDAO->changeNameProfession(oldName, newName); _log.debug(__FILE__, "Profession [" + oldName + "] was changed on [" + newName + "]."); return true; } catch (NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } <file_sep>/Views/Forms/PagesMainForm/MainFormPageSettings.cpp #include "MainFormPageSettings.h" #include "ui_MainForm.h" MainFormPageSettings::MainFormPageSettings(Ui::MainForm* mainForm) : _administratorsService(new AdministratorsService), _modelAdministrators(new QStandardItemModel) { _ui = mainForm; QStringList headers = {"Логин", "Пароль"}; _modelAdministrators->setHorizontalHeaderLabels(headers); _ui->tableAdministrators->setModel(_modelAdministrators.data()); _ui->tableAdministrators->resizeColumnsToContents(); _ui->tableAdministrators->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); reloadAdministratorsInTable(); reloadAdministratorsInCheckBox(); } void MainFormPageSettings::reloadAdministratorsInTable() { QMap<QString, QString> administrators = _administratorsService->getAllAdministrators(); _modelAdministrators->removeRows(0, _modelAdministrators->rowCount()); size_t row = 0; for (auto it = administrators.begin(); it != administrators.end(); it++) { _modelAdministrators->setItem(row, 0, new QStandardItem(it.key())); //login _modelAdministrators->setItem(row, 1, new QStandardItem(it.value())); //password row++; } } void MainFormPageSettings::reloadAdministratorsInCheckBox() { QMap<QString, QString> administrators = _administratorsService->getAllAdministrators(); _ui->cbxAdminsLogin->clear(); _ui->cbxAdminsLogin->addItem("Не выбрано"); for (auto it = administrators.begin(); it != administrators.end(); it++) { _ui->cbxAdminsLogin->addItem(it.key()); } } void MainFormPageSettings::addAdministrator() { QString login = _ui->editAdminLogin->text(); QString password = _ui->editAdminPassword->text(); if (login.isEmpty()) { QMessageBox::critical(0, "Ошибка добавления", "Не введене логин, добавление администратора невозможно."); return; } if (password.isEmpty()) { QMessageBox::critical(0, "Ошибка добавления", "Не введене пароль, добавление администратора невозможно."); return; } if (_administratorsService->addAdministrator(login , password)) { QMessageBox::information(0, "Успешная операция", "Администратор [" + login + "] успешно добавлен."); _ui->editAdminLogin->setText(""); _ui->editAdminPassword->setText(""); reloadAdministratorsInTable(); reloadAdministratorsInCheckBox(); } else { QMessageBox::warning(0, "Неудачная операция", "Администратор [" + login + "] не был добавлен. Возможно такой администратор уже существует."); } } void MainFormPageSettings::changePasswordAdministrator() { QString login = _ui->cbxAdminsLogin->currentText(); QString oldPassword = _ui->editAdminOldPassword->text(); QString newPassword = _ui->editAdminNewPassword->text(); if (login == "Не выбрано") { QMessageBox::warning(0, "Ошибка изменения пароля", "Не выбран администратор для изменения пароля."); return; } if (oldPassword.isEmpty()) { QMessageBox::warning(0, "Ошибка изменения пароля", "Не введен старый пароль этого администартора."); return; } if(newPassword.isEmpty()) { QMessageBox::warning(0, "Ошибка изменения пароля", "Не введен новый пароль для администартора."); return; } if (_administratorsService->changePasswordAdministratoByLogin(login, oldPassword, newPassword)) { QMessageBox::information(0, "Успешная операция", "Пароль администратора[" + login + "] успешно изменен."); _ui->cbxAdminsLogin->setCurrentIndex(0); _ui->editAdminOldPassword->setText(""); _ui->editAdminNewPassword->setText(""); reloadAdministratorsInTable(); } else { QMessageBox::warning(0, "Неудачная операция", "Был введен неправильный страый пароль. Изменение пароля невозможно"); } } void MainFormPageSettings::removeAdministrator() { QModelIndexList selectedRows = getSelectedRows(_ui->tableAdministrators); if(selectedRows.isEmpty()) { QMessageBox::warning(0, "Ошибка удаления", "Не выбран(ы) администратор(ы) в таблице."); return; } QMessageBox::StandardButton confirm = QMessageBox::question(0, "Подтверждение", "Действительно хотите удалить администратора(ов)?", QMessageBox::Yes|QMessageBox::No); if(confirm == QMessageBox::Yes) { removeSelectedRows(selectedRows); reloadAdministratorsInTable(); reloadAdministratorsInCheckBox(); } } void MainFormPageSettings::removeSelectedRows(QModelIndexList selectedRows) { for (auto row : selectedRows) { QString login = row.data().toString(); if(_administratorsService->removeAdministratorByLogin(login)) { QMessageBox::information(0, "Успешная операция", "Администратор [" + login + "] успешно удален."); } else { QMessageBox::warning(0, "Неудачная операция", "Такого администратора не существует."); } } } <file_sep>/Data/Service/IPredmetsService.h #ifndef IPREDMETSSERVICE_H #define IPREDMETSSERVICE_H #include <QString> #include <QSharedPointer> #include "Data/Entity/Pupil.h" struct IPredmetsService { virtual QVector<QString> getAllPredmets() = 0; virtual bool addPredmet(const QString& name) = 0; virtual bool removePredmetByName(const QString& name) = 0; }; #endif <file_sep>/Data/Service/PredmetsService.cpp #include "PredmetsService.h" QVector<QString> PredmetsService::getAllPredmets() { return _predmetsDAO->findAllPredmets(); } bool PredmetsService::addPredmet(const QString &name) { try { _predmetsDAO->addPredmet(name); _log.debug(__FILE__, "Predmet [" + name + "] was added."); return true; } catch (NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } bool PredmetsService::removePredmetByName(const QString &name) { try { _predmetsDAO->removePredmetByName(name); _log.debug(__FILE__, "Predmet [" + name + "] was deleted."); return true; } catch (NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } <file_sep>/Data/Service/ParentsService.cpp #include "ParentsService.h" QVector<QSharedPointer<Parent> > ParentsService::getParentsByChild(const QString &name) { return _parentsDAO->findParentsByChild(name); } bool ParentsService::addParent(QSharedPointer<Parent> &parent) { try { _parentsDAO->addParent(parent); _log.debug(__FILE__, "Parent [" + parent->toString() + "] was added."); return true; } catch(NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } bool ParentsService::removeParentByName(const QString &name) { try { _parentsDAO->removeParentByName(name); _log.debug(__FILE__, "Parent [" + name + "] was deleted."); return true; } catch(NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } <file_sep>/Views/Dialogs/AddingEmployeDialog.h #ifndef ADD_STAFF_DIALOG_H #define ADD_STAFF_DIALOG_H #include <QDialog> #include <QMessageBox> #include <QInputDialog> #include <QSharedPointer> #include "Data/Entity/Employe.h" #include "Data/Service/ProfessionsService.h" namespace Ui { class AddingEmployeDialog; } class AddingEmployeDialog : public QDialog { Q_OBJECT public: explicit AddingEmployeDialog(QWidget *parent = 0); QSharedPointer<Employe> getData(); ~AddingEmployeDialog(); private: Ui::AddingEmployeDialog *_ui; QScopedPointer<IProfessionsService> _professionsService; bool isValidDialog(); private slots: void clickedBtnAddProfession(); void clickedBtnAccept(); void clickedBtnCancel(); }; #endif <file_sep>/Views/Dialogs/AddingPupilDialog.cpp #include "AddingPupilDialog.h" #include "ui_AddingPupilDialog.h" AddingPupilDialog::AddingPupilDialog(QWidget *parent) : QDialog(parent), _ui(new Ui::AddingPupilDialog), _classesService(new ClassesService) { _ui->setupUi(this); connect(_ui->btnAccept, SIGNAL(clicked(bool)), this, SLOT(clickedBtnAccept())); connect(_ui->btnCancel, SIGNAL(clicked(bool)), this, SLOT(clickedBtnCancel())); _ui->cbxClasses->addItem("Не выбрано"); QVector<QString> classes = _classesService->getAllClasses(); for (auto curClass : classes) { _ui->cbxClasses->addItem(curClass); } } QSharedPointer<Pupil> AddingPupilDialog::getData() { QSharedPointer<Pupil> pupil = Pupil::Builder() .setName(_ui->editName->text()) .setDateBirth(_ui->editDateBirth->text()) .setAddress(_ui->editAddress->text()) .setNameClass(_ui->cbxClasses->currentText()) .build(); return pupil; } void AddingPupilDialog::clickedBtnAccept() { if(isValidDialog()) { accept(); } } bool AddingPupilDialog::isValidDialog() { if (_ui->editName->text().isEmpty()) { QMessageBox::warning(0, "Ошибка", "Введите ФИО."); return false; } if (_ui->editDateBirth->text().isEmpty()) { QMessageBox::warning(0, "Ошибка", "Введите дату рождения."); return false; } if (_ui->editAddress->text().isEmpty()) { QMessageBox::warning(0, "Ошибка", "Введите адрес."); return false; } if (_ui->cbxClasses->currentText() == "Не выбрано") { QMessageBox::warning(0, "Ошибка", "Выберите профессию для сотрудника."); return false; } return true; } void AddingPupilDialog::clickedBtnCancel() { this->close(); } AddingPupilDialog::~AddingPupilDialog() { delete _ui; } <file_sep>/Data/Entity/Employe.cpp #include "Employe.h" QString Employe::getName() const { return _name; } QString Employe::getDateBirth() const { return _dateBirth; } QString Employe::getAddress() const { return _address; } QString Employe::getProfession() const { return _profession; } QString Employe::getPhoneNumber() const { return _phoneNumber; } QString Employe::getPersonalData() const { return _personalData; } Employe::Builder& Employe::Builder::setName(const QString &name) { _name = name; return *this; } Employe::Builder& Employe::Builder::setDateBirth(const QString &dateBirth) { _dateBirth = dateBirth; return *this; } Employe::Builder& Employe::Builder::setAddress(const QString& address) { _address = address; return *this; } Employe::Builder& Employe::Builder::setProfession(const QString& profession) { _profession = profession; return *this; } Employe::Builder& Employe::Builder::setPhoneNumber(const QString& phoneNumber) { _phoneNumber = phoneNumber; return *this; } Employe::Builder& Employe::Builder::setPersonalData(const QString& personalData) { _personalData = personalData; return *this; } QSharedPointer<Employe> Employe::Builder::build() { QSharedPointer<Employe> employePtr(new Employe(_name, _dateBirth, _address, _profession, _phoneNumber, _personalData)); return employePtr; } QString Employe::toString() const { return "name = " + _name + ", dateBirth = " + _dateBirth + ", address = " + _address + ", profession = " + _profession + ", phoneNumber = " + _phoneNumber + ", perosnalData = " + _personalData; } std::ostream& operator << (std::ostream &os, Employe *em) { os << "name = " << em->getName().toStdString() << ", dateBirth = " << em->getDateBirth().toStdString() << ", address = " << em->getAddress().toStdString() << ", profession = " << em->getProfession().toStdString() << ", phoneNumber = " << em->getPhoneNumber().toStdString() << ", perosnalData = " << em->getPersonalData().toStdString(); return os; } <file_sep>/Data/Service/ClassesService.h #ifndef CLASSESSERVICE_H #define CLASSESSERVICE_H #include "IClassesService.h" #include "Data/DAO/ClassesDAO.h" #include "Utils/Logger.h" class ClassesService : public IClassesService { Logger _log; QScopedPointer<IClassesDAO> _classesDAO; public: ClassesService() : _classesDAO(new ClassesDAO) {} QVector<QString> getAllClasses() override; bool addClass(const QString& name) override; bool removeClassByName(const QString& name) override; bool changeNameClass(const QString& oldName, const QString& newName) override; }; #endif <file_sep>/Data/DAO/ClassesDAO.cpp #include "ClassesDAO.h" QVector<QString> ClassesDAO::findAllClasses() { _classes.clear(); QSqlQuery query; query.prepare("SELECT name FROM classes"); query.exec(); while (query.next()) { _classes.append(query.value(0).toString()); } return _classes; } void ClassesDAO::addClass(const QString& name) { QSqlQuery query; query.prepare("INSERT INTO classes(name) VALUES(:name)"); query.bindValue(":name", name); if (!query.exec()) { QString exceptionMessage = "Error in adding class[" + name + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } void ClassesDAO::removeClassByName(const QString& name) { QSqlQuery query; query.prepare("DELETE FROM classes WHERE name = :name"); query.bindValue(":name", name); if (!query.exec()) { QString exceptionMessage = "Error in deleting class[" + name + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } void ClassesDAO::changeNameClass(const QString& oldName, const QString& newName) { QSqlQuery query; query.prepare("UPDATE classes SET name = :newName WHERE name = :oldName"); query.bindValue(":oldName", oldName); query.bindValue(":newName", newName); if (!query.exec()) { QString exceptionMessage = "Error in changing class[" + oldName + "] on [" + newName + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } <file_sep>/Data/Entity/Pupil.cpp #include "Pupil.h" Pupil::Builder &Pupil::Builder::setName(const QString &name) { _name = name; return *this; } Pupil::Builder &Pupil::Builder::setDateBirth(const QString &dateBirth) { _dateBirth = dateBirth; return *this; } Pupil::Builder &Pupil::Builder::setAddress(const QString& address) { _address = address; return *this; } Pupil::Builder &Pupil::Builder::setNameClass(const QString& nameClass) { _nameClass = nameClass; return *this; } QSharedPointer<Pupil> Pupil::Builder::build() { QSharedPointer<Pupil> pupil(new Pupil(_name, _dateBirth, _address, _nameClass)); return pupil; } QString Pupil::getName() const { return _name; } QString Pupil::getDateBirth() const { return _dateBirth; } QString Pupil::getAddress() const { return _address; } QString Pupil::getNameClass() const { return _nameClass; } QString Pupil::toString() const { return "name = " + _name + ", dateBirth = " + _dateBirth + ", address = " + _address + ", nameClass = " + _nameClass; } std::ostream& operator << (std::ostream &os, Pupil *p) { os << "name = " << p->getName().toStdString() << ", dateBirth = " << p->getDateBirth().toStdString() << ", address = " << p->getAddress().toStdString() << ", nameClass = " << p->getNameClass().toStdString(); return os; } <file_sep>/Views/Dialogs/AddingEmployeDialog.cpp #include "AddingEmployeDialog.h" #include "ui_AddingEmployeDialog.h" AddingEmployeDialog::AddingEmployeDialog(QWidget *parent) : QDialog(parent), _ui(new Ui::AddingEmployeDialog), _professionsService(new ProfessionsService) { _ui->setupUi(this); connect(_ui->btnAddProfession, SIGNAL(clicked(bool)), this, SLOT(clickedBtnAddProfession())); connect(_ui->btnAccept, SIGNAL(clicked(bool)), this, SLOT(clickedBtnAccept())); connect(_ui->btnCancel, SIGNAL(clicked(bool)), this, SLOT(clickedBtnCancel())); _ui->cbxProfessions->addItem("Не выбрано"); QVector<QString> professions = _professionsService->getAllProfessions(); for(auto it = professions.begin(); it != professions.end(); it++) { _ui->cbxProfessions->addItem(*it); } } QSharedPointer<Employe> AddingEmployeDialog::getData() { QSharedPointer<Employe> employe = Employe::Builder() .setName(_ui->editName->text()) .setDateBirth(_ui->editDateBirth->text()) .setAddress(_ui->editAddress->text()) .setPhoneNumber(_ui->editPhoneNumber->text()) .setPersonalData(_ui->editPersonalData->text()) .setProfession(_ui->cbxProfessions->currentText()) .build(); return employe; } void AddingEmployeDialog::clickedBtnAccept() { if (isValidDialog()) { accept(); } } bool AddingEmployeDialog::isValidDialog() { if (_ui->editName->text().isEmpty()) { QMessageBox::warning(0, "Ошибка", "Введите ФИО."); return false; } if (_ui->editDateBirth->text().isEmpty()) { QMessageBox::warning(0, "Ошибка", "Введите дату рождения."); return false; } if (_ui->editAddress->text().isEmpty()) { QMessageBox::warning(0, "Ошибка", "Введите адрес."); return false; } if (_ui->editPhoneNumber->text().isEmpty()) { QMessageBox::warning(0, "Ошибка", "Введите номер телефона."); return false; } if (_ui->editPersonalData->text().isEmpty()) { QMessageBox::warning(0, "Ошибка", "Введите персональные данные."); return false; } if (_ui->cbxProfessions->currentText() == "Не выбрано") { QMessageBox::warning(0, "Ошибка", "Выберите профессию для сотрудника."); return false; } return true; } void AddingEmployeDialog::clickedBtnAddProfession() { bool ok; QString name = QInputDialog::getText(this, "Добавление профессии", "Введите название профессии:", QLineEdit::Normal, QDir::home().dirName(), &ok); if (ok && !name.isEmpty()){ if(_professionsService->addProfession(name)){ _ui->cbxProfessions->addItem(name); QMessageBox::information(0, "Успешная операция", "Профессия [" + name + "] успешно добавлена."); } else { QMessageBox::warning(0, "Неудачная операция", "Профессия [" + name + "] не была добавлена. Возможно такая профессия уже существует."); } } } void AddingEmployeDialog::clickedBtnCancel() { this->close(); } AddingEmployeDialog::~AddingEmployeDialog() { delete _ui; } <file_sep>/Data/DAO/ProfessionsDAO.cpp #include "ProfessionsDAO.h" QVector<QString> ProfessionsDAO::findAllProfessions() { QVector<QString> professions; QSqlQuery query; query.prepare("SELECT name FROM professions"); query.exec(); while (query.next()) { professions.append(QString(query.value(0).toString())); } return professions; } void ProfessionsDAO::addProfession(QString &name) { QSqlQuery query; query.prepare("INSERT INTO professions(name) VALUES(:name)"); query.bindValue(":name", name); if (!query.exec()) { QString exceptionMessage = "Error in adding a profession[" + name + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } void ProfessionsDAO::removeProfessionByName(QString &name) { QSqlQuery query; query.prepare("DELETE FROM professions WHERE name = :name"); query.bindValue(":name", name); if (!query.exec()) { QString exceptionMessage = "Error in deleting a profession[" + name + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } void ProfessionsDAO::changeNameProfession(QString &oldName, QString &newName) { QSqlQuery query; query.prepare("UPDATE professions SET name = :newName WHERE name = :oldName"); query.bindValue(":oldName", oldName); query.bindValue(":newName", newName); if (!query.exec()) { QString exceptionMessage = "Error in changing profession[" + oldName + "] on [" + newName + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } <file_sep>/Views/Forms/PagesMainForm/MainFormPageEmployees.h #ifndef MAINFORMPAGEEMPLOYEES_H #define MAINFORMPAGEEMPLOYEES_H #include "Views/Dialogs/AddingEmployeDialog.h" #include "Data/Service/EmployeesService.h" #include "Data/Service/ProfessionsService.h" #include "MainFormPage.h" namespace Ui { class MainForm; } class MainFormPageEmployees : public MainFormPage { public: MainFormPageEmployees(Ui::MainForm* mainForm); void reloadEmployees(); void addEmploye(); void removeEmploye(); void selectEmployees(); void searchEmployees(); void addProfession(); void removeProfession(); private: void reloadEmployeesInTable(QVector<QSharedPointer<Employe>> employees); void reloadProfessionsInCheckBox(); void removeSelectedRows(QModelIndexList selectedRows); private: Ui::MainForm* _ui; QScopedPointer<IEmployeesService> _employeesService; QScopedPointer<IProfessionsService> _professionsService; QScopedPointer<QStandardItemModel> _modelEmployees; }; #endif <file_sep>/Views/Forms/MainFormPageTeachers.h #ifndef MAINFORMPAGETEACHERS_H #define MAINFORMPAGETEACHERS_H #include "Data/Service/TeachersService.h" #include "Data/Service/PredmetsService.h" #include "MainFormPage.h" namespace Ui { class MainForm; } class MainFormPageTeachers :public MainFormPage { public: MainFormPageTeachers(Ui::MainForm* mainForm); void removeTeacherPredmet(); void addPredmetForTeacher(); void addPredmet(); void removePredmet(); void reloadTeachersInTable(); void reloadTeachersInCheckBox(); private: void reloadPredmetsInCheckBox(); private: Ui::MainForm* _ui; QScopedPointer<ITeachersService> _teachersService; QScopedPointer<IPredmetsService> _predmetsService; QScopedPointer<QStandardItemModel> _modelTeachers; }; #endif <file_sep>/Data/DAO/IProfessionsDAO.h #ifndef IPROFESSIONSDAO_H #define IPROFESSIONSDAO_H #include <iostream> #include <QVector> struct IProfessionsDAO { virtual QVector<QString> findAllProfessions() = 0; virtual void addProfession(QString& name) = 0; virtual void removeProfessionByName(QString& name) = 0; virtual void changeNameProfession(QString& oldName, QString& newName) = 0; virtual ~IProfessionsDAO() {} }; #endif <file_sep>/Utils/Logger.cpp #include "Logger.h" void Logger::info(const char* file, const QString& message) { std::cout << "[INFO] " << getCurrentDateTine() << " " << file << " "<< message.toStdString() << std::endl; } void Logger::debug(const char* file, const QString& message) { std::cout << "[DEBUG] " << getCurrentDateTine() << " " << file << " "<< message.toStdString() << std::endl; } void Logger::warning(const char* file, const QString& message) { std::cerr << "[WARNING] " << getCurrentDateTine() << " " << file << " "<< message.toStdString() << std::endl; } void Logger::error(const char* file, const QString& message) { std::cerr << "[ERROR] " << getCurrentDateTine() << " " << file << " "<< message.toStdString() << std::endl; } std::string Logger::getCurrentDateTine() { return QDateTime::currentDateTime().toString("dd.MM.yy HH:mm:ss").toStdString(); } <file_sep>/Views/Forms/PagesMainForm/MainFormPage.cpp #include "MainFormPage.h" QModelIndexList MainFormPage::getSelectedRows(QTableView* table) { QAbstractItemView* view = table; QItemSelectionModel* selectedModel = view->selectionModel(); return selectedModel->selectedRows(); } <file_sep>/Views/Dialogs/AddingParentDialog.cpp #include "AddingParentDialog.h" #include "ui_AddingParentDialog.h" AddingParentDialog::AddingParentDialog(QWidget *parent) : QDialog(parent), _ui(new Ui::AddingParentDialog), _pupilsService(new PupilsService) { _ui->setupUi(this); connect(_ui->btnAccept, SIGNAL(clicked(bool)), this, SLOT(clickedBtnAccept())); connect(_ui->btnCancel, SIGNAL(clicked(bool)), this, SLOT(clickedBtnCancel())); _ui->cbxPupils->addItem("Не выбрано"); QVector<QSharedPointer<Pupil>> pupils = _pupilsService->getAllPupils(); for (auto pupil : pupils) { _ui->cbxPupils->addItem(pupil->getName()); } } QSharedPointer<Parent> AddingParentDialog::getData() { QSharedPointer<Parent> parent = Parent::Builder() .setName(_ui->editName->text()) .setDateBirth(_ui->editDateBirth->text()) .setAddress(_ui->editAddress->text()) .setChild(_ui->cbxPupils->currentText()) .build(); return parent; } void AddingParentDialog::clickedBtnAccept() { if(isValidDialog()) { accept(); } } bool AddingParentDialog::isValidDialog() { if(_ui->editName->text().isEmpty()) { QMessageBox::warning(0, "Ошибка", "Введите ФИО."); return false; } if(_ui->editDateBirth->text().isEmpty()) { QMessageBox::warning(0, "Ошибка", "Введите дату рождения."); return false; } if(_ui->editAddress->text().isEmpty()) { QMessageBox::warning(0, "Ошибка", "Введите адрес."); return false; } if(_ui->cbxPupils->currentText() == "Не вбырано") { QMessageBox::warning(0, "Ошибка", "Введите ребенка для родителя."); return false; } return true; } void AddingParentDialog::clickedBtnCancel() { this->close(); } AddingParentDialog::~AddingParentDialog() { delete _ui; } <file_sep>/Views/Forms/LoginForm.cpp #include "LoginForm.h" #include "ui_LogInForm.h" LoginForm::LoginForm(QWidget* parent) : QMainWindow(parent), _ui(new Ui::LoginForm), _administratorsService(new AdministratorsService) { _ui->setupUi(this); connect(_ui->btnLogin, SIGNAL(clicked(bool)), this, SLOT(clickedBtnLogin())); connect(_ui->cbxShowPassword, SIGNAL(clicked(bool)), this, SLOT(clickedCbxShowPassword())); } void LoginForm::clickedBtnLogin() { QString login = _ui->editLogin->text(); QString password = _ui->editPassword->text(); if(isValidForm()) { if(_administratorsService->isExistAdministrator(login, password)) { MainForm* mainForm = new MainForm; mainForm->show(); this->close(); } else { QMessageBox::warning(this, "Ошибка авторизация", "Вы ввели не правильный логин или пароль."); } } } bool LoginForm::isValidForm() { if(_ui->editLogin->text().isEmpty()) { QMessageBox::critical(this, "Ошибка авторизации", "Не введене логин, авторизация невозможна."); return false; } if(_ui->editPassword->text().isEmpty()) { QMessageBox::critical(this, "Ошибка авторизации", "Не введене пароль, авторизация невозможна."); return false; } return true; } void LoginForm::clickedCbxShowPassword() { if(_ui->cbxShowPassword->isChecked()) { _ui->editPassword->setEchoMode(QLineEdit::Normal); } else { _ui->editPassword->setEchoMode(QLineEdit::Password); } } LoginForm::~LoginForm() { delete _ui; } <file_sep>/Views/Forms/PagesMainForm/MainFormPageEmployees.cpp #include "MainFormPageEmployees.h" #include "ui_MainForm.h" MainFormPageEmployees::MainFormPageEmployees(Ui::MainForm* mainForm) : _ui(mainForm), _employeesService(new EmployeesService), _professionsService(new ProfessionsService), _modelEmployees(new QStandardItemModel) { QStringList headers = {"ФИО", "Дата рождения", "Адрес", "Профессия", "Номер телефона", "Персональные данные"}; _modelEmployees->setHorizontalHeaderLabels(headers); _ui->tableEmployees->setModel(_modelEmployees.data()); _ui->tableEmployees->resizeColumnsToContents(); _ui->tableEmployees->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); reloadEmployeesInTable(_employeesService->getAllEmployees()); reloadProfessionsInCheckBox(); } void MainFormPageEmployees::reloadEmployeesInTable(QVector<QSharedPointer<Employe> > employees) { _modelEmployees->removeRows(0, _modelEmployees->rowCount()); for (long i = 0; i < employees.size(); i++) { _modelEmployees->setItem(i, 0, new QStandardItem(employees.at(i)->getName())); _modelEmployees->setItem(i, 1, new QStandardItem(employees.at(i)->getDateBirth())); _modelEmployees->setItem(i, 2, new QStandardItem(employees.at(i)->getAddress())); _modelEmployees->setItem(i, 3, new QStandardItem(employees.at(i)->getProfession())); _modelEmployees->setItem(i, 4, new QStandardItem(employees.at(i)->getPhoneNumber())); _modelEmployees->setItem(i, 5, new QStandardItem(employees.at(i)->getPersonalData())); } } void MainFormPageEmployees::reloadProfessionsInCheckBox() { QVector<QString> professions = _professionsService->getAllProfessions(); _ui->cbxProfessions->clear(); _ui->cbxProfessions->addItem("Не выбрано"); _ui->cbxDeletingProfession->clear(); _ui->cbxDeletingProfession->addItem("Не выбрано"); for (auto profession : professions) { _ui->cbxProfessions->addItem(profession); _ui->cbxDeletingProfession->addItem(profession); } } void MainFormPageEmployees::reloadEmployees() { reloadEmployeesInTable(_employeesService->getAllEmployees()); reloadProfessionsInCheckBox(); QMessageBox::information(0, "Успешная операция", "Сотрудники и их профессии успешно обновлены."); } void MainFormPageEmployees::addEmploye() { AddingEmployeDialog addingEmployeDialog; if (addingEmployeDialog.exec() == QDialog::Accepted) { QSharedPointer<Employe> employe = addingEmployeDialog.getData(); if (_employeesService->addEmploye(employe)) { QMessageBox::information(0, "Успешная операция", "Сотрудник [" + employe->getName() + "] был успешно добавлен."); reloadEmployeesInTable(_employeesService->getAllEmployees()); } else { QMessageBox::warning(0, "Неуспешная операция", "Видимо уже существует такой сотрудник с таким именем, добавление нового невозможно."); } } } void MainFormPageEmployees::removeEmploye() { QModelIndexList selectedRows = getSelectedRows(_ui->tableEmployees); if (selectedRows.isEmpty()) { QMessageBox::warning(0, "Ошибка удаления", "Не выбран(ы) сотрудник(и) в таблице."); return; } QMessageBox::StandardButton confirm = QMessageBox::question(0, "Подтверждение", "Действительно хотите удалить сотрудника(ов)?", QMessageBox::Yes|QMessageBox::No); if(confirm == QMessageBox::Yes) { removeSelectedRows(selectedRows); reloadEmployeesInTable(_employeesService->getAllEmployees()); } } void MainFormPageEmployees::removeSelectedRows(QModelIndexList selectedRows) { for (auto row : selectedRows) { QString name = row.data().toString(); if(_employeesService->removeEmployeByName(name)) { QMessageBox::information(0, "Успешная операция", "Сотрудник [" + name + "] успешно удален."); } else { QMessageBox::warning(0, "Неудачная операция", "Такого сотрудника не существует."); } } } void MainFormPageEmployees::selectEmployees() { QString profession = _ui->cbxProfessions->currentText(); if (profession == "Не выбрано") { QMessageBox::critical(0, "Ошибка выборки", "Не выбрана профессия, выборка сотрудников невозможна."); return; } reloadEmployeesInTable(_employeesService->selectEmployeesByProfession(profession)); } void MainFormPageEmployees::searchEmployees() { QString name = _ui->editSearchEmployee->text(); if (name.isEmpty()) { QMessageBox::critical(0, "Ошибка поиска", "Не введено ФИО сотрудника, поиск невозможна."); return; } reloadEmployeesInTable(_employeesService->searchEmployeesByName(name)); } void MainFormPageEmployees::addProfession() { QString profession = _ui->editAddingProfession->text(); if (profession.isEmpty()) { QMessageBox::critical(0, "Ошибка добавления", "Не введено название профессии, добавление невозможно."); return; } if(_professionsService->addProfession(profession)){ QMessageBox::information(0, "Успешная операция", "Профессия [" + profession + "] успешно добавлена."); reloadProfessionsInCheckBox(); _ui->editAddingProfession->setText(""); } else { QMessageBox::warning(0, "Неудачная операция", "Профессия [" + profession + "] не была добавлена. Возможно такая профессия уже существует."); } } void MainFormPageEmployees::removeProfession() { QString profession = _ui->cbxDeletingProfession->currentText(); if (profession == "Не выбрано") { QMessageBox::critical(0, "Ошибка удаления", "Не выбрано название профессии, удаление невозможно."); return; } if(_professionsService->removeProfessionByName(profession)){ QMessageBox::information(0, "Успешная операция", "Профессия [" + profession + "] успешно удалена."); reloadProfessionsInCheckBox(); } else { QMessageBox::warning(0, "Неудачная операция", "Профессия [" + profession + "] не была удалена."); } } <file_sep>/Data/Service/ParentsService.h #ifndef PARENTSSERVICE_H #define PARENTSSERVICE_H #include "IParentsService.h" #include "Utils/Logger.h" #include "Data/DAO/ParentsDAO.h" #include "Exceptions/NotWorkingRequest.h" #include "Data/Service/IParentsService.h" class ParentsService : public IParentsService { Logger _log; QScopedPointer<IParentsDAO> _parentsDAO; public: ParentsService() : _parentsDAO(new ParentsDAO) {} QVector<QSharedPointer<Parent>> getParentsByChild(const QString& name) override; bool addParent(QSharedPointer<Parent>& parent) override; bool removeParentByName(const QString& name) override; }; #endif <file_sep>/Data/DAO/PupilsDAO.h #ifndef PUPILSDAO_H #define PUPILSDAO_H #include <QtSql> #include <QSqlQuery> #include "IPupilsDAO.h" #include "Data/Entity/Pupil.h" #include "Exceptions/NotWorkingRequest.h" class PupilsDAO : public IPupilsDAO { public: PupilsDAO(); QVector<QSharedPointer<Pupil>> findAllPupils() override; QVector<QSharedPointer<Pupil>> findPupilsByClass(const QString& nameClass) override; QVector<QSharedPointer<Pupil>> findPupilsByName(const QString& name) override; void addPupil(const QSharedPointer<Pupil>& pupil) override; void removePupilByName(const QString& name) override; private: void loadPupilsInVectorFromDB(QSqlQuery& query); private: QVector<QSharedPointer<Pupil>> _pupils; QString _basicSelectQuery; }; #endif <file_sep>/Data/DAO/IEmployeesDAO.h #ifndef IEMPLOYEESDAO_H #define IEMPLOYEESDAO_H #include <QVector> #include <QSharedPointer> #include "Data/Entity/Employe.h" struct IEmployeesDAO { virtual QVector<QSharedPointer<Employe>> findAllEmployees() = 0; virtual QVector<QSharedPointer<Employe>> findEmployeesByProfession(const QString& profession) = 0; virtual QVector<QSharedPointer<Employe>> findEmployeesByName(const QString& name) = 0; virtual void removeEmployeByName(const QString& name) = 0; virtual void addEmployee(const QSharedPointer<Employe>& employe) = 0; virtual ~IEmployeesDAO() {} }; #endif <file_sep>/Data/Service/IEmployeesService.h #ifndef IEMPLOYEESSERVICE_H #define IEMPLOYEESSERVICE_H #include <QVector> #include <QSharedPointer> #include "Data/Entity/Employe.h" struct IEmployeesService{ virtual QVector<QSharedPointer<Employe>> getAllEmployees() = 0; virtual QVector<QSharedPointer<Employe>> searchEmployeesByName(const QString& name) = 0; virtual QVector<QSharedPointer<Employe>> selectEmployeesByProfession(const QString& profession) = 0; virtual bool addEmploye(const QSharedPointer<Employe>& employe) = 0; virtual bool removeEmployeByName(const QString& name) = 0; virtual ~IEmployeesService() {} }; #endif <file_sep>/Views/Forms/PagesMainForm/MainFormPage.h #ifndef MAINFORMPAGE_H #define MAINFORMPAGE_H #include <QVector> #include <QTableView> #include <QCheckBox> #include <QMessageBox> #include <QInputDialog> #include <QSharedPointer> #include <QScopedPointer> #include <QStandardItem> #include <QStandardItemModel> class MainFormPage { protected: QModelIndexList getSelectedRows(QTableView* table); }; #endif <file_sep>/Views/Dialogs/AddingParentDialog.h #ifndef ADD_PARENT_DIALOG_H #define ADD_PARENT_DIALOG_H #include <QVector> #include <QMessageBox> #include <QScopedPointer> #include <QSharedPointer> #include "Data/Entity/Parent.h" #include "Data/Service/PupilsService.h" namespace Ui { class AddingParentDialog; } class AddingParentDialog : public QDialog { Q_OBJECT public: explicit AddingParentDialog(QWidget *parent = 0); QSharedPointer<Parent> getData() ; ~AddingParentDialog(); private: Ui::AddingParentDialog *_ui; QScopedPointer<IPupilsService> _pupilsService; bool isValidDialog(); private slots: void clickedBtnAccept(); void clickedBtnCancel(); }; #endif <file_sep>/Data/DAO/IPupilsDAO.h #ifndef IPUPILSDAO_H #define IPUPILSDAO_H #include <QString> #include <QSharedPointer> #include "Data/Entity/Pupil.h" struct IPupilsDAO { virtual QVector<QSharedPointer<Pupil>> findPupilsByClass(const QString& nameClass) = 0; virtual QVector<QSharedPointer<Pupil>> findPupilsByName(const QString& name) = 0; virtual QVector<QSharedPointer<Pupil>> findAllPupils() = 0; virtual void addPupil(const QSharedPointer<Pupil>& pupil) = 0; virtual void removePupilByName(const QString& name) = 0; virtual ~IPupilsDAO() {} }; #endif <file_sep>/Utils/DataBase.h #ifndef DATABASE_H #define DATABASE_H #include <QtSql> #include <QtSql/QSqlDatabase> #include "Utils/Logger.h" class DataBase { public: static DataBase* getInstance(); void connect(); private: QSqlDatabase _dataBase; Logger _log; DataBase() {} }; #endif <file_sep>/Views/Forms/PagesMainForm/MainFormPagePupils.h #ifndef MAINFORMPAGEPUPILS_H #define MAINFORMPAGEPUPILS_H #include "MainFormPage.h" #include "Data/Service/PupilsService.h" #include "Data/Service/ParentsService.h" #include "Data/Service/ClassesService.h" #include "Views/Dialogs/AddingPupilDialog.h" #include "Views/Dialogs/AddingParentDialog.h" namespace Ui { class MainForm; } class MainFormPagePupils : public MainFormPage { public: MainFormPagePupils(Ui::MainForm* mainForm); void reloadPupilsAndParents(); void addPupil(); void removePupil(); void selectPupils(); void searchPupils(); void addParent(); void removeParent(); void showParentsSelectedPupil(QModelIndex index); void addClass(); void removeClass(); private: void reloadPupilsInTable(QVector<QSharedPointer<Pupil>> pupils); void reloadParentsInTable(QVector<QSharedPointer<Parent>> parents); void reloadClassesInCheckBox(); private: Ui::MainForm* _ui; QScopedPointer<IPupilsService> _pupilsService; QScopedPointer<IParentsService> _parentsService; QScopedPointer<IClassesService> _classesService; QScopedPointer<QStandardItemModel> _modelPupils; QScopedPointer<QStandardItemModel> _modelParents; }; #endif <file_sep>/Data/Service/ClassesService.cpp #include "ClassesService.h" QVector<QString> ClassesService::getAllClasses() { return _classesDAO->findAllClasses(); } bool ClassesService::addClass(const QString& name) { try { _classesDAO->addClass(name); _log.debug(__FILE__, "Class [" + name + "] was added."); return true; } catch(NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } bool ClassesService::removeClassByName(const QString& name) { try { _classesDAO->removeClassByName(name); _log.debug(__FILE__, "Class [" + name + "] was deleted."); return true; } catch(NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } bool ClassesService::changeNameClass(const QString& oldName, const QString& newName) { try { _classesDAO->changeNameClass(oldName, newName); _log.debug(__FILE__, "Class [" + oldName + "] was changed on [" + newName + "]."); return true; } catch(NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } <file_sep>/Views/Forms/LoginForm.h #ifndef LOGIN_FORM_H #define LOGIN_FORM_H #include <QMainWindow> #include <QScopedPointer> #include <QMessageBox> #include "MainForm.h" #include "Data/Service/IAdministratorsService.h" #include "Data/Service/AdministratorsService.h" namespace Ui { class LoginForm; } class LoginForm : public QMainWindow { Q_OBJECT public: explicit LoginForm(QWidget* parent = 0); ~LoginForm(); private slots: void clickedBtnLogin(); void clickedCbxShowPassword(); private: Ui::LoginForm* _ui; QScopedPointer<IAdministratorsService> _administratorsService; bool isValidForm(); }; #endif <file_sep>/Data/Service/PredmetsService.h #ifndef PREDMETSSERVICE_H #define PREDMETSSERVICE_H #include "IPredmetsService.h" #include "Utils/Logger.h" #include "Data/DAO/PredmetsDAO.h" #include "Exceptions/NotWorkingRequest.h" class PredmetsService : public IPredmetsService { Logger _log; QScopedPointer<IPredmetsDAO> _predmetsDAO; public: PredmetsService() : _predmetsDAO(new PredmetsDAO) {} QVector<QString> getAllPredmets() override; bool addPredmet(const QString& name) override; bool removePredmetByName(const QString& name) override; }; #endif <file_sep>/Data/DAO/PredmetsDAO.cpp #include "PredmetsDAO.h" QVector<QString> PredmetsDAO::findAllPredmets() { QVector<QString> predmets; QSqlQuery query; query.prepare("SELECT name FROM predmets"); query.exec(); while (query.next()) { predmets.append(QString(query.value(0).toString())); } return predmets; } void PredmetsDAO::addPredmet(const QString &name) { QSqlQuery query; query.prepare("INSERT INTO predmets(name) VALUES(:name)"); query.bindValue(":name", name); if (!query.exec()) { QString exceptionMessage = "Error in adding a predmet[" + name + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } void PredmetsDAO::removePredmetByName(const QString &name) { QSqlQuery query; query.prepare("DELETE FROM predmets WHERE name = :name"); query.bindValue(":name", name); if (!query.exec()) { QString exceptionMessage = "Error in deleting a predmet[" + name + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } void PredmetsDAO::changeNamePredmet(const QString &oldName, const QString &newName) { QSqlQuery query; query.prepare("UPDATE predmets SET name = :newName WHERE name = :oldName"); query.bindValue(":oldName", oldName); query.bindValue(":newName", newName); if (!query.exec()) { QString exceptionMessage = "Error in changing predmet[" + oldName + "] on [" + newName + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } <file_sep>/Data/DAO/IAdministratorsDAO.h #ifndef IADMINISTRATORSDAO_H #define IADMINISTRATORSDAO_H #include <iostream> #include <QPair> #include <QMap> struct IAdministratorsDAO { virtual QPair<QString, QString> findAdministratorByLogin(const QString& login) = 0; virtual QMap<QString, QString> findAllAdministrators() = 0; virtual void addAdministrator(const QString& login, const QString& password) = 0; virtual void removeAdministratorByLogin(const QString& login) = 0; virtual void changePasswordAdministratorByLogin(const QString& login, const QString& oldPassword, const QString& newPassword) = 0; virtual QString hashPassword(const QString& password) = 0; virtual ~IAdministratorsDAO() {} }; #endif <file_sep>/Data/Service/PupilsService.h #ifndef PUPILSSERVICE_H #define PUPILSSERVICE_H #include <QScopedPointer> #include "Utils/Logger.h" #include "Data/DAO/PupilsDAO.h" #include "Exceptions/NotWorkingRequest.h" #include "Data/Service/IPupilsService.h" class PupilsService : public IPupilsService { Logger _log; QScopedPointer<IPupilsDAO> _pupilsDAO; public: PupilsService() : _pupilsDAO(new PupilsDAO) {} QVector<QSharedPointer<Pupil>> getPupilsByClass(const QString& nameClass) override; QVector<QSharedPointer<Pupil>> getPupilsByName(const QString& name) override; QVector<QSharedPointer<Pupil>> getAllPupils() override; bool addPupil(const QSharedPointer<Pupil>& pupil) override; bool removePupilByName(const QString& name) override; }; #endif <file_sep>/Data/DAO/ClassesDAO.h #ifndef CLASSESDAO_H #define CLASSESDAO_H #include <QtSql> #include <QSqlQuery> #include "IClassesDAO.h" #include "Exceptions/NotWorkingRequest.h" class ClassesDAO : public IClassesDAO { public: QVector<QString> findAllClasses() override; void addClass(const QString& name) override; void removeClassByName(const QString& name) override; void changeNameClass(const QString& oldName, const QString& newName) override; private: QVector<QString> _classes; }; #endif <file_sep>/Views/Dialogs/AddingPupilDialog.h #ifndef ADDING_PUPIL_DIALOG_H #define ADDING_PUPIL_DIALOG_H #include <QDialog> #include <QMessageBox> #include <QSharedPointer> #include <QScopedPointer> #include "Data/Entity/Pupil.h" #include "Data/Service/ClassesService.h" namespace Ui { class AddingPupilDialog; } class AddingPupilDialog : public QDialog { Q_OBJECT public: explicit AddingPupilDialog(QWidget *parent = 0); QSharedPointer<Pupil> getData(); ~AddingPupilDialog(); private: Ui::AddingPupilDialog *_ui; QScopedPointer<IClassesService> _classesService; bool isValidDialog(); private slots: void clickedBtnAccept(); void clickedBtnCancel(); }; #endif <file_sep>/Data/Service/IClassesService.h #ifndef ICLASSESSERVICE_H #define ICLASSESSERVICE_H #include <QVector> struct IClassesService { virtual QVector<QString> getAllClasses() = 0; virtual bool addClass(const QString& name) = 0; virtual bool removeClassByName(const QString& name) = 0; virtual bool changeNameClass(const QString& oldName, const QString& newName) = 0; }; #endif <file_sep>/Utils/Logger.h #ifndef LOGGER_H #define LOGGER_H #include <iostream> #include <QString> #include <QDateTime> class Logger { std::string getCurrentDateTine(); public: void info(const char* file, const QString& message); void debug(const char* file, const QString& message); void warning(const char* file, const QString& message); void error(const char* file, const QString& message); }; #endif <file_sep>/Exceptions/NotWorkingRequest.h #ifndef NOTWORKINGREQUEST_H #define NOTWORKINGREQUEST_H #include <QString> class NotWorkingRequest { QString _message; public: NotWorkingRequest(const QString& message) : _message(message) {} QString what() const { return "Not working request. Exception: " + _message; } }; #endif <file_sep>/Data/DAO/TeachersDAO.h #ifndef TEACHERSDAO_H #define TEACHERSDAO_H #include <QtSql> #include <QSqlQuery> #include "ITeachersDAO.h" #include "Exceptions/NotWorkingRequest.h" class TeachersDAO : public ITeachersDAO { public: QVector<QSharedPointer<Teacher>> findAllTeachers() override; void addPredmetForTeacher(const QString& nameTeacher, const QString& namePredmet) override; void removePredmetTeacherByName(const QString& nameTeacher, const QString& namePredmet) override; private: QVector<QSharedPointer<Teacher>> _teachers; }; #endif <file_sep>/Views/Forms/PagesMainForm/MainFormPageSettings.h #ifndef MAINFORMSETTINGS_H #define MAINFORMSETTINGS_H #include "Data/Service/AdministratorsService.h" #include "MainFormPage.h" namespace Ui { class MainForm; } class MainFormPageSettings : public MainFormPage { public: MainFormPageSettings(Ui::MainForm* mainForm); void addAdministrator(); void changePasswordAdministrator(); void removeAdministrator(); private: void reloadAdministratorsInTable(); void reloadAdministratorsInCheckBox(); void removeSelectedRows(QModelIndexList selectedRows); private: Ui::MainForm* _ui; QScopedPointer<IAdministratorsService> _administratorsService; QScopedPointer<QStandardItemModel> _modelAdministrators; }; #endif <file_sep>/Data/Service/ProfessionsService.h #ifndef PROFESSIONSSERVICE_H #define PROFESSIONSSERVICE_H #include <QScopedPointer> #include "IProfessionsService.h" #include "Data/DAO/ProfessionsDAO.h" #include "Utils/Logger.h" #include "Exceptions/NotWorkingRequest.h" class ProfessionsService : public IProfessionsService { Logger _log; QScopedPointer<IProfessionsDAO> _professionsDAO; public: ProfessionsService() : _professionsDAO(new ProfessionsDAO) {} QVector<QString> getAllProfessions() override; bool addProfession(QString &name) override; bool removeProfessionByName(QString &name) override; bool changeNameProfession(QString &oldName, QString &newName) override; }; #endif <file_sep>/Data/DAO/ParentsDAO.h #ifndef PARENTSDAO_H #define PARENTSDAO_H #include <QtSql> #include <QSqlQuery> #include "IParentsDAO.h" #include "Exceptions/NotWorkingRequest.h" class ParentsDAO : public IParentsDAO { QVector<QSharedPointer<Parent>> _parents; public: QVector<QSharedPointer<Parent>> findParentsByChild(const QString& name) override; void addParent(QSharedPointer<Parent>& parent) override; void removeParentByName(const QString& name) override; }; #endif <file_sep>/Data/Service/TeachersService.cpp #include "TeachersService.h" QVector<QSharedPointer<Teacher> > TeachersService::getAllTeachers() { return _teachersDAO->findAllTeachers(); } bool TeachersService::addPredmetForTeacher(const QString &nameTeacher, const QString &namePredmet) { try { _teachersDAO->addPredmetForTeacher(nameTeacher, namePredmet); _log.debug(__FILE__, "Predmet for teacher [" + nameTeacher + "] was added."); return true; } catch(NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } bool TeachersService::removePredmetTeacherByName(const QString &nameTeacher, const QString &namePredmet) { try { _teachersDAO->removePredmetTeacherByName(nameTeacher, namePredmet); _log.debug(__FILE__, "Predmet of teacher [" + nameTeacher + "] was deleted."); return true; } catch(NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } <file_sep>/Exceptions/ParentNotFound.h #ifndef PARENTNOTFOUND_H #define PARENTNOTFOUND_H #include <QString> class ParentNotFound { QString _message; public: ParentNotFound(const QString& message) : _message(message) {} QString what() const { return "Parent not found. Exception: " + _message; } }; #endif <file_sep>/Views/Forms/MainFormPageTeachers.cpp #include "MainFormPageTeachers.h" #include "ui_MainForm.h" MainFormPageTeachers::MainFormPageTeachers(Ui::MainForm *mainForm) : _ui(mainForm), _teachersService(new TeachersService), _predmetsService(new PredmetsService), _modelTeachers(new QStandardItemModel){ QStringList headerTeachers = { "ФИО", "Класс", "Предметы" }; _modelTeachers->setHorizontalHeaderLabels(headerTeachers); _ui->tableTeachers->setModel(_modelTeachers.data()); _ui->tableTeachers->resizeColumnsToContents(); _ui->tableTeachers->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); reloadTeachersInTable(); reloadTeachersInCheckBox(); reloadPredmetsInCheckBox(); } void MainFormPageTeachers::reloadTeachersInTable() { _modelTeachers->removeRows(0, _modelTeachers->rowCount()); QVector<QSharedPointer<Teacher>> teachers = _teachersService->getAllTeachers(); for (long i = 0; i < teachers.size(); i++) { _modelTeachers->setItem(i, 0, new QStandardItem(teachers.at(i)->getName())); _modelTeachers->setItem(i, 1, new QStandardItem(teachers.at(i)->getNameClass())); QVector<QString> predmets = teachers.at(i)->getPredmets(); QString predmetsTeacher; for(QString predmet : predmets) { predmetsTeacher.append(predmet + " "); } _modelTeachers->setItem(i, 2, new QStandardItem(predmetsTeacher)); } } void MainFormPageTeachers::reloadTeachersInCheckBox() { _ui->cbxTeachers->clear(); _ui->cbxTeachersForAddingPredmer->clear(); _ui->cbxTeachers->addItem("Не выбрано"); _ui->cbxTeachersForAddingPredmer->addItem("Не выбрано"); QVector<QSharedPointer<Teacher>> teachers = _teachersService->getAllTeachers(); for (auto teacher : teachers) { _ui->cbxTeachers->addItem(teacher->getName()); _ui->cbxTeachersForAddingPredmer->addItem(teacher->getName()); } } void MainFormPageTeachers::reloadPredmetsInCheckBox() { _ui->cbxAddingPredmetForTeacher->clear(); _ui->cbxDeletingPredmet->clear(); _ui->cbxPredmets->clear(); _ui->cbxAddingPredmetForTeacher->addItem("Не выбрано"); _ui->cbxDeletingPredmet->addItem("Не выбрано"); _ui->cbxPredmets->addItem("Не выбрано"); QVector<QString> predmets = _predmetsService->getAllPredmets(); for (QString predmet : predmets) { _ui->cbxAddingPredmetForTeacher->addItem(predmet); _ui->cbxDeletingPredmet->addItem(predmet); _ui->cbxPredmets->addItem(predmet); } } void MainFormPageTeachers::removeTeacherPredmet() { QString selectedTeacher = _ui->cbxTeachers->currentText(); QString selectedPredmet = _ui->cbxPredmets->currentText(); if (selectedTeacher == "Не выбрано") { QMessageBox::critical(0, "Ошибка ", "Не выбран учитель для удаления у него предмета."); return; } if (selectedPredmet == "Не выбрано") { QMessageBox::critical(0, "Ошибка ", "Не выбран предмет для удаления у учителя."); return; } if(_teachersService->removePredmetTeacherByName(selectedTeacher, selectedPredmet)){ QMessageBox::information(0,"Успешная операция", "Предмет у учителя успешно удален."); reloadTeachersInTable(); } else { QMessageBox::warning(0, "Ошибка ", "Не получилось удалить предмет у учителя."); } } void MainFormPageTeachers::addPredmetForTeacher() { QString selectedTeacher = _ui->cbxTeachersForAddingPredmer->currentText(); QString predmetForTeacher = _ui->cbxAddingPredmetForTeacher->currentText(); if (selectedTeacher == "Не выбрано") { QMessageBox::critical(0, "Ошибка ", "Не выбран учитель для добавления предмета."); return; } if (predmetForTeacher == "Не выбрано") { QMessageBox::critical(0, "Ошибка ", "Не выбран предмет для учителя."); return; } if(_teachersService->addPredmetForTeacher(selectedTeacher, predmetForTeacher)){ QMessageBox::information(0,"Успешная операция", "Предмет для учителя успешно добавлен."); reloadTeachersInTable(); } else { QMessageBox::warning(0, "Ошибка ", "Не получилось добавить предмет для учителя."); } } void MainFormPageTeachers::addPredmet() { QString predmet = _ui->editAddingPredmet->text(); if(predmet.isEmpty()){ QMessageBox::critical(0, "Ошибка ", "Не введено название предмета"); return; } if(_predmetsService->addPredmet(predmet)) { QMessageBox::information(0,"Успешная операция", "Предмет успешно добавлен."); reloadPredmetsInCheckBox(); _ui->editAddingPredmet->clear(); } else { QMessageBox::warning(0, "Ошибка", "Не получилось добавить предмет."); } } void MainFormPageTeachers::removePredmet() { QString predmet = _ui->cbxDeletingPredmet->currentText(); if(predmet == "Не выбрано"){ QMessageBox::critical(0, "Ошибка ", "Не выбран предмет для удаления"); return; } if(_predmetsService->removePredmetByName(predmet)) { QMessageBox::information(0,"Успешная операция", "Предмет успешно удален."); reloadPredmetsInCheckBox(); } else { QMessageBox::warning(0, "Ошибка", "Не получилось удалить предмет."); } } <file_sep>/Data/Entity/Teacher.cpp #include "Teacher.h" QString Teacher::getName() const { return _name; } QString Teacher::getNameClass() const { return _nameClass; } QVector<QString> Teacher::getPredmets() const { return _predmets; } void Teacher::addPredmet(const QString &namePredmet) { _predmets.append(namePredmet); } QString Teacher::toString() const { return "name = " + _name + " nameClass = " + _nameClass; } std::ostream& operator <<(std::ostream &os, Teacher *t) { os << "name = " << t->getName().toStdString() << ", nameClass = " << t->getNameClass().toStdString(); return os; } <file_sep>/Data/Service/EmployeesService.cpp #include "EmployeesService.h" QVector<QSharedPointer<Employe>> EmployeesService::getAllEmployees() { return _emploeesDAO->findAllEmployees(); } QVector<QSharedPointer<Employe>> EmployeesService::searchEmployeesByName(const QString& name) { return _emploeesDAO->findEmployeesByName(name); } QVector<QSharedPointer<Employe>> EmployeesService::selectEmployeesByProfession(const QString &profession) { return _emploeesDAO->findEmployeesByProfession(profession); } bool EmployeesService::addEmploye(const QSharedPointer<Employe>& employe) { try { _emploeesDAO->addEmployee(employe); _log.debug(__FILE__, "Employe [" + employe->toString() + "] was added."); return true; } catch(NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } bool EmployeesService::removeEmployeByName(const QString& name) { try { _emploeesDAO->removeEmployeByName(name); _log.debug(__FILE__, "Employe [" + name + "] was deleted."); return true; } catch(NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } <file_sep>/Data/Service/AdministratorsService.h #ifndef ADMINISTRATORSSERVICE_H #define ADMINISTRATORSSERVICE_H #include <QScopedPointer> #include "Utils/Logger.h" #include "IAdministratorsService.h" #include "Data/DAO/AdministratorsDAO.h" class AdministratorsService : public IAdministratorsService { Logger _log; QScopedPointer<IAdministratorsDAO> _administratorsDAO; public: AdministratorsService() : _administratorsDAO(new AdministratorsDAO) {} bool addAdministrator(const QString& login, const QString& password) override; bool removeAdministratorByLogin(const QString& login) override; bool changePasswordAdministratoByLogin(const QString& login, const QString& oldPassword, const QString& newPassword) override; bool isExistAdministrator(const QString& login, const QString& password) override; QMap<QString, QString> getAllAdministrators() override; }; #endif <file_sep>/Data/Entity/Parent.cpp #include "Parent.h" Parent::Builder &Parent::Builder::setName(const QString &name) { _name = name; return *this; } Parent::Builder &Parent::Builder::setDateBirth(const QString &dateBirth) { _dateBirth = dateBirth; return *this; } Parent::Builder &Parent::Builder::setAddress(const QString &address) { _address = address; return *this; } Parent::Builder &Parent::Builder::setChild(const QString &child) { _child = child; return *this; } QSharedPointer<Parent> Parent::Builder::build() { QSharedPointer<Parent> parent(new Parent(_name, _dateBirth, _address, _child)); return parent; } QString Parent::getName() const { return _name; } QString Parent::getDateBirth() const { return _dateBirth; } QString Parent::getAddress() const { return _address; } QString Parent::getChild() const{ return _child; } QString Parent::toString() const { return "name = " + _name + ", dateBirth = " + _dateBirth + ", address = " + _address; } std::ostream& operator << (std::ostream &os, Parent *p) { os << "name = " << p->getName().toStdString() << ", dateBirth = " << p->getDateBirth().toStdString() << ", address = " << p->getAddress().toStdString(); return os; } <file_sep>/Data/DAO/EmployeesDAO.cpp #include "EmployeesDAO.h" #include <iostream> EmployeesDAO::EmployeesDAO() { _basicSelectQuery = "SELECT e.name, e.date_birth, e.address, e.phone_number, e.personal_data, p.name " "FROM employees e " "LEFT JOIN professions p ON e.id_profession = p.id "; } QVector<QSharedPointer<Employe>> EmployeesDAO::findAllEmployees() { _employees.clear(); QSqlQuery query; query.prepare(_basicSelectQuery); query.exec(); loadEmployeesInVectorFromDB(query); return _employees; } QVector<QSharedPointer<Employe>> EmployeesDAO::findEmployeesByProfession(const QString& profession) { _employees.clear(); QSqlQuery query; query.prepare(_basicSelectQuery + "WHERE p.name = :profession"); query.bindValue(":profession", profession); query.exec(); loadEmployeesInVectorFromDB(query); return _employees; } QVector<QSharedPointer<Employe>> EmployeesDAO::findEmployeesByName(const QString& name) { _employees.clear(); QSqlQuery query; query.prepare(_basicSelectQuery + "WHERE e.name LIKE :name"); query.bindValue(":name", '%' + name + '%'); query.exec(); loadEmployeesInVectorFromDB(query); return _employees; } void EmployeesDAO::loadEmployeesInVectorFromDB(QSqlQuery &query) { while (query.next()) { QSharedPointer<Employe> employe = Employe::Builder() .setName(QString(query.value(0).toString())) .setDateBirth(QString(query.value(1).toString())) .setAddress(QString(query.value(2).toString())) .setPhoneNumber(QString(query.value(3).toString())) .setPersonalData(QString(query.value(4).toString())) .setProfession(QString(query.value(5).toString())) .build(); _employees.append(employe); } } void EmployeesDAO::removeEmployeByName(const QString& name) { QSqlQuery query; query.prepare("DELETE FROM employees WHERE name = :name"); query.bindValue(":name", name); if (!query.exec()) { QString exceptionMessage = "Error in deleting an employe[" + name + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } void EmployeesDAO::addEmployee(const QSharedPointer<Employe>& employe) { QSqlQuery query; query.prepare("INSERT INTO employees(name, date_birth, address, phone_number, personal_data, id_profession) " "VALUES(:name_employe, :date_birth, :address, :phone_number, :personal_data, " "(SELECT p.id FROM professions p WHERE p.name = :name_profession))"); query.bindValue(":name_employe", employe->getName()); query.bindValue(":date_birth", employe->getDateBirth()); query.bindValue(":address", employe->getAddress()); query.bindValue(":phone_number", employe->getPhoneNumber()); query.bindValue(":personal_data", employe->getPersonalData()); query.bindValue(":name_profession", employe->getProfession()); if (!query.exec()) { QString exceptionMessage = "Error in adding an employe[" + employe->getName() + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } <file_sep>/Data/Entity/Parent.h #ifndef PARENT_H #define PARENT_H #include <QString> #include <QSharedPointer> class Parent { QString _name; QString _dateBirth; QString _address; QString _child; Parent(QString name, QString dateBirth, QString address, QString child) : _name(name), _dateBirth(dateBirth), _address(address), _child(child) {} public: class Builder { QString _name; QString _dateBirth; QString _address; QString _child; public: Builder& setName(const QString& name); Builder& setDateBirth(const QString& dateBirth); Builder& setAddress(const QString& address); Builder& setChild(const QString& child); QSharedPointer<Parent> build(); }; QString getName() const; QString getDateBirth() const; QString getAddress() const; QString getChild() const; QString toString() const; friend std::ostream& operator << (std::ostream& os, Parent *parent); }; #endif <file_sep>/Data/Service/IProfessionsService.h #ifndef IPROFESSIONSSERVICE_H #define IPROFESSIONSSERVICE_H #include <QString> #include <QVector> struct IProfessionsService { virtual QVector<QString> getAllProfessions() = 0; virtual bool addProfession(QString &name) = 0; virtual bool removeProfessionByName(QString &name) = 0; virtual bool changeNameProfession(QString &oldName, QString &newName) = 0; virtual ~IProfessionsService() {} }; #endif <file_sep>/Views/Forms/MainForm.cpp #include "MainForm.h" #include "ui_MainForm.h" MainForm::MainForm(QWidget* parent) : QMainWindow(parent), _ui(new Ui::MainForm) { _ui->setupUi(this); _mainFormPageEmployees = std::make_unique<MainFormPageEmployees>(_ui); _mainFormPageTeachers = std::make_unique<MainFormPageTeachers>(_ui); _mainFormPagePupils = std::make_unique<MainFormPagePupils>(_ui); _mainFormPageSettings = std::make_unique<MainFormPageSettings>(_ui); connect(_ui->btnReloadEmployees, SIGNAL(clicked(bool)), this, SLOT(clickedBtnReloadEmployees())); connect(_ui->btnAddEmploye, SIGNAL(clicked(bool)), this, SLOT(clickedBtnAddEmploye())); connect(_ui->btnRemoveEmploye, SIGNAL(clicked(bool)), this, SLOT(clickedBtnRemoveEmploye())); connect(_ui->btnSelectEmployees, SIGNAL(clicked(bool)), this, SLOT(clickedBtnSelectEmployees())); connect(_ui->btnSearchEmployees, SIGNAL(clicked(bool)), this, SLOT(clickedBtnSearchEmployees())); connect(_ui->btnAddProfession, SIGNAL(clicked(bool)), this, SLOT(clickedBtnAddProfession())); connect(_ui->btnRemoveProfession, SIGNAL(clicked(bool)), this, SLOT(clickedBtnRemoveProfession())); connect(_ui->btnAddPredmetForTeacher, SIGNAL(clicked(bool)), this, SLOT(clickedBtnAddPredmetForTeacher())); connect(_ui->btnRemoveTeacherPredmet, SIGNAL(clicked(bool)), this, SLOT(clickedBtnRemoveTeacherPredmet())); connect(_ui->btnAddPredmet, SIGNAL(clicked(bool)), this, SLOT(clickedBtnAddPredmet())); connect(_ui->btnDeletePredmet, SIGNAL(clicked(bool)), this, SLOT(clickedBtnRemovePredmet())); connect(_ui->btnAddPupil, SIGNAL(clicked(bool)), this, SLOT(clickedBtnAddPupil())); connect(_ui->btnRemovePupil, SIGNAL(clicked(bool)), this, SLOT(clickedBtnRemovePupil())); connect(_ui->btnSelectPupils, SIGNAL(clicked(bool)), this, SLOT(clickedBtnSelectPupils())); connect(_ui->btnSearchPupils, SIGNAL(clicked(bool)), this, SLOT(clickedBtnSearchPupils())); connect(_ui->btnReloadPupilsAndTeachers, SIGNAL(clicked(bool)), this, SLOT(clickedBtnReloadPupils())); connect(_ui->btnAddParent, SIGNAL(clicked(bool)), this, SLOT(clickedBtnAddParent())); connect(_ui->btnRemoveParent, SIGNAL(clicked(bool)), this, SLOT(clickedBtnRemoveParent())); connect(_ui->tablePupils, SIGNAL(pressed(QModelIndex)), this, SLOT(selectedPupil(QModelIndex))); connect(_ui->btnAddClass, SIGNAL(clicked(bool)), this, SLOT(clickedBtnAddClass())); connect(_ui->btnRemoveClass, SIGNAL(clicked(bool)), this, SLOT(clickedBtnRemoveClass())); connect(_ui->btnAddAdmin, SIGNAL(clicked(bool)), this, SLOT(clickedBtnAddAdmin())); connect(_ui->btnChangeAdminPassword, SIGNAL(clicked(bool)), this, SLOT(clickedBtnChangeAdminPassword())); connect(_ui->btnRemoveAdmin, SIGNAL(clicked(bool)), this, SLOT(clickedBtnRemoveAdmin())); } //Page employees void MainForm::clickedBtnReloadEmployees(){ _mainFormPageEmployees->reloadEmployees(); } void MainForm::clickedBtnAddEmploye() { _mainFormPageEmployees->addEmploye(); _mainFormPageTeachers->reloadTeachersInTable(); } void MainForm::clickedBtnRemoveEmploye() { _mainFormPageEmployees->removeEmploye(); } void MainForm::clickedBtnSelectEmployees() { _mainFormPageEmployees->selectEmployees(); } void MainForm::clickedBtnSearchEmployees() { _mainFormPageEmployees->searchEmployees(); } void MainForm::clickedBtnAddProfession() { _mainFormPageEmployees->addProfession(); } void MainForm::clickedBtnRemoveProfession() { _mainFormPageEmployees->removeProfession(); } // Page teachers void MainForm::clickedBtnAddPredmetForTeacher() { _mainFormPageTeachers->addPredmetForTeacher(); } void MainForm::clickedBtnRemoveTeacherPredmet() { _mainFormPageTeachers->removeTeacherPredmet(); } void MainForm::clickedBtnAddPredmet() { _mainFormPageTeachers->addPredmet(); } void MainForm::clickedBtnRemovePredmet() { _mainFormPageTeachers->removePredmet(); } // Page pupils and employees void MainForm::clickedBtnAddPupil() { _mainFormPagePupils->addPupil(); } void MainForm::clickedBtnRemovePupil() { _mainFormPagePupils->removePupil(); } void MainForm::clickedBtnSelectPupils() { _mainFormPagePupils->selectPupils(); } void MainForm::clickedBtnSearchPupils() { _mainFormPagePupils->searchPupils(); } void MainForm::clickedBtnReloadPupils() { _mainFormPagePupils->reloadPupilsAndParents(); } void MainForm::clickedBtnAddParent() { _mainFormPagePupils->addParent(); } void MainForm::clickedBtnRemoveParent() { _mainFormPagePupils->removeParent(); } void MainForm::selectedPupil(QModelIndex index) { _mainFormPagePupils->showParentsSelectedPupil(index); } void MainForm::clickedBtnAddClass() { _mainFormPagePupils->addClass(); } void MainForm::clickedBtnRemoveClass() { _mainFormPagePupils->removeClass(); } //Page settings void MainForm::clickedBtnAddAdmin() { _mainFormPageSettings->addAdministrator(); } void MainForm::clickedBtnChangeAdminPassword() { _mainFormPageSettings->changePasswordAdministrator(); } void MainForm::clickedBtnRemoveAdmin() { _mainFormPageSettings->removeAdministrator(); } MainForm::~MainForm() { delete _ui; } <file_sep>/Data/DAO/ProfessionsDAO.h #ifndef PROFESSIONSDAO_H #define PROFESSIONSDAO_H #include <QtSql> #include <QSqlQuery> #include "IProfessionsDAO.h" #include "Exceptions/NotWorkingRequest.h" struct ProfessionsDAO : public IProfessionsDAO { QVector<QString> findAllProfessions() override; void addProfession(QString &name) override; void removeProfessionByName(QString &name) override; void changeNameProfession(QString &oldName, QString &newName) override; }; #endif <file_sep>/Data/Service/AdministratorsService.cpp #include "AdministratorsService.h" bool AdministratorsService::addAdministrator(const QString& login, const QString& password) { try { _administratorsDAO->addAdministrator(login, password); _log.debug(__FILE__, "Administrator [" + login + "] was added."); return true; } catch(NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } bool AdministratorsService::removeAdministratorByLogin(const QString& login) { try { _administratorsDAO->removeAdministratorByLogin(login); _log.debug(__FILE__, "Administrator [" + login + "] was deleted."); return true; } catch(NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } bool AdministratorsService::changePasswordAdministratoByLogin(const QString &login, const QString &oldPassword, const QString &newPassword) { QString hashPassword = _administratorsDAO->hashPassword(oldPassword); if(!isExistAdministrator(login, hashPassword)) { return false; } try { _administratorsDAO->changePasswordAdministratorByLogin(login, oldPassword, newPassword); _log.debug(__FILE__, "Password of administrator [" + login + "] was changed."); return true; } catch(NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } bool AdministratorsService::isExistAdministrator(const QString& login, const QString& password) { QString hashPassword = _administratorsDAO->hashPassword(password); QPair<QString, QString> admin; try { admin = _administratorsDAO->findAdministratorByLogin(login); } catch(AdministratorNotFound& e) { _log.warning(__FILE__, e.what()); return false; } if(admin.first == login && admin.second == hashPassword) { return true; } else { return false; } } QMap<QString, QString> AdministratorsService::getAllAdministrators() { return _administratorsDAO->findAllAdministrators(); } <file_sep>/Data/DAO/IParentsDAO.h #ifndef IPARENTSDAO_H #define IPARENTSDAO_H #include <QVector> #include <QSharedPointer> #include "Data/Entity/Parent.h" struct IParentsDAO { virtual QVector<QSharedPointer<Parent>> findParentsByChild(const QString& name) = 0; virtual void addParent(QSharedPointer<Parent>& parent) = 0; virtual void removeParentByName(const QString& name) = 0; virtual ~IParentsDAO() {} }; #endif <file_sep>/Data/Service/PupilsService.cpp #include "PupilsService.h" QVector<QSharedPointer<Pupil>> PupilsService::getPupilsByClass(const QString& nameClass) { return _pupilsDAO->findPupilsByClass(nameClass); } QVector<QSharedPointer<Pupil> > PupilsService::getPupilsByName(const QString &name) { return _pupilsDAO->findPupilsByName(name); } QVector<QSharedPointer<Pupil>> PupilsService::getAllPupils() { return _pupilsDAO->findAllPupils(); } bool PupilsService::addPupil(const QSharedPointer<Pupil>& pupil) { try { _pupilsDAO->addPupil(pupil); _log.debug(__FILE__, "Pupil [" + pupil->toString() + "] was added."); return true; } catch(NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } bool PupilsService::removePupilByName(const QString& name) { try { _pupilsDAO->removePupilByName(name); _log.debug(__FILE__, "Pupil [" + name + "] was deleted."); return true; } catch(NotWorkingRequest& e) { _log.warning(__FILE__, e.what()); return false; } } <file_sep>/Data/Entity/Employe.h #ifndef EMPLOYE_H #define EMPLOYE_H #include <QString> #include <QSharedPointer> class Employe{ QString _name; QString _dateBirth; QString _address; QString _profession; QString _phoneNumber; QString _personalData; public: Employe(const QString& name, const QString& dateBirth, const QString& address, const QString& profession, const QString& phoneNumber, const QString& personalData) : _name(name), _dateBirth(dateBirth), _address(address), _profession(profession), _phoneNumber(phoneNumber), _personalData(personalData) {} class Builder{ QString _name; QString _dateBirth; QString _address; QString _profession; QString _phoneNumber; QString _personalData; public: Builder& setName(const QString& name); Builder& setDateBirth(const QString& dateBirth); Builder& setAddress(const QString& address); Builder& setProfession(const QString& profession); Builder& setPhoneNumber(const QString& phoneNumber); Builder& setPersonalData(const QString& personalData); QSharedPointer<Employe> build(); }; QString getName() const; QString getDateBirth() const; QString getAddress() const; QString getProfession() const; QString getPhoneNumber() const; QString getPersonalData() const; QString toString() const; friend std::ostream& operator << (std::ostream& os, Employe *employe); }; #endif <file_sep>/Data/Service/IPupilsService.h #ifndef IPUPILSSERVICE_H #define IPUPILSSERVICE_H #include <QVector> #include <QSharedPointer> #include "Data/Entity/Pupil.h" struct IPupilsService{ virtual QVector<QSharedPointer<Pupil>> getPupilsByClass(const QString& nameClass) = 0; virtual QVector<QSharedPointer<Pupil>> getPupilsByName(const QString& name) = 0; virtual QVector<QSharedPointer<Pupil>> getAllPupils() = 0; virtual bool addPupil(const QSharedPointer<Pupil>& pupil) = 0; virtual bool removePupilByName(const QString& name) = 0; virtual ~IPupilsService() {} }; #endif <file_sep>/Data/Service/IAdministratorsService.h #ifndef IADMINISTRATORSSERVICE_H #define IADMINISTRATORSSERVICE_H #include <QString> #include <QMap> struct IAdministratorsService { virtual bool addAdministrator(const QString& login, const QString& password) = 0; virtual bool removeAdministratorByLogin(const QString& login) = 0; virtual bool changePasswordAdministratoByLogin(const QString& login, const QString& oldPassword, const QString& newPassword) = 0; virtual bool isExistAdministrator(const QString& login, const QString& password) = 0; virtual QMap<QString, QString> getAllAdministrators() = 0; virtual ~IAdministratorsService() {} }; #endif <file_sep>/Data/Service/ITeachersService.h #ifndef ITEACHERSSERVICE_H #define ITEACHERSSERVICE_H #include <QVector> #include <QSharedPointer> #include "Data/Entity/Teacher.h" struct ITeachersService { virtual QVector<QSharedPointer<Teacher>> getAllTeachers() = 0; virtual bool addPredmetForTeacher(const QString& nameTeacher, const QString& namePredmet) = 0; virtual bool removePredmetTeacherByName(const QString& nameTeacher, const QString& namePredmet) = 0; virtual ~ITeachersService() {} }; #endif <file_sep>/Exceptions/AdministratorNotFound.h #ifndef ADMINISTRATORNOTFOUND_H #define ADMINISTRATORNOTFOUND_H #include <QString> class AdministratorNotFound { QString _message; public: AdministratorNotFound(const QString& message) : _message(message) {} QString what() const { return "Administraot not found. Exception: " + _message; } }; #endif <file_sep>/Data/Entity/Teacher.h #ifndef TEACHER_H #define TEACHER_H #include <QString> #include <QVector> #include <QSharedPointer> class Teacher { QString _name; QString _nameClass; QVector<QString> _predmets; public: Teacher(const QString& name, const QString& nameClass) : _name(name), _nameClass(nameClass) {} QString getName() const; QString getNameClass() const; QVector<QString> getPredmets() const; void addPredmet(const QString& namePredmet); QString toString() const; friend std::ostream& operator << (std::ostream& os, Teacher *teacher); }; #endif <file_sep>/Data/DAO/PredmetsDAO.h #ifndef PREDMETSDAO_H #define PREDMETSDAO_H #include <QtSql> #include <QSqlQuery> #include "IPredmetsDAO.h" #include "Exceptions/NotWorkingRequest.h" struct PredmetsDAO : public IPredmetsDAO { QVector<QString> findAllPredmets() override; void addPredmet(const QString &name) override; void removePredmetByName(const QString& name) override; void changeNamePredmet(const QString& oldName, const QString& newName) override; }; #endif <file_sep>/Data/DAO/ITeachersDAO.h #ifndef ITEACHERSDAO_H #define ITEACHERSDAO_H #include <QVector> #include <QSharedPointer> #include "Data/Entity/Teacher.h" struct ITeachersDAO { virtual QVector<QSharedPointer<Teacher>> findAllTeachers() = 0; virtual void addPredmetForTeacher(const QString& nameTeacher, const QString& namePredmet) = 0; virtual void removePredmetTeacherByName(const QString& nameTeacher, const QString& namePredmet) = 0; virtual ~ITeachersDAO() {} }; #endif <file_sep>/Data/Service/IParentsService.h #ifndef IPARENTSSERVICE_H #define IPARENTSSERVICE_H #include <QVector> #include <QSharedPointer> #include "Data/Entity/Parent.h" struct IParentsService { virtual QVector<QSharedPointer<Parent>> getParentsByChild(const QString& name) = 0; virtual bool addParent(QSharedPointer<Parent>& parent) = 0; virtual bool removeParentByName(const QString& name) = 0; virtual ~IParentsService() {} }; #endif <file_sep>/Data/DAO/ParentsDAO.cpp #include "ParentsDAO.h" QVector<QSharedPointer<Parent> > ParentsDAO::findParentsByChild(const QString &name) { _parents.clear(); QSqlQuery query; query.prepare("SELECT par.name, par.date_birth, par.address " "FROM parents par " "LEFT JOIN pupils pup ON pup.id = par.id_pupil " "WHERE pup.name = :name"); query.bindValue(":name", name); query.exec(); while (query.next()) { QSharedPointer<Parent> parent = Parent::Builder() .setName(QString(query.value(0).toString())) .setDateBirth(QString(query.value(1).toString())) .setAddress(QString(query.value(2).toString())) .build(); _parents.append(parent); } return _parents; } void ParentsDAO::addParent(QSharedPointer<Parent> &parent) { QSqlQuery query; query.prepare("INSERT INTO parents(name, date_birth, address, id_pupil) " "VALUES(:name, :date_birth, :address, " "(SELECT p.id FROM pupils p WHERE p.name = :child))"); query.bindValue(":name", parent->getName()); query.bindValue(":date_birth", parent->getDateBirth()); query.bindValue(":address", parent->getAddress()); query.bindValue(":child", parent->getChild()); if (!query.exec()) { QString exceptionMessage = "Error in adding parent[" + parent->getName() + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } void ParentsDAO::removeParentByName(const QString &name) { QSqlQuery query; query.prepare("DELETE FROM parents WHERE name = :name"); query.bindValue(":name", name); if (!query.exec()) { QString exceptionMessage = "Error in deleting parent[" + name + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } <file_sep>/main.cpp #include <QApplication> #include "Views/Forms/LoginForm.h" #include "Utils/DataBase.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); DataBase* database = DataBase::getInstance(); database->connect(); LoginForm loginForm; loginForm.show(); return app.exec(); } <file_sep>/Data/Service/EmployeesService.h #ifndef EMPLOYEESSERVICE_H #define EMPLOYEESSERVICE_H #include <QScopedPointer> #include "Utils/Logger.h" #include "Data/DAO/EmployeesDAO.h" #include "Data/Service/IEmployeesService.h" class EmployeesService : public IEmployeesService { Logger _log; QScopedPointer<IEmployeesDAO> _emploeesDAO; public: EmployeesService() : _emploeesDAO(new EmployeesDAO) {} QVector<QSharedPointer<Employe>> getAllEmployees() override; QVector<QSharedPointer<Employe>> searchEmployeesByName(const QString& name) override; QVector<QSharedPointer<Employe>> selectEmployeesByProfession(const QString& profession) override; bool addEmploye(const QSharedPointer<Employe>& employe) override; bool removeEmployeByName(const QString &name) override; }; #endif <file_sep>/Data/DAO/PupilsDAO.cpp #include "PupilsDAO.h" PupilsDAO::PupilsDAO() { _basicSelectQuery = "SELECT p.name, p.date_birth, p.address, c.name " "FROM pupils p " "LEFT JOIN classes c ON c.id = p.id_class "; } QVector<QSharedPointer<Pupil>> PupilsDAO::findAllPupils() { _pupils.clear(); QSqlQuery query; query.prepare(_basicSelectQuery); query.exec(); loadPupilsInVectorFromDB(query); return _pupils; } QVector<QSharedPointer<Pupil>> PupilsDAO::findPupilsByClass(const QString& nameClass) { _pupils.clear(); QSqlQuery query; query.prepare(_basicSelectQuery + "WHERE c.name = :nameClass"); query.bindValue(":nameClass", nameClass); query.exec(); loadPupilsInVectorFromDB(query); return _pupils; } QVector<QSharedPointer<Pupil> > PupilsDAO::findPupilsByName(const QString& name) { _pupils.clear(); QSqlQuery query; query.prepare(_basicSelectQuery + "WHERE p.name LIKE :name"); query.bindValue(":name", '%' + name + '%'); query.exec(); loadPupilsInVectorFromDB(query); return _pupils; } void PupilsDAO::loadPupilsInVectorFromDB(QSqlQuery& query) { while (query.next()) { QSharedPointer<Pupil> pupil = Pupil::Builder() .setName(QString(query.value(0).toString())) .setDateBirth(QString(query.value(1).toString())) .setAddress(QString(query.value(2).toString())) .setNameClass(QString(query.value(3).toString())) .build(); _pupils.append(pupil); } } void PupilsDAO::addPupil(const QSharedPointer<Pupil>& pupil) { QSqlQuery query; query.prepare("INSERT INTO pupils(name, date_birth, address, id_class) " "VALUES(:name, :date_birth, :address, " "(SELECT c.id FROM classes c WHERE c.name = :nameClass))"); query.bindValue(":name", pupil->getName()); query.bindValue(":date_birth", pupil->getDateBirth()); query.bindValue(":address", pupil->getAddress()); query.bindValue(":nameClass", pupil->getNameClass()); if (!query.exec()) { QString exceptionMessage = "Error in adding an pupil[" + pupil->getName() + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } void PupilsDAO::removePupilByName(const QString &name) { QSqlQuery query; query.prepare("DELETE FROM pupils " "WHERE name = :name"); query.bindValue(":name", name); if (!query.exec()) { QString exceptionMessage = "Error in deleting an pupil[" + name + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } <file_sep>/Data/DAO/AdministratorsDAO.cpp #include "AdministratorsDAO.h" AdministratorsDAO::AdministratorsDAO() { _basicSelectQuery = "SELECT login, password FROM administrators "; } QPair<QString, QString> AdministratorsDAO::findAdministratorByLogin(const QString &login) { QSqlQuery query; query.prepare(_basicSelectQuery + "WHERE login = :login"); query.bindValue(":login", login); query.exec(); if (query.next()) { QPair<QString, QString> admin; admin.first = QString(query.value(0).toString()); //login admin.second = QString(query.value(1).toString()); //password return admin; } else { QString exceptionMessage = "Administrator [" + login + "] isn't exist."; throw AdministratorNotFound(exceptionMessage); } } QMap<QString, QString> AdministratorsDAO::findAllAdministrators() { _administrators.clear(); QSqlQuery query; query.prepare(_basicSelectQuery); query.exec(); while (query.next()) { QString login = QString(query.value(0).toString()); QString password = QString(query.value(1).toString()); _administrators.insert(login, password); } return _administrators; } void AdministratorsDAO::addAdministrator(const QString &login, const QString &password) { QSqlQuery query; query.prepare("INSERT INTO administrators(login, password) VALUES(:login, :password)"); query.bindValue(":login", login); query.bindValue(":password", hashPassword(password)); if (!query.exec()) { QString exceptionMessage = "Error in adding an administrator[" + login + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } void AdministratorsDAO::removeAdministratorByLogin(const QString &login) { QSqlQuery query; query.prepare("DELETE FROM administrators WHERE login = :login"); query.bindValue(":login", login); if (!query.exec()) { QString exceptionMessage = "Error in deleting an administrator[" + login + "]. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } void AdministratorsDAO::changePasswordAdministratorByLogin(const QString &login, const QString &oldPassword, const QString &newPassword) { QSqlQuery query; query.prepare("UPDATE administrators " "SET password = :newPassword " "WHERE password = :old<PASSWORD> AND login = :login"); query.bindValue(":login", login); query.bindValue(":oldPassword", hashPassword(oldPassword)); query.bindValue(":newPassword", hashPassword(newPassword)); if (!query.exec()) { QString exceptionMessage = "Error in changing administrator[" + login + "] password. Query: " + query.lastQuery(); throw NotWorkingRequest(QString(exceptionMessage)); } } QString AdministratorsDAO::hashPassword(const QString &password) { QByteArray arrayForHash = password.toUtf8(); QString hashPassword = QString(QCryptographicHash::hash(arrayForHash, QCryptographicHash::Sha256).toHex()); return hashPassword; } <file_sep>/Views/Forms/PagesMainForm/MainFormPagePupils.cpp #include "MainFormPagePupils.h" #include "ui_MainForm.h" MainFormPagePupils::MainFormPagePupils(Ui::MainForm* mainForm) : _ui(mainForm), _pupilsService(new PupilsService), _modelPupils(new QStandardItemModel), _modelParents(new QStandardItemModel), _classesService(new ClassesService), _parentsService(new ParentsService) { QStringList headerPupils = { "ФИО", "Дата рождения", "Адрес", "Класс" }; QStringList headerParents = { "ФИО", "Дата рождения", "Адрес" }; _modelPupils->setHorizontalHeaderLabels(headerPupils); _modelParents->setHorizontalHeaderLabels(headerParents); _ui->tablePupils->setModel(_modelPupils.data()); _ui->tablePupils->resizeColumnsToContents(); _ui->tablePupils->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); _ui->tableParents->setModel(_modelParents.data()); _ui->tableParents->resizeColumnsToContents(); _ui->tableParents->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); reloadClassesInCheckBox(); reloadPupilsInTable(_pupilsService->getAllPupils()); } void MainFormPagePupils::reloadPupilsInTable(QVector<QSharedPointer<Pupil>> pupils) { _modelPupils->removeRows(0, _modelPupils->rowCount()); for (long i = 0; i < pupils.size(); i++) { _modelPupils->setItem(i, 0, new QStandardItem(pupils.at(i)->getName())); _modelPupils->setItem(i, 1, new QStandardItem(pupils.at(i)->getDateBirth())); _modelPupils->setItem(i, 2, new QStandardItem(pupils.at(i)->getAddress())); _modelPupils->setItem(i, 3, new QStandardItem(pupils.at(i)->getNameClass())); } } void MainFormPagePupils::reloadParentsInTable(QVector<QSharedPointer<Parent>> parents) { _modelParents->removeRows(0, _modelParents->rowCount()); for (long i = 0; i < parents.size(); i++) { _modelParents->setItem(i, 0, new QStandardItem(parents.at(i)->getName())); _modelParents->setItem(i, 1, new QStandardItem(parents.at(i)->getDateBirth())); _modelParents->setItem(i, 2, new QStandardItem(parents.at(i)->getAddress())); } } void MainFormPagePupils::reloadClassesInCheckBox() { QVector<QString> classes = _classesService->getAllClasses(); _ui->cbxPupilsClasses->clear(); _ui->cbxDeletingClass->clear(); _ui->cbxPupilsClasses->addItem("Не выбрано"); _ui->cbxDeletingClass->addItem("Не выбрано"); for (auto curClass : classes) { _ui->cbxPupilsClasses->addItem(curClass); _ui->cbxDeletingClass->addItem(curClass); } } void MainFormPagePupils::reloadPupilsAndParents() { reloadPupilsInTable(_pupilsService->getAllPupils()); QMessageBox::information(0, "Успешная операция", "Ученики и их родители успешно обновлены."); } void MainFormPagePupils::addPupil() { AddingPupilDialog addingPupilDialog; if (addingPupilDialog.exec() == QDialog::Accepted) { QSharedPointer<Pupil> pupil = addingPupilDialog.getData(); if (_pupilsService->addPupil(pupil)) { QMessageBox::information(0, "Успешная операция", "Ученик [" + pupil->getName() + "] был успешно добавлен."); reloadPupilsInTable(_pupilsService->getAllPupils()); } else { QMessageBox::warning(0, "Неуспешная операция", "Видимо уже существует такой ученик с таким именем, добавление нового невозможно."); } } } void MainFormPagePupils::removePupil() { QModelIndexList selectedRows = getSelectedRows(_ui->tablePupils); if (selectedRows.isEmpty()) { QMessageBox::warning(0, "Ошибка удаления", "Не выбран(ы) ученик(и) в таблице."); return; } QMessageBox::StandardButton confirm = QMessageBox::question(0, "Подтверждение", "Действительно хотите удалить ученика(ов)?", QMessageBox::Yes|QMessageBox::No); if(confirm == QMessageBox::Yes) { for (auto row : selectedRows) { QString name = row.data().toString(); if(_pupilsService->removePupilByName(name)) { QMessageBox::information(0, "Успешная операция", "Ученик [" + name + "] успешно удален."); } else { QMessageBox::warning(0, "Неудачная операция", "Такого ученика не существует."); } } reloadPupilsInTable(_pupilsService->getAllPupils()); } } void MainFormPagePupils::selectPupils() { QString classPupils = _ui->cbxPupilsClasses->currentText(); if (classPupils == "Не выбрано") { QMessageBox::critical(0, "Ошибка выборки", "Не выбран класс, выборка ученков невозможна."); return; } reloadPupilsInTable(_pupilsService->getPupilsByClass(classPupils)); } void MainFormPagePupils::searchPupils() { QString name = _ui->editSearchingPupils->text(); if (name.isEmpty()) { QMessageBox::critical(0, "Ошибка поиска", "Не введено данных для поиска."); return; } reloadPupilsInTable(_pupilsService->getPupilsByName(name)); } void MainFormPagePupils::addParent() { AddingParentDialog addingParentDialog; if (addingParentDialog.exec() == QDialog::Accepted) { QSharedPointer<Parent> parent = addingParentDialog.getData(); if (_parentsService->addParent(parent)) { QMessageBox::information(0, "Успешная операция", "Родитель [" + parent->getName() + "] был успешно добавлен."); reloadParentsInTable(_parentsService->getParentsByChild("")); } else { QMessageBox::warning(0, "Неуспешная операция", "Видимо уже существует такой родитель с таким именем, добавление нового невозможно."); } } } void MainFormPagePupils::removeParent() { QModelIndexList selectedRows = getSelectedRows(_ui->tableParents); if (selectedRows.isEmpty()) { QMessageBox::warning(0, "Ошибка удаления", "Не выбран(ы) родитель(и) в таблице."); return; } QMessageBox::StandardButton confirm = QMessageBox::question(0, "Подтверждение", "Действительно хотите удалить родителя(ей)?", QMessageBox::Yes|QMessageBox::No); if(confirm == QMessageBox::Yes) { for (auto row : selectedRows) { QString name = row.data().toString(); if(_parentsService->removeParentByName(name)) { QMessageBox::information(0, "Успешная операция", "Родитель [" + name + "] успешно удален."); } else { QMessageBox::warning(0, "Неудачная операция", "Такого родителя не существует."); } } reloadParentsInTable(_parentsService->getParentsByChild("")); } } void MainFormPagePupils::showParentsSelectedPupil(QModelIndex index) { QModelIndex selectedPupil = index.sibling(index.row(), 0); QString namePupil = selectedPupil.data().toString(); reloadParentsInTable(_parentsService->getParentsByChild(namePupil)); } void MainFormPagePupils::addClass() { QString newClass = _ui->editAddingNewClass->text(); if (newClass.isEmpty()) { QMessageBox::critical(0, "Ошибка добавления", "Не введено название класса, добавление невозможно."); return; } if(_classesService->addClass(newClass)){ QMessageBox::information(0, "Успешная операция", "Класс [" + newClass + "] успешно добавлен."); reloadClassesInCheckBox(); _ui->editAddingNewClass->setText(""); } else { QMessageBox::warning(0, "Неудачная операция", "Класс [" + newClass + "] не была добавлен. Возможно такой класс уже существует."); } } void MainFormPagePupils::removeClass() { QString oldClass = _ui->cbxDeletingClass->currentText(); if (oldClass == "Не выбрано") { QMessageBox::critical(0, "Ошибка удаления", "Не выбрано название профессии, удаление невозможно."); return; } if(_classesService->removeClassByName(oldClass)){ QMessageBox::information(0, "Успешная операция", "Класс [" + oldClass + "] успешно удален."); reloadClassesInCheckBox(); reloadPupilsInTable(_pupilsService->getAllPupils()); } else { QMessageBox::warning(0, "Неудачная операция", "Класс [" + oldClass + "] не была удален."); } } <file_sep>/Data/Service/TeachersService.h #ifndef TEACHERSSERVICE_H #define TEACHERSSERVICE_H #include <QScopedPointer> #include "Utils/Logger.h" #include "Data/DAO/TeachersDAO.h" #include "Exceptions/NotWorkingRequest.h" #include "ITeachersService.h" class TeachersService : public ITeachersService { Logger _log; QScopedPointer<TeachersDAO> _teachersDAO; public: TeachersService() : _teachersDAO(new TeachersDAO) {} QVector<QSharedPointer<Teacher>> getAllTeachers() override; bool addPredmetForTeacher(const QString& nameTeacher, const QString& namePredmet) override; bool removePredmetTeacherByName(const QString& nameTeacher, const QString& namePredmet) override; }; #endif <file_sep>/Data/DAO/IPredmetsDAO.h #ifndef IPREDMETSDAO_H #define IPREDMETSDAO_H #include <QString> #include <QVector> struct IPredmetsDAO { virtual QVector<QString> findAllPredmets() = 0; virtual void addPredmet(const QString& name) = 0; virtual void removePredmetByName(const QString& name) = 0; virtual void changeNamePredmet(const QString& oldName, const QString& newName) = 0; virtual ~IPredmetsDAO() {} }; #endif
84109660f2bfe3df30cd78fa9aea06e3721ce30b
[ "C", "C++" ]
84
C++
advaitgupta/SchoolDataBase
9a7b67d55621e1e04fdfff8d66a0fb5d98c89572
b87a9e648a753ab915449c86a9a1db0090eb6785
refs/heads/main
<repo_name>omobosteven/stephenomobo.com<file_sep>/src/components/underConstruction.js import * as React from "react"; import { SvgIcon, makeStyles } from "@material-ui/core"; import { ReactComponent as Construction } from "../images/svgs/construction.svg"; const UnderConstruction = () => { const classes = useStyles(); return ( <section className={classes.section}> <SvgIcon component={Construction} className="blockIcon" /> <p className="text">Under Construction</p> </section> ); }; const useStyles = makeStyles({ section: { marginTop: 80, textAlign: "center", "& .MuiSvgIcon-root.blockIcon": { fontSize: 150, }, "& .text": { color: "#76777E", fontSize: 24, margin: 0, }, }, }); export default UnderConstruction; <file_sep>/src/components/layout.js import * as React from "react"; import { makeStyles } from "@material-ui/core"; import Navigation from "./navigation"; const Layout = ({ activeLink, children }) => { const classes = useStyles(); return ( <main className={classes.layout}> <Navigation activeLink={activeLink} /> {children} </main> ); }; const useStyles = makeStyles((theme) => ({ layout: { minHeight: "100vh", }, })); export default Layout; <file_sep>/src/reusables/Chip.js import * as React from "react"; import clsx from "clsx"; import { Chip as MuiChip, makeStyles } from "@material-ui/core"; const Chip = ({ color, ...rest }) => { const classes = useStyles(); return ( <MuiChip {...rest} classes={{ root: clsx(classes.chipRoot, { [classes.greenChip]: color === "green", [classes.redChip]: color === "red", }), }} /> ); }; const useStyles = makeStyles((theme) => ({ chipRoot: { borderRadius: 2, fontSize: theme.typography.fontSize, fontWeight: 500, fontFamily: theme.typography.fontFamilySecondary, height: "unset", minWidth: 90, color: theme.palette.text.black, "& .MuiChip-label": { padding: "1px 8px", }, }, greenChip: { backgroundColor: theme.palette.success.main, border: `1px solid ${theme.palette.success.main}`, }, redChip: { backgroundColor: theme.palette.error.main, border: `1px solid ${theme.palette.error.main}`, color: theme.palette.error.light, }, })); export default Chip; <file_sep>/gatsby-config.js module.exports = { siteMetadata: { siteUrl: "https://stephenomobo.com", title: "Stephen Omobo", }, flags: { DEV_SSR: false, }, plugins: [ "gatsby-plugin-netlify-cms", "gatsby-plugin-gatsby-cloud", "gatsby-plugin-image", "gatsby-plugin-react-helmet", "gatsby-plugin-mdx", "gatsby-plugin-sharp", "gatsby-transformer-sharp", { resolve: "gatsby-theme-material-ui", options: { webFontsConfig: { fonts: { google: [ { family: "Montserrat", variants: ["300", "400", "500"], }, { family: "Inconsolata", variants: ["300", "400", "500", "600"], }, ], }, }, }, }, { resolve: "gatsby-source-filesystem", options: { name: "images", path: "./src/images/", }, __key: "images", }, { resolve: "gatsby-source-filesystem", options: { name: "pages", path: "./src/pages/", }, __key: "pages", }, { resolve: "gatsby-plugin-svgr", options: { include: /images\/svgs/, }, }, ], }; <file_sep>/src/gatsby-theme-material-ui-top-layout/theme/typography.js const typography = { fontFamily: "Inconsolata, monospace", fontFamilySecondary: "Montserrat, sans-serif", fontSizeXXSmall: 8, fontSizeXSmall: 10, fontSizeSmall: 12, fontSize: 14, fontSizeLarge: 16, fontSizeXLarge: 18, fontSizeXXLarge: 20, fontSizeTitle: 24, fontSizeLargeTitle: 32, }; export default typography; <file_sep>/src/pages/index.js import * as React from "react"; import { makeStyles, Grid, Box, Typography, SvgIcon } from "@material-ui/core"; import clsx from "clsx"; import { differenceInCalendarYears } from "date-fns"; import { ReactComponent as Andela } from "../images/svgs/andelaLogo.svg"; import { ReactComponent as Arvo } from "../images/svgs/arvoLogo.svg"; import { ReactComponent as Prunedge } from "../images/svgs/prunedgeLogo.svg"; import Stacks from "../components/stacks"; import Layout from "../components/layout"; import { Container, Chip } from "../reusables"; const IndexPage = () => { const classes = useStyles(); return ( <Layout activeLink="about"> <section className={classes.home}> <Container> <Grid container className={classes.gridContainer}> <Grid item className={classes.gridItem} xs={12} lg={5}> <Box className="introBox"> <div className={classes.chipGroup}> <Chip label="Software Engineer" color="green" /> <Chip label="Front-end Developer" color="red" /> </div> <div className={classes.introGroup}> <Typography variant="h1" className="title"> / This is me </Typography> <Typography variant="body1" component="div" className="body"> <div className="bodyStart"> &#10090;<span className="name"><NAME></span> &#10091; &#10142; &#10100; </div> <div className="bodyContent"> Experienced software engineer, who is very keen on leveraging technology to solve problems and improve the lives of people around the world. I have worked on progressively challenging projects across different domains including FinTech, Telemedicine, HR / Payroll, and beyond. </div> <div className="bodyEnd">&#10101;</div> </Typography> </div> </Box> <Box className="summaryBox" display="flex" justifyContent="space-between" > <Typography variant="caption" className={classes.numExperience}> <span className="captionYears"> {differenceInCalendarYears( new Date(), new Date(2018, 8, 1) )} </span> <span className="captionText"> <span>Years</span> <span>Experience</span> </span> </Typography> <div className="workLogo"> <SvgIcon component={Andela} viewBox="0 0 24 7" /> <SvgIcon component={Arvo} viewBox="0 0 24 9" /> <SvgIcon component={Prunedge} viewBox="0 0 24 8.2" /> </div> </Box> </Grid> <Grid item className={clsx(classes.gridItem, classes.stackGridItem)} xs={12} lg={7} > <Box className={classes.stackBox}> <Stacks /> </Box> </Grid> </Grid> </Container> </section> </Layout> ); }; const useStyles = makeStyles((theme) => ({ home: { marginTop: 40, marginBottom: 40, }, gridContainer: {}, gridItem: { "& .summaryBox": { marginTop: 15, display: "flex", flexDirection: "column", "& .workLogo": { marginTop: 20, display: "flex", alignItems: "center", maxWidth: 420, "& .MuiSvgIcon-root": { flexBasis: "31.5%", fontSize: 40, "&:not(:last-of-type)": { marginRight: 10, }, }, }, }, }, stackGridItem: { marginTop: 54, }, chipGroup: { "& div:first-child": { marginRight: 18, }, }, introGroup: { marginTop: 28, "& .title": { fontSize: theme.typography.fontSizeXLarge, textTransform: "uppercase", color: theme.palette.text.body, }, "& .body": { marginTop: 2, "& .bodyStart, & .bodyEnd": { fontSize: 32, fontWeight: 500, color: theme.palette.text.primary, "& .name": { fontSize: 34, marginLeft: 2, marginRight: 2, }, }, "& .bodyContent": { marginTop: 5, marginBottom: 5, color: theme.palette.text.secondary, marginLeft: 20, fontSize: theme.typography.fontSizeXLarge, }, }, }, numExperience: { display: "flex", alignItems: "center", "& .captionYears": { fontSize: 50, marginRight: 8, lineHeight: 1, }, "& .captionText": { display: "inline-flex", flexDirection: "column", fontSize: 14, "& span": { lineHeight: 1.4, textTransform: "uppercase", }, }, }, stackBox: { display: "inline-block", position: "relative", width: "100%", paddingBottom: "92%", verticalAlign: "middle", overflow: "hidden", }, "@media screen and (min-width: 1280px)": { home: { marginTop: 60, }, stackGridItem: { marginTop: 0, }, gridItem: { "& .introBox": { marginTop: "15%", }, }, stackBox: { paddingBottom: "89%", }, }, })); export default IndexPage; <file_sep>/src/pages/blog.js import * as React from "react"; import Layout from "../components/layout"; import UnderConstruction from "../components/underConstruction"; const Blog = () => { return ( <Layout activeLink="blog"> <UnderConstruction /> </Layout> ); }; export default Blog; <file_sep>/src/reusables/Container.js import React from "react"; import { Container as MuiContainer, makeStyles } from "@material-ui/core"; const Container = ({ children, ...rest }) => { const classes = useStyles(); return ( <MuiContainer maxWidth="xl" classes={{ root: classes.containerRoot, maxWidthXl: classes.containerMaxWidth, }} {...rest} > {children} </MuiContainer> ); }; const useStyles = makeStyles({ containerMaxWidth: { maxWidth: "unset", }, containerRoot: {}, "@media screen and (min-width: 600px)": { containerRoot: { paddingLeft: "8%", paddingRight: "8%", }, }, "@media screen and (min-width: 1024px)": { containerRoot: { paddingLeft: "10%", paddingRight: "10%", }, }, "@media screen and (min-width: 1280px)": { containerRoot: { paddingLeft: "5%", paddingRight: "5%", }, }, "@media screen and (min-width: 1440px)": { containerRoot: { paddingLeft: "8%", paddingRight: "8%", }, }, }); export default Container;
506ed33840fd8b9a5d4c99f65d1cb705b0536798
[ "JavaScript" ]
8
JavaScript
omobosteven/stephenomobo.com
45c1c2183f2a70e84016ad2185b1fcb911e8ead2
e47223229adece761c6a4563103f57cf812c6d49
refs/heads/master
<file_sep>import os from os.path import join, dirname from dotenv import load_dotenv import mysql.connector dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) cnx = mysql.connector.connect( host = "localhost", user = "root", password = os.getenv('ROOT_<PASSWORD>') ) cursor = cnx.cursor()<file_sep>CREATE SCHEMA IF NOT EXISTS boligrating; USE boligrating; CREATE TABLE IF NOT EXISTS boligrating.leiligheter ( id BIGINT NOT NULL PRIMARY KEY, veinavn VARCHAR(100) NOT NULL, nummer SMALLINT NOT NULL, bokstav VARCHAR(2), nummer_bokstav VARCHAR(10) NOT NULL, bruksenhetsnummer VARCHAR(5), postnummer SMALLINT NOT NULL, poststed VARCHAR(50) NOT NULL, kommunenavn VARCHAR(50) NOT NULL, FULLTEXT(veinavn, nummer_bokstav, poststed, kommunenavn) ); CREATE TABLE IF NOT EXISTS boligrating.adresser ( id BIGINT NOT NULL PRIMARY KEY, veinavn VARCHAR(100) NOT NULL, nummer SMALLINT NOT NULL, bokstav VARCHAR(2), nummer_bokstav VARCHAR(10) NOT NULL, postnummer SMALLINT NOT NULL, poststed VARCHAR(50) NOT NULL, kommunenavn VARCHAR(50) NOT NULL, FULLTEXT(veinavn, nummer_bokstav, poststed, kommunenavn) ); CREATE TABLE IF NOT EXISTS boligrating.reviews ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, dato_review DATETIME NOT NULL, adresse_id INT NOT NULL REFERENCES adresser(bruksenhetid), karakter_total TINYINT NOT NULL, karakter_bygg TINYINT NOT NULL, karakter_pris TINYINT NOT NULL, karakter_utleier TINYINT NOT NULL, navn_utleier VARCHAR(100) NOT NULL, kontrakt_oppsigelsestid ENUM('1', '2', '3', '3+', 'ingen') NOT NULL, depositumskonto TINYINT NOT NULL, leiepris INT NOT NULL, depositum INT NOT NULL, leie_fra DATE NOT NULL, leie_til DATE NOT NULL, bo_alene TINYINT NOT NULL, telefonnummer_reviewer VARCHAR(11) NOT NULL, godkjent TINYINT NOT NULL ); CREATE VIEW boligrating.adresse_leilighet AS SELECT a.id as adresseID, l.id as leilighetID, a.veinavn, l.bruksenhetsnummer as leilighetnummer, a.nummer_bokstav as bolignummer, a.postnummer, a.poststed, a.kommunenavn FROM adresser a LEFT JOIN leiligheter l ON l.veinavn = a.veinavn AND l.nummer_bokstav = a.nummer_bokstav AND l.postnummer = a.postnummer AND l.poststed = a.poststed AND l.kommunenavn = a.kommunenavn;<file_sep>from db import cnx, cursor file = open('./data/test/matrikkelenAdresseLeilighetsniva.csv', encoding="utf8") query = "INSERT INTO boligrating_testdata.leiligheter(id, veinavn, nummer, bokstav, nummer_bokstav, bruksenhetsnummer, postnummer, poststed, kommunenavn) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s)" for l in file: line = l.split(';') if line[2] == 'vegadresse' and line[15] != '': try: data = (line[14], line[6], line[7], line[8], line[7] + line[8], line[15], line[21],line[22],line[1]) cursor.execute(query, data) cnx.commit() except: print("Did not write to database") print(line) cursor.close() cnx.close()<file_sep>from db import cnx, cursor file = open('./data/real/matrikkelenVegadresse.csv', encoding="utf8") query = "INSERT INTO boligrating.adresser(id, veinavn,nummer,bokstav,nummer_bokstav, postnummer, poststed, kommunenavn) VALUES(%s, %s, %s, %s, %s, %s, %s, %s)" for l in file: line = l.split(';') if line[3] == 'vegadresse': try: data = (line[0],line[7],line[8],line[9],line[8] + line[9],line[19],line[20],line[2]) cursor.execute(query, data) cnx.commit() except: print("Did not write to database") print(line) cursor.close() cnx.close() <file_sep>from db import cnx, cursor file = open('./data/test/matrikkelenVegadresse.csv', encoding="utf8") query = "INSERT INTO boligrating_testdata.adresser(id, veinavn,nummer,bokstav,nummer_bokstav, postnummer, poststed, kommunenavn) VALUES(%s, %s, %s, %s, %s, %s, %s, %s)" for l in file: line = l.split(';') if line[3] == 'vegadresse': data = (line[0],line[7],line[8],line[9],line[8] + line[9],line[19],line[20],line[2]) cursor.execute(query, data) cnx.commit() cursor.close() cnx.close() <file_sep>from db import cnx, cursor file = open('./data/test/reviews.csv', encoding="utf8") query = "INSERT INTO boligrating_testdata.reviews(dato_review, adresse_id, leilighet_id, karakter_total, karakter_bygg, karakter_pris, karakter_utleier, navn_utleier, kontrakt_oppsigelsestid, depositumskonto, leiepris, depositum, leie_fra, leie_til, bo_alene, telefonnummer_reviewer, godkjent) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" for l in file: line = l.split(';') if line[0] != 'dato_reviews': if line[2] == '': line[2] = None data = (line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7], line[8], line[9], line[10], line[11], line[12], line[13], line[14], line[15], line[16]) cursor.execute(query, data) cnx.commit() cursor.close() cnx.close()
dc099b305cbc7f9fa45345cf06009982db6677f6
[ "SQL", "Python" ]
6
Python
Hatland87/boligrating-db
e9963e2475886b3e89fd7603b51759c905dcb0b6
90db6a86ff86aa8548576218cc2d5fa9ee3395c7
refs/heads/master
<repo_name>M1ke/Codejo<file_sep>/checkout.rb require 'test/unit' class CheckoutTests < Test::Unit::TestCase def setup @apple = Item.new("apple",50,3,130) @biscuits = Item.new("biscuits",30,2,45) @chocolate = Item.new("chocolate",20,0,0) @tea = Item.new("tea",15,0,0) end def test_item_price_50 item=@apple assert item.price==50 end def test_item_is_apple item = @apple assert item.name == "apple" end def test_item_is_apple_for_50 item = @apple assert (item.name == "apple" && item.price == 50) end def test_item_is_biscuits_for_30 item=@biscuits assert (item.name == "biscuits" && item.price==30) end def test_basket_empty basket=Basket.new assert basket.empty? end def test_basket_not_empty_when_item_added basket=Basket.new basket.add(@apple) assert_equal false, basket.empty? end def test_basket_has_no_items_when_no_items_added basket=Basket.new assert_equal 0, basket.count end def test_basket_has_one_item_when_one_item_added basket=Basket.new basket.add(@apple) assert_equal 1, basket.count end def test_basket_has_two_items_when_two_items_added basket=Basket.new basket.add(@apple) basket.add(@biscuits) assert_equal 2, basket.count end def test_basket_total_is_50_when_one_apple_added basket = Basket.new basket.add(@apple) assert_equal 50, basket.total_price end def test_basket_total_is_30_when_one_biscuits_added basket = Basket.new basket.add(@biscuits) assert_equal 30, basket.total_price end def test_basket_total_is_80_when_apple_and_biscuits_added basket=Basket.new basket.add(@apple) basket.add(@biscuits) assert_equal 80, basket.total_price end def test_basket_total_is_130_when_three_apples_added basket=Basket.new basket.add(@apple) basket.add(@apple) basket.add(@apple) assert_equal 130, basket.total_price end def test_basket_total_is_160_when_three_apples_and_biscuits_added basket=Basket.new basket.add(@apple) basket.add(@apple) basket.add(@apple) basket.add(@biscuits) assert_equal 160, basket.total_price end def test_basket_total_is_160_when_two_apples_and_biscuits_and_apple_added basket=Basket.new basket.add(@apple) basket.add(@apple) basket.add(@biscuits) basket.add(@apple) assert_equal 160, basket.total_price end def test_basket_total_is_175_when_two_apples_and_biscuits_and_apple_and_biscuit_added basket=Basket.new basket.add(@apple) basket.add(@apple) basket.add(@biscuits) basket.add(@apple) basket.add(@biscuits) assert_equal 175, basket.total_price end def test_basket_total_is_210_when_two_apples_and_biscuits_and_apple_and_biscuit_and_chocolate_and_tea_added basket=Basket.new basket.add(@apple) basket.add(@apple) basket.add(@biscuits) basket.add(@apple) basket.add(@biscuits) basket.add(@chocolate) basket.add(@tea) assert_equal 210, basket.total_price end end class Basket def initialize @empty=true @count=0 @total_price = 0 @items=[] end def add(item) @total_price += item.price @items<<item @count+=1 @empty=false end def empty? return @empty end def count return @count end def total_price total_price=0; counts={"apple"=>0,"biscuits"=>0,"chocolate"=>0,"tea"=>0} @items.each do |item| total_price+=item.price if item.discount_num>0 counts[item.name]+=1 if counts[item.name]==item.discount_num total_price-=item.discount_price counts[item.name]=0; end end end return total_price end end class Item def initialize(item_name, item_price,item_discount_num,item_discount_price) @price=item_price @name=item_name @discount_num=item_discount_num @discount_price=(item_price*item_discount_num)-item_discount_price end def price return @price end def name return @name end def discount_num return @discount_num end def discount_price return @discount_price end end
3afed119c625b2aa6ef52f82bc4074caab19e3be
[ "Ruby" ]
1
Ruby
M1ke/Codejo
cdead7b3a7fa399c8db242d386493d17492b15e1
7e6539e2771daf4388cfc61eec5a1786f6aaccf7
refs/heads/master
<file_sep>jQuery(document).ready(function() { if(jQuery('.slides') == true) { jQuery('.slides').slides({ preload: true, play: 0, pause: 6000, generateNextPrev: true, animationStart: function() { jQuery(".slide_text").css("display","none"); jQuery(".slide_text").css("left","1186px"); }, animationComplete: function() { jQuery(".slide_text").css("display","none").css("display","block").animate({ left:"546px" }); } }); jQuery(".scroll_item").click(function(){ jQuery("html").animate({ scrollTop: jQuery(jQuery(this).attr("href")).offset().top + "px", }, { duration: 500 }); return false; }); /* Скрытие и показ новостей при прокрутке -----------------------------------------------------------------*/ jQuery(window).scroll(function(){ if (jQuery(window).scrollTop() > jQuery(".header").height() && jQuery(window).scrollTop() < jQuery(".header").height() + 100) { jQuery(".news").removeClass("animated bounceIn").fadeOut(); } else if(jQuery(window).scrollTop() >= jQuery(".header").height() + 100) { jQuery(".news").fadeIn().addClass("animated bounceIn"); } }); jQuery('.multiple-items').slick({ infinite: false, slidesToShow: 4, slidesToScroll: 4 }); } jQuery(window).resize(function(){ if(jQuery(window).width() < 768) { jQuery(".news__item").addClass("fadeInUpBig"); } else { jQuery(".news__item").removeClass("fadeInUpBig"); } }); /* Адаптивный слайдер -----------------------------------------------------------------*/ var _SlideshowTransitions = [ { $Duration: 1200, x: 0.2, y: -0.1, $Delay: 20, $Cols: 8, $Rows: 4, $Clip: 15, $During: {$Left: [0.3, 0.7], $Top: [0.3, 0.7]}, $Formation: $JssorSlideshowFormations$.$FormationStraightStairs, $Assembly: 260, $Easing: { $Left: $JssorEasing$.$EaseInWave, $Top: $JssorEasing$.$EaseInWave, $Clip: $JssorEasing$.$EaseOutQuad }, $Outside: true, $Round: {$Left: 1.3, $Top: 2.5} } , { $Duration: 1500, x: 0.3, y: -0.3, $Delay: 20, $Cols: 8, $Rows: 4, $Clip: 15, $During: {$Left: [0.1, 0.9], $Top: [0.1, 0.9]}, $SlideOut: true, $Formation: $JssorSlideshowFormations$.$FormationStraightStairs, $Assembly: 260, $Easing: { $Left: $JssorEasing$.$EaseInJump, $Top: $JssorEasing$.$EaseInJump, $Clip: $JssorEasing$.$EaseOutQuad }, $Outside: true, $Round: {$Left: 0.8, $Top: 2.5} } , { $Duration: 1500, x: 0.2, y: -0.1, $Delay: 20, $Cols: 8, $Rows: 4, $Clip: 15, $During: {$Left: [0.3, 0.7], $Top: [0.3, 0.7]}, $Formation: $JssorSlideshowFormations$.$FormationStraightStairs, $Assembly: 260, $Easing: { $Left: $JssorEasing$.$EaseInWave, $Top: $JssorEasing$.$EaseInWave, $Clip: $JssorEasing$.$EaseOutQuad }, $Outside: true, $Round: {$Left: 0.8, $Top: 2.5} } , { $Duration: 1500, x: 0.3, y: -0.3, $Delay: 80, $Cols: 8, $Rows: 4, $Clip: 15, $During: {$Left: [0.3, 0.7], $Top: [0.3, 0.7]}, $Easing: { $Left: $JssorEasing$.$EaseInJump, $Top: $JssorEasing$.$EaseInJump, $Clip: $JssorEasing$.$EaseOutQuad }, $Outside: true, $Round: {$Left: 0.8, $Top: 2.5} } , { $Duration: 1800, x: 1, y: 0.2, $Delay: 30, $Cols: 10, $Rows: 5, $Clip: 15, $During: {$Left: [0.3, 0.7], $Top: [0.3, 0.7]}, $SlideOut: true, $Reverse: true, $Formation: $JssorSlideshowFormations$.$FormationStraightStairs, $Assembly: 2050, $Easing: { $Left: $JssorEasing$.$EaseInOutSine, $Top: $JssorEasing$.$EaseOutWave, $Clip: $JssorEasing$.$EaseInOutQuad }, $Outside: true, $Round: {$Top: 1.3} } //Collapse Stairs , { $Duration: 1200, $Delay: 30, $Cols: 8, $Rows: 4, $Clip: 15, $SlideOut: true, $Formation: $JssorSlideshowFormations$.$FormationStraightStairs, $Assembly: 2049, $Easing: $JssorEasing$.$EaseOutQuad } //Collapse Random , { $Duration: 1000, $Delay: 80, $Cols: 8, $Rows: 4, $Clip: 15, $SlideOut: true, $Easing: $JssorEasing$.$EaseOutQuad } //Vertical Chess Stripe , { $Duration: 1000, y: -1, $Cols: 12, $Formation: $JssorSlideshowFormations$.$FormationStraight, $ChessMode: {$Column: 12} } //Extrude out Stripe , { $Duration: 1000, x: -0.2, $Delay: 40, $Cols: 12, $SlideOut: true, $Formation: $JssorSlideshowFormations$.$FormationStraight, $Assembly: 260, $Easing: {$Left: $JssorEasing$.$EaseInOutExpo, $Opacity: $JssorEasing$.$EaseInOutQuad}, $Opacity: 2, $Outside: true, $Round: {$Top: 0.5} } //Dominoes Stripe , { $Duration: 2000, y: -1, $Delay: 60, $Cols: 15, $SlideOut: true, $Formation: $JssorSlideshowFormations$.$FormationStraight, $Easing: $JssorEasing$.$EaseOutJump, $Round: {$Top: 1.5} } ]; var options = { $AutoPlay: true, //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false $AutoPlaySteps: 1, //[Optional] Steps to go for each navigation request (this options applys only when slideshow disabled), the default value is 1 $AutoPlayInterval: 4000, //[Optional] Interval (in milliseconds) to go for next slide since the previous stopped if the slider is auto playing, default value is 3000 $PauseOnHover: 1, //[Optional] Whether to pause when mouse over if a slider is auto playing, 0 no pause, 1 pause for desktop, 2 pause for touch device, 3 pause for desktop and touch device, 4 freeze for desktop, 8 freeze for touch device, 12 freeze for desktop and touch device, default value is 1 $ArrowKeyNavigation: true, //[Optional] Allows keyboard (arrow key) navigation or not, default value is false $SlideDuration: 500, //[Optional] Specifies default duration (swipe) for slide in milliseconds, default value is 500 $MinDragOffsetToSlide: 20, //[Optional] Minimum drag offset to trigger slide , default value is 20 //$SlideWidth: 600, //[Optional] Width of every slide in pixels, default value is width of 'slides' container //$SlideHeight: 300, //[Optional] Height of every slide in pixels, default value is height of 'slides' container $SlideSpacing: 0, //[Optional] Space between each slide in pixels, default value is 0 $DisplayPieces: 1, //[Optional] Number of pieces to display (the slideshow would be disabled if the value is set to greater than 1), the default value is 1 $ParkingPosition: 0, //[Optional] The offset position to park slide (this options applys only when slideshow disabled), default value is 0. $UISearchMode: 1, //[Optional] The way (0 parellel, 1 recursive, default value is 1) to search UI components (slides container, loading screen, navigator container, arrow navigator container, thumbnail navigator container etc). $PlayOrientation: 1, //[Optional] Orientation to play slide (for auto play, navigation), 1 horizental, 2 vertical, 5 horizental reverse, 6 vertical reverse, default value is 1 $DragOrientation: 3, //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0) $SlideshowOptions: { //[Optional] Options to specify and enable slideshow or not $Class: $JssorSlideshowRunner$, //[Required] Class to create instance of slideshow $Transitions: _SlideshowTransitions, //[Required] An array of slideshow transitions to play slideshow $TransitionsOrder: 1, //[Optional] The way to choose transition to play slide, 1 Sequence, 0 Random $ShowLink: true //[Optional] Whether to bring slide link on top of the slider when slideshow is running, default value is false }, $BulletNavigatorOptions: { //[Optional] Options to specify and enable navigator or not $Class: $JssorBulletNavigator$, //[Required] Class to create navigator instance $ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always $AutoCenter: 0, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0 $Steps: 1, //[Optional] Steps to go for each navigation request, default value is 1 $Lanes: 1, //[Optional] Specify lanes to arrange items, default value is 1 $SpacingX: 10, //[Optional] Horizontal space between each item in pixel, default value is 0 $SpacingY: 10, //[Optional] Vertical space between each item in pixel, default value is 0 $Orientation: 1 //[Optional] The orientation of the navigator, 1 horizontal, 2 vertical, default value is 1 }, $ArrowNavigatorOptions: { $Class: $JssorArrowNavigator$, //[Requried] Class to create arrow navigator instance $ChanceToShow: 2 //[Required] 0 Never, 1 Mouse Over, 2 Always } }; var jssor_slider2 = new $JssorSlider$("slider2_container", options); //responsive code begin //you can remove responsive code if you don't want the slider scales while window resizes function ScaleSlider() { var parentWidth = jssor_slider2.$Elmt.parentNode.clientWidth; if (parentWidth) jssor_slider2.$ScaleWidth(Math.min(parentWidth, 960)); else window.setTimeout(ScaleSlider, 30); } ScaleSlider(); jQuery(window).bind("load", ScaleSlider); jQuery(window).bind("resize", ScaleSlider); jQuery(window).bind("orientationchange", ScaleSlider); //responsive code end });
ddadc99338df47ae09c8970791a133374f2e1495
[ "JavaScript" ]
1
JavaScript
BorisProvotorov/mobil_test
a683c58ae65406b95b4f78e43693170146705848
f46051b89d2122dfd28920c0bd1cb17c3ffaeb6c
refs/heads/master
<file_sep>var value = prompt('What/s the "official" name of JavaScript?', 'Enter name:'); if ( value === 'ECMAScript') { alert('Right!'); } else { alert("You don't know ECMAScript"); }
d11d71253cc4258423600c8fef0e61a662db99de
[ "JavaScript" ]
1
JavaScript
hophiducanh/Exercise_if_else
65904746d49d38339c104bf0cab4f4398073acb7
5c958bc3fd8049ff75b5d14c6d4ec525130f9a5e
refs/heads/main
<file_sep>// // ContentView.swift // ReadMe // // Created by <NAME> on 2/1/21. // import SwiftUI struct ContentView: View { @State var library = Library() var body: some View { NavigationView { List(library.sortedBooks, id: \.self) { book in let _ = print("hi!", $library.uiImages[book]) BookRow( book: book, image: $library.uiImages[book] ) .lineLimit(1) } }.navigationTitle("My Library") } } struct BookRow: View { let book: Book @Binding var image: UIImage? var body: some View { NavigationLink(destination: DetailView(book: book, image: $image)) { HStack { Book.Image(uiImage: image, title: book.title) Book.Details(book: book) }.padding() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() .previewdInAllColorSchemes } } <file_sep>// // Library.swift // ReadMe // // Created by <NAME> on 2/1/21. // import class UIKit.UIImage final class Library { var sortedBooks: [Book] { booksCache } private var booksCache: [Book] = [ Book.init(title: "Henlo", author: "<NAME>"), Book.init(title: "Matcher", author: "<NAME>"), ] var uiImages: [Book: UIImage] = [:] } <file_sep>// // BookViews.swift // ReadMe // // Created by <NAME> on 2/1/21. // import SwiftUI extension Book { struct Image: View { let uiImage: UIImage? let title: String var size: CGFloat? var body: some View { if let image = uiImage.map(SwiftUI.Image.init) { image.resizable() .scaledToFill() .frame(width: size, height: size) } else { let symbol = SwiftUI.Image(title: title) ?? SwiftUI.Image(systemName: "book") symbol .resizable() .scaledToFit() .frame(width: size, height: size) .font(Font.title.weight(.light)) .foregroundColor(.secondary) } } } struct Details: View { let book: Book var body: some View { VStack(alignment:.leading) { Text(book.title) .font(.title2) .foregroundColor(.primary) .multilineTextAlignment(.leading) Text(book.author) .font(.title3) .foregroundColor(.secondary) .multilineTextAlignment(.leading) } } } } extension Book.Image { init(title: String) { self.init( uiImage: nil, title: title ) } } extension Image { init?(title: String) { guard let character = title.first, case let symbolName = "\(character.lowercased()).square", UIImage(systemName: symbolName) != nil else { return nil } self.init(systemName: symbolName) } } extension View { var previewdInAllColorSchemes: some View { ForEach(ColorScheme.allCases, id: \.self, content: preferredColorScheme) } } <file_sep>// // DetailView.swift // ReadMe // // Created by <NAME> on 2/1/21. // import class PhotosUI.PHPickerViewController import SwiftUI struct DetailView: View { var book: Book @Binding var image: UIImage? @State var showImagePicker = false var body: some View { VStack(alignment: .leading) { Book.Details(book: book) VStack { Book.Image(uiImage: image, title: book.title) Button("Update Image") { showImagePicker = true } } Spacer() }.padding() .sheet(isPresented: $showImagePicker) { PHPickerViewController.View(image: $image) } } } struct DetailView_Previews: PreviewProvider { static var previews: some View { DetailView(book: .init(), image: .constant(nil)) .previewdInAllColorSchemes } }
0c05121bb5ca59db902ded8af50d15edc85fed89
[ "Swift" ]
4
Swift
4shub/learning-ios-readme
c268d9c44dbd03021ac28197543e2e18057d83d1
7f9127288989efda04a001e5e3752a8f7d2e2c88
refs/heads/master
<repo_name>conglt10/demo-ens<file_sep>/src/App.js import React, { useEffect } from 'react'; import './App.css'; import getWeb3 from './ultils/getWeb3'; import { Form, Input, Button, Checkbox } from 'antd'; import 'antd/dist/antd.css'; import ENS from 'ethereum-ens'; const layout = { labelCol: { span: 8 }, wrapperCol: { span: 16 }, }; const tailLayout = { wrapperCol: { offset: 8, span: 16 }, }; function App() { useEffect(() => { const connectWeb3 = () => { window.addEventListener('load', async () => { getWeb3(); }); }; connectWeb3(); }); const onFinish = async (values) => { let web3 = window.web3; let myAccount = web3.currentProvider.selectedAddress; if (values.ens) { try { let ens = new ENS(web3); let address = await ens.resolver(values.address).addr(); console.log(address); await web3.eth.sendTransaction({ from: myAccount, to: address, value: values.value * 1000000000000000000, }); console.log('Success'); } catch (error) { console.log(error); } } else { try { await web3.eth.sendTransaction({ from: myAccount, to: values.address, value: values.value * 1000000000000000000, }); console.log('Success'); } catch (error) { console.log(error); } } }; const onFinishFailed = (errorInfo) => { console.log('Failed:', errorInfo); }; return ( <div className='App'> <div className='App-header'> <Form {...layout} name='basic' initialValues={{ remember: true }} onFinish={onFinish} onFinishFailed={onFinishFailed} > <Form.Item label='Address' name='address' rules={[{ required: true, message: 'Please input your address!' }]} > <Input /> </Form.Item> <Form.Item label='ETH' name='value' rules={[{ required: true, message: 'Please input your value!' }]} > <Input /> </Form.Item> <Form.Item {...tailLayout} name='ens' valuePropName='checked'> <Checkbox>Use ENS Domain</Checkbox> </Form.Item> <Form.Item {...tailLayout}> <Button type='primary' htmlType='submit'> Send </Button> </Form.Item> </Form> </div> </div> ); } export default App; <file_sep>/README.md <h1 align="center">ENS Demo 👋</h1> <p> <img src="https://img.shields.io/badge/version-1.0.0-blue.svg?cacheSeconds=2592000" /> </p> ![](/image/logo.png) ## Description Send ETH use ENS domain or address Ethereum ## Technology - ReactJS - ENS (ethereum-ens) - Ant-Design ### How to install ```sh yarn install ``` ```sh yarn start ``` View on: http://localhost:3000
b3252a932a7bb2fba03238661b8911e62d0e8ed0
[ "JavaScript", "Markdown" ]
2
JavaScript
conglt10/demo-ens
4489dfd939a137407fc4796c5a527ed1ea6fbd6f
fdb3f6632e81e5a680486d813fc33ab30a83f390
refs/heads/master
<repo_name>alchermd/AmericanFootballScoreKeeper<file_sep>/app/src/main/java/me/johnalcher/americanfootballscorekeeper/MainActivity.java package me.johnalcher.americanfootballscorekeeper; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import android.view.View; /** * This activity keeps track of the score for two Football teams. */ public class MainActivity extends AppCompatActivity { int homeScore = 0; int awayScore = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** * Displays the score for the HOME team. * * @param score */ public void displayHomeScore(int score) { TextView homeScore = (TextView) findViewById(R.id.home_score); homeScore.setText(Integer.toString(score)); } /** * Displays the score for the AWAY team. * * @param score */ public void displayAwayScore(int score) { TextView awayScore = (TextView) findViewById(R.id.away_score); awayScore.setText(Integer.toString(score)); } /** * This method is called when the HOME team scores a touchdown. * * @param view */ public void homeTouchDown(View view) { homeScore += 6; displayHomeScore(homeScore); } /** * This method is called when the HOME team scores a field goal. * * @param view */ public void homeFieldGoal(View view) { homeScore += 3; displayHomeScore(homeScore); } /** * This method is called when the HOME team scores two points. * * @param view */ public void homePlusTwo(View view) { homeScore += 2; displayHomeScore(homeScore); } /** * This method is called when the HOME team scores a point. * * @param view */ public void homePlusOne(View view) { homeScore += 1; displayHomeScore(homeScore); } /** * This method is called when the AWAY team scores a touchdown. * * @param view */ public void awayTouchDown(View view) { awayScore += 6; displayAwayScore(awayScore); } /** * This method is called when the AWAY team scores a field goal. * * @param view */ public void awayFieldGoal(View view) { awayScore += 3; displayAwayScore(awayScore); } /** * This method is called when the AWAY team scores two points. * * @param view */ public void awayPlusTwo(View view) { awayScore += 2; displayAwayScore(awayScore); } /** * This method is called when the AWAY team scores a point. * * @param view */ public void awayPlusOne(View view) { awayScore += 1; displayAwayScore(awayScore); } /** * This method is called when the reset button is clicked. */ public void resetScores(View view) { homeScore = 0; awayScore = 0; displayHomeScore(homeScore); displayAwayScore(awayScore); } }
3ddf8211cd6dfbe97e5635b22dabf451183917e4
[ "Java" ]
1
Java
alchermd/AmericanFootballScoreKeeper
343e516eff0a22b10cdcafee8df5d5e8a701ae49
8e063d9fecfe9182007e9240eaec5f06ec48148d
refs/heads/master
<file_sep>import sys import tkinter as tk from PIL import Image from tkinter import filedialog h2 = 0 # file dialog to choose image def open_dialog(): root = tk.Tk() root.withdraw() return filedialog.askopenfilename() # Manipulate image data def img_manip(img, w2): # Store width and height values w, h = img.size aRatio = h / w h2 = int(aRatio * w2 * 0.55) img = img.resize((w2, h2)) # Convert image to grey-scale img = img.convert('L') return img.getdata() # Convert Pixel data to char def main(): asciiChar = ["B", "S", "#", "&", "@", "$", "%", "*", "!", ":", "."] # Open received path from file dialog img = Image.open(open_dialog()) # Choose character width and height for ASCII width = 200 pixelData = img_manip(img, width) newPixelData = ''.join([asciiChar[pixel//25] for pixel in pixelData]) imgASCII = "\n".join([newPixelData[index:index + width] for index in range(0, len(newPixelData), width)]) print(imgASCII) if __name__ == "__main__": main()
715beb179493b03e8a58a50871f8f16787dc644e
[ "Python" ]
1
Python
k48shah/IMGtoASCII
af72f8d75d94b66107dad7f923af115953cc59dd
7f4dcf00c90c6ec544c820a63396c20affa73cf7
refs/heads/master
<repo_name>forviz/emerce<file_sep>/app/models/Merchant.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const mercharntSchema = new Schema({ name: String, client_id: String, client_secret: String, }); const Merchant = mongoose.model('Merchant', mercharntSchema); module.exports = Merchant; <file_sep>/app/controllers/merchantController.js const Merchant = require('../models/Merchant'); const uuidv1 = require('uuid/v1'); const checkInput = (req) => { if (req.body.name === '') { return { error: { code: 402, status: 'bad request', }, }; } else if (!req.body.name) { return { error: { code: 400, status: 'bad request', }, }; } return false; }; const createMerchant = async (req, res, next) => { try { const checkError = checkInput(req); if (checkError) { res.status(checkError.error.code).send(checkError.error); return; } const m = new Merchant({ name: req.body.name, client_id: uuidv1(), client_secret: uuidv1(), }); m.save((err) => { if (err) { res.status(500).send({ error: { code: 500, status: 'cannot save into database', }, }); } res.json({ data: { id: m._id, name: m.name, client_id: m.client_id, client_secret: m.client_secret, }, }); }); } catch (e) { next(e); } }; module.exports = { createMerchant, }; <file_sep>/app/controllers/product/index.js //import { getIdentityFromToken } from '../../utils/jwtUtils'; const mongoose = require('mongoose'); const Product = require('../../models/Product'); exports.getAll = async (req, res, next) => { try { const products = await Product.find(); res.json({ data: products, }); } catch (e) { next(e); } }; exports.getSingle = async (req, res, next) => { try {//597b012aa1c6000a501c0490 const productId = req.params.product_id; const products = await Product.findOne({ _id: productId }); res.json({ data: products, }); } catch (e) { next(e); } }; exports.createProduct = async (req, res, next) => { try { // const product = new Product(); const type = req.body.type; const name = req.body.name; const description = req.body.description; const slug = req.body.slug; const status = req.body.status; const commodity_type = req.body.commodity_type; const amount = req.body.amount; const includes_tax = req.body.includes_tax; const weight = req.body.weight; const products = new Product({ type: type, name: name, description: description, slug: slug, status: status, commodity_type: commodity_type, price: [{ "amount": amount, "includes_tax": includes_tax }], weight: { "value": weight } }); const result = await products.save(); res.json({ data: result, }); } catch (e) { next(e); } }; exports.updateProduct = async (req, res, next) => { try { const productId = req.params.product_id; const type = req.body.type; const name = req.body.name; const description = req.body.description; const slug = req.body.slug; const status = req.body.status; const commodity_type = req.body.commodity_type; const amount = req.body.amount; const includes_tax = req.body.includes_tax; const weight = req.body.weight; const products = await Product.update( { _id: productId }, { $set: { type: type, name: name, description: description, slug: slug, status: status, commodity_type: commodity_type, price: [{ amount: amount, includes_tax: includes_tax }], weight: { value: weight } } } ); const result = await Product.findOne({ _id: productId }); res.json({ data: result, }); } catch (e) { next(e); } }; exports.delete = async (req, res, next) => { try { const productId = req.params.product_id; await Product.remove( { _id: productId } ) res.json({ data: { id: productId }, }); } catch (e) { next(e); } }; <file_sep>/.env.example MONGODB_URI=mongodb://192.168.0.108:27017/emerce MONGOLAB_URI=mongodb://192.168.0.108:27017/emerce <file_sep>/app/controllers/oauthController.js // import _ from 'lodash'; const util = require('util'); const AccessToken = require('../models/AccessToken'); const jwt = require('jsonwebtoken'); const createToken = async (req, res, next) => { try { const clientId = req.body.client_id; // const clientSecret = req.body.client_secret; const grantType = req.body.grant_type; req.getValidationResult().then((result) => { if (!result.isEmpty()) { res.status(400).send(`There have been validation errors: ${util.inspect(result.array())}`); return; } const m = new AccessToken({ identifier: grantType, }); m.save((err) => { if (err) { res.json({ errors: { code: 404, status: 'not found', }, }); } const _token = jwt.sign({ data: clientId + m._id }, 'emerceSecret', { expiresIn: '1 days' }); AccessToken.findOneAndUpdate({ _id: m._id }, { $set: { access_token: _token, }, }, (updateErr, updateM) => { if (updateErr) { res.json({ errors: { code: 404, status: 'failed', }, }); } res.json({ data: { identifier: updateM.identifier, access_token: updateM.access_token, expires: updateM.expires, expires_in: updateM.expires_in, token_type: updateM.token_type, }, }); }, ); }); }); } catch (e) { next(e); } }; module.exports = { createToken, }; <file_sep>/app/models/Product.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const productSchema = new Schema({ id: Schema.Types.ObjectId, type: String, name: String, description: String, slug: String, status: String, price: [{ amount: Number, currency: { type: String, default: 'THB', }, includes_tax: Boolean }], commodity_type: String, weight: { unit: { type: String, default: 'kg', }, value: Number } }); const Product = mongoose.model('Product', productSchema); module.exports = Product; <file_sep>/app/utils/index.js export const test = () => { console.log('test'); } export const toEndUser = (data = {}, errors = [], meta = {}) => { return { data: data, errors: errors, meta: meta, } }<file_sep>/app/Models/Cart.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const cartSchema = new Schema({ ref: String, merchantId: String, items: [{}], createdAt: { type: Date, default: Date.now }, updatedAt: { type: Date, default: Date.now }, }); export default mongoose.model('Cart', cartSchema);
26a2bd00a059b83724293f770d0c74951d431c45
[ "JavaScript", "Shell" ]
8
JavaScript
forviz/emerce
2c596ba471e170f9430f2f69e655bfde28399123
3bf0e183ad151d6ee3775aabb6c7f82fcffe88ed
refs/heads/master
<file_sep>import Main from "./views/Main"; import NewProduct from "./views/NewProduct"; import NoMatch from "./views/NoMatch"; import AddRation from "./views/AddRation"; import Products from "./views/Products"; const routes = [ { path: "/", component: Main, }, { path: "/new-product", component: NewProduct, }, { path: "/add-ration", component: AddRation, }, { path: "/products", component: Products, }, { path: "*", component: NoMatch, }, ]; export default routes; <file_sep>import React, { useState, useEffect } from "react"; import { Link } from "react-router-dom"; import { read, save } from "../core/api"; import Product from "../components/products-page/Product"; export default function Products() { const [products, setProducts] = useState([]); const [isLoading, setIsLoading] = useState(true); useEffect(() => { const data = read("products"); data.sort((a, b) => (a.title > b.title ? 1 : -1)); setProducts(data); setIsLoading(false); }, []); useEffect(() => { save("products", products); }, [products]); function removeHandler(id) { const res = window.confirm("Вы уверены, что хотите удалить?"); if (res) { const data = products.filter((item) => { return item.id !== id; }); setProducts(data); } } const prods = products.map((item) => { return ( <Product title={item.title} proteins={item.proteins} fats={item.fats} carbohydrates={item.carbohydrates} calories={item.calories} id={item.id} remove={removeHandler} key={item.id} /> ); }); return ( <div className="products"> <div className="container"> {!isLoading && prods} {!isLoading && ( <Link to="/new-product" className="button button_mobile"> <span className="material-icons">add_circle</span> </Link> )} </div> </div> ); } <file_sep>https://elnasim.github.io/react/calorie-calc/<file_sep>import React from "react"; import { HashRouter, Switch, Route } from "react-router-dom"; import routes from "./routes"; import Header from "./components/app/Header"; export default function App() { return ( <HashRouter> <div> <Header /> <Switch> {routes.map((route, i) => ( <Route key={i} exact={route.path === "/"} path={route.path} render={(props) => <route.component {...props} />} /> ))} </Switch> </div> </HashRouter> ); } <file_sep>import React, { useEffect, useState } from "react"; import { Link } from "react-router-dom"; import Product from "../components/main-page/Product"; import { read, save } from "../core/api"; export default function Main() { const [ration, setRation] = useState([]); const [summary, setSummary] = useState({ proteins: 0, calories: 0, carbohydrates: 0, fats: 0, }); const [isLoading, setIsLoading] = useState(true); useEffect(() => { const data = read("ration"); setRation(data); setIsLoading(false); }, []); useEffect(() => { if (ration) { rationInfoCalc(); save("ration", ration); } }, [ration]); function rationInfoCalc() { let proteins = 0, carbohydrates = 0, calories = 0, fats = 0; for (let item of ration) { proteins += Math.round((item.proteins * item.weight) / 100); calories += Math.round((item.calories * item.weight) / 100); carbohydrates += Math.round((item.carbohydrates * item.weight) / 100); fats += Math.round((item.fats * item.weight) / 100); } const data = { proteins, calories, carbohydrates, fats, }; setSummary(data); } function removeHandler(id) { const res = window.confirm("Вы уверены, что хотите удалить?"); if (res) { const data = ration.filter((item) => { return item.id !== id; }); setRation(data); } } const products = ration.map((item) => { return ( <Product title={item.title} proteins={item.proteins} fats={item.fats} carbohydrates={item.carbohydrates} calories={item.calories} id={item.id} weight={item.weight} remove={removeHandler} key={item.id} /> ); }); return ( <div className="main"> <div className="container"> {/* <div className="day"> <div className="day__change"> <span className="material-icons">undo</span> </div> <div className="day__date">16.05.2020</div> <div className="day__change"> <span className="material-icons">redo</span> </div> </div> */} {!isLoading && products} {!isLoading && ( <div className="product-main"> <div className="product-main__title">Всего</div> <div className="product-main__info"> <div className="product-main__i"> {summary.proteins} <br />Б </div> <div className="product-main__i"> {summary.fats} <br />Ж </div> <div className="product-main__i"> {summary.carbohydrates} <br />У </div> <div className="product-main__i"> {summary.calories} <br /> Ккал </div> </div> </div> )} {!isLoading && ( <Link to="/add-ration" className="button button_mobile"> <span className="material-icons">add_circle</span> </Link> )} </div> </div> ); }
ae5f10a76341fa33ef414e791e597e3229a98417
[ "JavaScript", "Markdown" ]
5
JavaScript
elnasim/calorie-calc-react
7233b7c03b89da88d9bb3bd1fb17edb6edb7c5d7
4fe0981d2730194a2b349196a016d1921b0c2894
refs/heads/master
<repo_name>arecker/cloudmon<file_sep>/cloudmon.py import os import CloudFlare import yaml cloudflare = CloudFlare.CloudFlare() class Record(object): def __init__(self, zone): self.zone_id = cloudflare.zones.get(params={'name': zone})[0]['id'] def __repr__(self): return 'Record <{} ({})>'.format(self.name, self.type) @classmethod def from_config(cls, zone, config): record = cls(zone) record.name = config['name'] record.type = config['type'] record.content = config['content'] record.proxied = config.get('proxied', False) return record.populate() def as_search_params(self): return { 'name': self.name, 'type': self.type } def as_params(self): result = self.as_search_params() result['content'] = self.content result['proxied'] = self.proxied return result def exists(self): return any([ record for record in cloudflare.zones.dns_records.get(self.zone_id) if self.name == record['name'] and self.type == record['type'] ]) def populate(self): if self.exists(): self.id = cloudflare.zones.dns_records.get( self.zone_id, params=self.as_search_params() )[0]['id'] else: self.id = None return self def apply(self): if self.id: cloudflare.zones.dns_records.put(self.zone_id, self.id, data=self.as_params()) else: cloudflare.zones.dns_records.post(self.zone_id, data=self.as_params()) def main(): here = os.path.dirname(os.path.realpath(__file__)) config = yaml.load(open(os.path.join(here, 'config.yml'))) for zone, info in config.items(): config_records = map( lambda c: Record.from_config(zone, c), info.get('records', []) ) for record in config_records: record.apply()
2739d2a11d99007a299e8e8b493bc6d825686d82
[ "Python" ]
1
Python
arecker/cloudmon
e06c58d36ee52a27d3c46d080d3e65a029858abf
21488c7868885285b82906e4b97e3be21097b722
refs/heads/main
<repo_name>pokraspolina/T.Ishmetova<file_sep>/salon/js/main.js /* When the user clicks on the button, toggle between hiding and showing the dropdown content */ function validator(){ let i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } function myFunctionone() { document.getElementById("myDropdown").classList.toggle("show"); } // Close the dropdown menu if the user clicks outside of it window.onclick = function(event) { if (!event.target.matches('.btn')) { var dropdowns = document.getElementsByClassName("first"); validator(); } } function myFunctionsecond() { document.getElementById("myDropdownsecond").classList.toggle("show"); } // Close the dropdown menu if the user clicks outside of it window.onclick = function(event) { if (!event.target.matches('.btn')) { var dropdowns = document.getElementsByClassName("second"); validator(); } } function myFunctionthird() { document.getElementById("myDropdownthird").classList.toggle("show"); } // Close the dropdown menu if the user clicks outside of it window.onclick = function(event) { if (!event.target.matches('.btn')) { var dropdowns = document.getElementsByClassName("third"); validator(); } } function myFunctionfour() { document.getElementById("myDropdownfour").classList.toggle("show"); } // Close the dropdown menu if the user clicks outside of it window.onclick = function(event) { if (!event.target.matches('.btn')) { var dropdowns = document.getElementsByClassName("four"); validator(); } } function myFunctionfive() { document.getElementById("myDropdownfive").classList.toggle("show"); } // Close the dropdown menu if the user clicks outside of it window.onclick = function(event) { if (!event.target.matches('.btn')) { var dropdowns = document.getElementsByClassName("five"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } function myFunctionnail() { document.getElementById("myDropdownnail").classList.toggle("show"); } // Close the dropdown menu if the user clicks outside of it window.onclick = function(event) { if (!event.target.matches('.btn')) { var dropdowns = document.getElementsByClassName("nail"); validator(); } } function myFunctionsix() { document.getElementById("myDropdownsix").classList.toggle("show"); } // Close the dropdown menu if the user clicks outside of it window.onclick = function(event) { if (!event.target.matches('.btn')) { var dropdowns = document.getElementsByClassName("six"); validator(); } } function myFunction(imgs) { var expandImg = document.getElementById("expandedImg"); var imgText = document.getElementById("imgtext"); expandImg.src = imgs.src; imgText.innerHTML = imgs.alt; expandImg.parentElement.style.display = "block"; } $(function() { $(window).scroll(function() { if($(this).scrollTop() != 0) { $('#topNubex').fadeIn(); } else { $('#topNubex').fadeOut(); } }); $('#topNubex').click(function() { $('body,html').animate({scrollTop:0},700); }); }); var paused = false; $(".crop-img").click(function(){ $("#expandedImg").attr('src', $(this).attr('src')); }); // the counter variable that keeps // track of which image you are showing var counter = 1; // virtually click on the current // image to load it into the big image $("#image"+counter).click(); // when you click on the backwards // button select the previous image $("#backward").click(function (){ // go back one in the counter counter = counter - 1; // if we are below 1 (the first // image) loop round to 4 (the // last image) if(counter < 1){ counter = 12; } // virtually click on the current // image to load it into the big image $("#image"+counter).click(); }); // when you click on the backwards // button select the next image $("#forward").click(function (){ // go forward one in the counter counter = counter + 1; // if we are above 4 (the last // image) loop round to 1 (the // first image) if(counter > 12){ counter = 1; } // virtually click on the current // image to load it into the big image $("#image"+counter).click(); }); $("#expandedImg").click(function (){ paused = !paused; }); // set interval makes it move // forward every 3 second setInterval(function (){ // first check if it is paused if(!paused){ // virtual click the forward // button $("#forward").click(); }; }, 5000);
a2dc2e85f94c55eb068aa7ccd24afb9da1f8e6f6
[ "JavaScript" ]
1
JavaScript
pokraspolina/T.Ishmetova
44c06f727a1e554f5bba3b5a0e6dde4913334e70
5624651fae290568efa1775d7bde40d0ede1e4df
refs/heads/master
<repo_name>ULL-ESIT-GRADOII-PL/mongodb-mongoose-csv-ivan_garcia<file_sep>/models/db.js (function() { "use strict"; const util = require('util'); const mongoose = require('mongoose'); const EntradaSchema = //Introducimos el esquema csv mongoose.Schema({ "name": { type: String, unique: true }, "content": String }); const Entrada = mongoose.model("Entrada", EntradaSchema); /*let entrada1 = new Entrada({"rank":"ace", "suit":"spades ♠", "chuchu": [{a: "hello", b: "world!"}]}); let entrada2 = new Entrada({"rank":"2", "suit":"hearts ♥", "chuchu": [{a: "hola", b: "mundo"}]}); let entrada3 = new Entrada({"rank":"3", "suit":"clubs ♣", "chuchu": [{a: "hola", b: "mundo"}]}); let c4 = new Entrada({"rank":"4", "suit":"diamonds ♦", "chuchu": [{a: "hola", b: "mundo"}]});*/ let entrada1 = new Entrada({ "name": "entrada1.csv", "content": `"producto", "precio" "camisa", "4,3" "libro de O\"Reilly", "7,2"` }); let entrada2 = new Entrada({ "name": "entrada2.csv", "content": `"producto", "precio" "fecha" "camisa", "4,3", "14/01" "libro de O\"Reilly", "7,2" "13/02"` }); let entrada3 = new Entrada({ "name": "entrada3.csv", "content": `"edad", "sueldo", "peso" , "6000€", "90Kg" 47, "3000€", "100Kg"` }); let promesa1 = entrada1.save(function (err) { if (err) { console.log(`Hubieron errores:\n${err}`); return err; } console.log(`Saved: ${entrada1}`); }); let promesa2 = entrada2.save(function (err) { if (err) { console.log(`Hubieron errores:\n${err}`); return err; } console.log(`Saved: ${entrada2}`); }); let promesa3 = Entrada.create(entrada3, function (err, x) { if (err) { console.log(`Hubieron errores:\n${err}`); return err; } console.log(`Saved promesa3: ${x}`); }); Promise.all([promesa1, promesa2, promesa3]).then( (value) => { console.log(util.inspect(value, {depth: null})); mongoose.connection.close(); }); module.exports = Entrada; })(); <file_sep>/app.js "use strict"; const express = require('express'); const app = express(); const path = require('path'); const expressLayouts = require('express-ejs-layouts'); const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/basededatos'); app.set('port', (process.env.PORT || 5000)); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(expressLayouts); app.use(express.static(__dirname + '/public')); const calculate = require('./models/calculate'); app.get('/', (request, response) => { response.render('index', { title: 'Comma Separated Value Analyzer' }); }); app.get('/csv', (request, response) => { response.send({ "rows": calculate(request.query.input) }); }); const Entrada = require('./models/db'); //Guardar maximo 4 entradas. Siempre se cambia la ultima app.get('/mongo/', function(req, res) { Entrada.find({}, function(err, docs) { if (err) return err; if (docs.length >= 4) { Entrada.find({ name: docs[3].name }).remove().exec(); } }); let input = new Entrada({ "name": req.query.name, "content": req.query.content }); input.save(function(err) { if (err) { console.log(`Hubieron errores:\n${err}`); return err; } console.log(`Guardado: ${input}`); }); }); app.get('/find', function(req, res) { Entrada.find({}, function(err, docs) { if (err) return err; res.send(docs); }); }); //se devuelve el contenido app.get('/findPorNombre', function(req, res) { Entrada.find({ name: req.query.name }, function(err, docs) { res.send(docs); }); }); /*// Routes app.get('/', producto.index) app.get('/producto/:id', producto.show_edit) app.post('/producto/:id', producto.update) app.get('/delete-producto/:id', producto.remove) app.get('/nuevo-producto', producto.create)*/ app.listen(app.get('port'), () => { console.log(`Node app is running at localhost: ${app.get('port')}` ); }); <file_sep>/controllers/producto.js exports.index = function (req, res, next) { res.send('Funciona!') } <file_sep>/README.md # mongodb-mongoose-csv-ivan_garcia mongodb-mongoose-csv-ivan_garcia created by GitHub Classroom <NAME> ## Practica CSV usando MongoDB * Practica Procesadores de Lenguaje * Repositorio C9: https://ide.c9.io/alu0100693737/mongodb-csv#openfile-README.md Para usar la aplicacion escribir en la terminal de C9: * node app.js y entrar en la siguiente URL: * https://mongodb-csv-alu0100693737.c9users.io/? - Al estar ya cargada la db, la terminal dice que hay 3 falsos errores. No pudieron crearse, ya estan creados con ese nombre. - Si se cambia la db, cargar node app.js dos veces. * Aplicacion sin MongoDB: http://fierce-wildwood-36000.herokuapp.com/
68f7fc6d23548eae44a773a2afb7d5a22322c05b
[ "JavaScript", "Markdown" ]
4
JavaScript
ULL-ESIT-GRADOII-PL/mongodb-mongoose-csv-ivan_garcia
6bc0c6bcec4e560a1147bd8a9b281ffed171a815
862074f25ce92c12728344f0ba891d9f5bfcdfa4
refs/heads/main
<file_sep># Normalizing Flows Test Bench Some simple experiments to try out off-the-shelf Normalizing Flow architectures.<file_sep># Refs: # https://github.com/clbonet/Generative-Models/tree/main/Normalizing%20Flows # https://github.com/acids-ircam/pytorch_flows import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.distributions as td from abc import ABC, abstractmethod from tqdm.auto import trange class BaseNormalizingFlow(ABC, nn.Module): """ Abtract class for NF """ def __init__(self, device): super().__init__() if device is None: self.device = "cuda" if torch.cuda.is_available() else "cpu" else: self.device = device @abstractmethod def forward(self, x): pass @abstractmethod def backward(self, z): pass class Shifting(nn.Module): def __init__(self, input_dim, nh=None, n_layers=1, device=None): super().__init__() if nh is None: self.nh = input_dim self.layers = nn.ModuleList() self.layers.append(nn.Linear(input_dim, self.nh)) for i in range(n_layers): self.layers.append(nn.Linear(self.nh, self.nh)) self.layers.append(nn.Linear(self.nh, input_dim)) self.layers.to(device) def forward(self, x): for layer in self.layers: x = F.leaky_relu(layer(x), 0.2) return x class Scaling(nn.Module): def __init__(self, input_dim, nh=None, n_layers=1, device=None): super().__init__() if nh is None: self.nh = input_dim self.layers = nn.ModuleList() self.layers.append(nn.Linear(input_dim, self.nh)) for i in range(n_layers): self.layers.append(nn.Linear(self.nh, self.nh)) self.layers.append(nn.Linear(self.nh, input_dim)) self.layers.to(device) def forward(self, x): for layer in self.layers: x = torch.tanh(layer(x)) return x class AffineCoupling(BaseNormalizingFlow): def __init__(self, input_dim, device=None): super().__init__(device) self.scaling = Scaling(input_dim // 2, device=self.device) self.shifting = Shifting(input_dim // 2, device=self.device) self.k = input_dim // 2 def forward(self, x): x0, x1 = x[:, :self.k], x[:, self.k:] s = self.scaling(x0) t = self.shifting(x0) z0 = x0 z1 = torch.exp(s)*x1+t z = torch.cat([z0, z1], dim=1) return z, torch.sum(s, dim=1) def backward(self, z): z0, z1 = z[:, :self.k], z[:, self.k:] s = self.scaling(z0) t = self.shifting(z0) x0 = z0 x1 = torch.exp(-s)*(z1-t) x = torch.cat([x0, x1], dim=1) return x, -torch.sum(s, dim=1) class Reverse(BaseNormalizingFlow): def __init__(self, input_dim, device=None): super().__init__(device) self.permute = torch.arange(input_dim - 1, -1, -1) self.inverse = torch.argsort(self.permute) def forward(self, x): return x[:, self.permute], torch.zeros(x.size(0), device=self.device) def backward(self, z): return z[:, self.inverse], torch.zeros(z.size(0), device=self.device) class BatchNorm(BaseNormalizingFlow): def __init__(self, d, eps=1e-5, momentum=0.95, device=None): super().__init__(device) self.eps = eps self.momentum = momentum self.train_mean = torch.zeros(d, device=self.device) self.train_var = torch.ones(d, device=self.device) self.gamma = nn.Parameter(torch.ones(d, device=self.device)) self.beta = nn.Parameter(torch.ones(d, device=self.device)) def forward(self, x): if self.training: self.batch_mean = x.mean(0) self.batch_var = (x - self.batch_mean).pow(2).mean(0) + self.eps self.train_mean = self.momentum * self.train_mean + (1 - self.momentum) * self.batch_mean self.train_var = self.momentum * self.train_var + (1 - self.momentum) * self.batch_var mean = self.batch_mean var = self.batch_var else: mean = self.train_mean var = self.train_var z = torch.exp(self.gamma) * (x - mean) / var.sqrt() + self.beta log_det = torch.sum(self.gamma - 0.5 * torch.log(var)) return z, log_det def backward(self, z): if self.training: mean = self.batch_mean var = self.batch_var else: mean = self.train_mean var = self.train_var x = (z - self.beta) * torch.exp(-self.gamma) * var.sqrt() + mean log_det = torch.sum(-self.gamma + torch.log(var)) return x, log_det class NormalizingFlows(BaseNormalizingFlow): def __init__(self, flows, device=None): super().__init__(device) self.flows = nn.ModuleList(flows) def forward(self, x): log_det = torch.zeros(x.shape[0], device=self.device) zs = [x] for flow in self.flows: x, log_det_i = flow(x) log_det += log_det_i zs.append(x) return zs, log_det def backward(self, z): log_det = torch.zeros(z.shape[0], device=self.device) xs = [z] for flow in self.flows[::-1]: z, log_det_i = flow.backward(z) log_det += log_det_i xs.append(z) return xs, log_det class RealNVP(BaseNormalizingFlow): """ Real NVP """ def __init__(self, input_dim, depth=5, device=None): super().__init__(device) self.input_dim = input_dim flows = [] for i in range(depth): flows.append(AffineCoupling(input_dim, device=self.device)) flows.append(Reverse(input_dim, device=self.device)) flows.append(BatchNorm(input_dim, device=self.device)) self.model = NormalizingFlows(flows) self.optimizer = optim.Adam(self.model.parameters(), lr=1e-4, weight_decay=1e-5) self.prior = td.multivariate_normal.MultivariateNormal( torch.zeros(input_dim, device=self.device), torch.eye(input_dim, device=self.device)) print("number of params: ", sum(p.numel() for p in self.model.parameters())) def forward(self, x): return self.model.forward(x) def backward(self, z): return self.model.backward(z) def loss(self, z, log_det): log_prior = self.prior.log_prob(z) return -(log_prior + log_det).mean() def train(self, trainloader, epochs=50): print_interval = 100 pbar = trange(epochs) for epoch in pbar: for i, (x_batch, _) in enumerate(trainloader): x_batch = x_batch.to(self.device) z, log_det = self.forward(x_batch) loss = self.loss(z[-1], log_det) loss.backward() self.optimizer.step() self.optimizer.zero_grad() if i % print_interval == 0: pbar.set_postfix_str(f"loss = {loss.item():.3f}") if epoch % 5 == 0: self.plot_generations() def plot_generations(self, num_samples=10): lambd = 1e-6 z_sample = torch.randn(num_samples, self.input_dim).to(self.device) x_gen, _ = self.backward(z_sample) x_gen = (torch.sigmoid(x_gen[-1]) - lambd) / (1 - 2 * lambd) x_gen = x_gen.cpu().detach().numpy().reshape(-1, 28, 28) fig, axes = plt.subplots(nrows=1, ncols=num_samples, figsize=(num_samples, 1)) for i in range(num_samples): axes[i].imshow(x_gen[i], cmap="gray") axes[i].axis("off") plt.show()
a40d500193457848f415d11f58eeaa1d635fcdf5
[ "Markdown", "Python" ]
2
Markdown
bmalezieux/NF_test_bench
20e6244aba1a720591c8f3732c9b56729a40533e
2ba0d10a4c73d0602f6c32b1fbe7bc8be2183b75
refs/heads/master
<file_sep>def square_array(array) count=0 array.each do |item| array[count]=item**2 count+=1 end end
f8dd682673a4db94749d47ed1e5ca36993f83b59
[ "Ruby" ]
1
Ruby
skyfox93/square_array-nyc-web-102918
8c4c883c9451abd70ddfcc067004f8877ad10c86
157b2869bfd9f875fe5c25cb4b598a547eb10bd5
refs/heads/master
<repo_name>Glokta0/RDW_CurvedPathConfigurator<file_sep>/Assets/_scripts/VirtualIntersection.cs using System.Collections; using System.Collections.Generic; using UnityEngine; /* * An intersection is the (virtual world) crossing of several paths. * Each intersection has one jointpoint as a real world counterpart. * */ [System.Serializable] public class VirtualIntersection : ScriptableObject { [SerializeField] private Vector3 position; [SerializeField] private JointPoint jointPoint; [SerializeField] private VirtualPath[] paths; [SerializeField] private Vector3[] walkingStartPositions; [SerializeField] private string label; public void init(Vector3 position, JointPoint jointPoint, string label) { this.position = position; this.jointPoint = jointPoint; this.label = label; this.paths = new VirtualPath[4]; this.walkingStartPositions = new Vector3[4]; } public Vector3 getPosition() { return position; } public string getLabel() { return this.label + " (" + jointPoint.getLabel() + ")"; } public JointPoint getJoint() { return jointPoint; } public void addPath(VirtualPath path, int direction) { if (paths[direction] == null) paths[direction] = path; } public VirtualPath getPath(int direction) { return paths[direction]; } public void setWalkingStartPosition(int curveIndex, Vector3 position) { this.walkingStartPositions[curveIndex] = position; } public Vector3 getWalkingStartPosition(int curveIndex) { return this.walkingStartPositions[curveIndex]; } } <file_sep>/Assets/Editor/PathGeneratorWindow.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; /* * This class draws the gui of the path generator window. * */ [System.Serializable] public class PathGeneratorWindow : EditorWindow { private RedirectionDataStructure data; private float gain = 2; private Vector3 jointAPosition = new Vector3(0.55f, 0, -1.25f); private Vector3 jointBPosition = new Vector3(0.55f, 0, 1.25f); private Vector3 jointCPosition = new Vector3(-1.615f, 0, 0); private int intersectionIndex = 0; private string[] curveOptions = new string[] { "" }; private int curveIndex = 0; private int joint = 0; private bool showCurves = true; private bool showJoints = true; private bool showPaths = true; private bool showIntersections = true; private bool hideJointsGui = false; private bool generateAutomatically = false; private Vector2 scrollPos; private float sideLength = 4; private float safetyDistance = 0.5f; private float walkingZoneRadius = 0.25f; [MenuItem("Window/Path Generator")] public static void ShowWindow() { EditorWindow.GetWindow(typeof(PathGeneratorWindow)); } /* * Load (or create if it does not exist) the data structure object. * Load all the gui specific variables saved to editorprefs. * */ private void OnEnable() { data = (RedirectionDataStructure)AssetDatabase.LoadAssetAtPath(@"Assets/Resources/data.asset", typeof(RedirectionDataStructure)); gain = EditorPrefs.GetFloat("gain", gain); sideLength = EditorPrefs.GetFloat("sideLength", sideLength); safetyDistance = EditorPrefs.GetFloat("safetyDistance", safetyDistance); walkingZoneRadius = EditorPrefs.GetFloat("walkingRadius", walkingZoneRadius); intersectionIndex = EditorPrefs.GetInt("intersectionIndex", intersectionIndex); curveIndex = EditorPrefs.GetInt("curveIndex", curveIndex); joint = EditorPrefs.GetInt("joint", joint); showCurves = EditorPrefs.GetBool("showCurves", showCurves); showJoints = EditorPrefs.GetBool("showJoints", showJoints); showPaths = EditorPrefs.GetBool("showPaths", showPaths); showIntersections = EditorPrefs.GetBool("showIntersections", showIntersections); hideJointsGui = EditorPrefs.GetBool("hideJointsGui", hideJointsGui); generateAutomatically = EditorPrefs.GetBool("generateAutomatically", generateAutomatically); if (data == null) { Debug.Log("Created new data resource"); data = CreateInstance<RedirectionDataStructure>(); if (!AssetDatabase.IsValidFolder("Assets/Resources")) AssetDatabase.CreateFolder("Assets", "Resources"); AssetDatabase.CreateAsset(data, "Assets/Resources/data.asset"); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); gain = 2; sideLength = 4; safetyDistance = 0.5f; walkingZoneRadius = 0.25f; intersectionIndex = 0; curveIndex = 0; joint = 0; showCurves = true; showJoints = true; showPaths = true; showIntersections = true; hideJointsGui = false; generateAutomatically = false; } } /* * Save all the gui specific variables to editorprefs. * */ private void OnDisable() { EditorPrefs.SetFloat("gain", gain); EditorPrefs.SetFloat("sideLength", sideLength); EditorPrefs.SetFloat("safetyDistance", safetyDistance); EditorPrefs.SetFloat("walkingRadius", walkingZoneRadius); EditorPrefs.SetInt("intersectionIndex", intersectionIndex); EditorPrefs.SetInt("curveIndex", curveIndex); EditorPrefs.SetInt("joint", joint); EditorPrefs.SetBool("showCurves", showCurves); EditorPrefs.SetBool("showJoints", showJoints); EditorPrefs.SetBool("showPaths", showPaths); EditorPrefs.SetBool("showIntersections", showIntersections); EditorPrefs.SetBool("hideJointsGui", hideJointsGui); EditorPrefs.SetBool("generateAutomatically", generateAutomatically); } /* * Draws the gui of the editor window. * */ void OnGUI () { scrollPos = EditorGUILayout.BeginScrollView(scrollPos); EditorGUILayout.Space(); EditorGUILayout.LabelField("Data Object", EditorStyles.boldLabel); GUI.enabled = false; data = (RedirectionDataStructure)EditorGUILayout.ObjectField(data, typeof(object), false); GUI.enabled = true; EditorGUILayout.Space(); GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1)); EditorGUILayout.Space(); EditorGUILayout.LabelField("General", EditorStyles.boldLabel); EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); bool oldShowCurves = showCurves; showCurves = EditorGUILayout.ToggleLeft("Show Curves", showCurves); if (oldShowCurves != showCurves) SceneView.RepaintAll(); bool oldShowJoints = showJoints; showJoints = EditorGUILayout.ToggleLeft("Show JointPoints", showJoints); if (oldShowJoints != showJoints) SceneView.RepaintAll(); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); bool oldShowPaths = showPaths; showPaths = EditorGUILayout.ToggleLeft("Show Virtual Paths", showPaths); if (oldShowPaths != showPaths) SceneView.RepaintAll(); bool oldShowIntersections = showIntersections; showIntersections = EditorGUILayout.ToggleLeft("Show Virtual Intersections", showIntersections); if (oldShowIntersections != showIntersections) SceneView.RepaintAll(); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); EditorGUILayout.HelpBox("Resetting means removing all joints, curves, intersections, and paths!", MessageType.Warning); if (GUILayout.Button("Reset all", GUILayout.Width(100))) { Debug.Log("Created new data resource"); AssetDatabase.DeleteAsset("Assets/Resources/data.asset"); data = CreateInstance<RedirectionDataStructure>(); if (!AssetDatabase.IsValidFolder("Assets/Resources/")) AssetDatabase.CreateFolder("Assets", "Resources"); AssetDatabase.CreateAsset(data, "Assets/Resources/data.asset"); intersectionIndex = 0; curveIndex = 0; hideJointsGui = false; jointAPosition = new Vector3(0.55f, 0, -1.25f); jointBPosition = new Vector3(0.55f, 0, 1.25f); jointCPosition = new Vector3(-1.615f, 0, 0); this.saveChanges(); SceneView.RepaintAll(); } if (hideJointsGui) GUI.enabled = false; EditorGUILayout.Space(); GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1)); EditorGUILayout.Space(); EditorGUILayout.LabelField("Jointpoints", EditorStyles.boldLabel); generateAutomatically = EditorGUILayout.ToggleLeft("Generate jointpoints automatically according to tracking space", generateAutomatically); if (!generateAutomatically) GUI.enabled = false; sideLength = EditorGUILayout.FloatField("Side length", sideLength, GUILayout.Width(200)); safetyDistance = EditorGUILayout.FloatField("Safety distance", safetyDistance, GUILayout.Width(200)); walkingZoneRadius = EditorGUILayout.FloatField("Walking zone radius (at joints)", walkingZoneRadius, GUILayout.Width(200)); GUI.enabled = true; if (generateAutomatically) GUI.enabled = false; jointAPosition = EditorGUILayout.Vector3Field("Joint A", jointAPosition); jointBPosition = EditorGUILayout.Vector3Field("Joint B", jointBPosition); jointCPosition = EditorGUILayout.Vector3Field("Joint C", jointCPosition); GUI.enabled = true; if (hideJointsGui) GUI.enabled = false; if (GUILayout.Button("Create curves", GUILayout.Width(100))) { hideJointsGui = true; if (generateAutomatically) { calculateJointPositions(sideLength, safetyDistance); data.initJointsAndCurves(jointAPosition, jointBPosition, jointCPosition, walkingZoneRadius); } else data.initJointsAndCurves(jointAPosition, jointBPosition, jointCPosition, walkingZoneRadius); this.saveChanges(); } GUI.enabled = true; if (!hideJointsGui) GUI.enabled = false; EditorGUILayout.Space(); GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1)); EditorGUILayout.Space(); EditorGUILayout.LabelField("Start Position", EditorStyles.boldLabel); EditorGUILayout.HelpBox("Choosing a new start joint, removes all existing intersections and paths!", MessageType.Warning); joint = EditorGUILayout.Popup("Start Joint", joint, new string[] { "A", "B", "C" }, GUILayout.Width(300)); if (GUILayout.Button("Set start joint", GUILayout.Width(100))) { if (joint == 0) data.setStartPosition(data.jointPointA); if (joint == 1) data.setStartPosition(data.jointPointB); if (joint == 2) data.setStartPosition(data.jointPointC); intersectionIndex = 0; curveIndex = 0; this.saveChanges(); } if (intersectionIndex >= data.intersections.Count) intersectionIndex = 0; // Show path creation fields only when a start point was chosen if (data.intersections.Count > 0 && intersectionIndex < data.intersections.Count) GUI.enabled = true; else GUI.enabled = false; EditorGUILayout.Space(); GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1)); EditorGUILayout.Space(); EditorGUILayout.LabelField("Virtual Paths", EditorStyles.boldLabel); EditorGUILayout.HelpBox("Active intersection is marked yellow in the scene view.", MessageType.Info); string[] intersectionOptions = new string[data.intersections.Count]; int i = 0; foreach (VirtualIntersection intersection in data.intersections) { intersectionOptions[i] = intersection.getLabel(); i++; } int oldIntersectionIndex = intersectionIndex; intersectionIndex = EditorGUILayout.Popup("Intersection", intersectionIndex, intersectionOptions, GUILayout.Width(400)); if (oldIntersectionIndex != intersectionIndex) { curveIndex = 0; SceneView.RepaintAll(); } curveIndex = EditorGUILayout.Popup("Curve", curveIndex, calculateCurveOptions(intersectionIndex), GUILayout.Width(400)); gain = EditorGUILayout.FloatField("Gain", gain); // TODO: Limit this to detection thresholds! if (curveOptions.Length == 0 || curveOptions[curveIndex] == "") GUI.enabled = false; if (GUILayout.Button("Create Path", GUILayout.Width(100))) { data.createPathAndIntersection(data.intersections[intersectionIndex], this.getCurve(curveIndex, intersectionIndex), gain); curveIndex = 0; this.saveChanges(); this.Repaint(); } GUI.enabled = true; EditorGUILayout.EndScrollView(); } /* * Save changes of the data structure object to disk. * */ private void saveChanges() { EditorUtility.SetDirty(data); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } /* * Calculates joint positions according to the given side length. * Side length should match the size of the tracking space. * Overwrites joint positions from gui field. * */ public void calculateJointPositions(float sideLength, float safetyDistance) { float smallRadius = (Mathf.Sqrt(3) / (Mathf.Sqrt(3) + 1)) * (sideLength / 2f); float largeRadius = 2 * smallRadius; float heightOfTriangle = (largeRadius / 2) * Mathf.Sqrt(3); jointAPosition = new Vector3((sideLength / 2) - smallRadius - safetyDistance, 0, -smallRadius); jointBPosition = new Vector3((sideLength / 2) - smallRadius - safetyDistance, 0, smallRadius); jointCPosition = new Vector3((sideLength / 2) - smallRadius - heightOfTriangle - safetyDistance, 0, 0); } /* * Calculates the available curve options based on the chosen intersection and the already existing paths. * */ private string[] calculateCurveOptions(int index) { if (data.intersections.Count == 0) { curveIndex = 0; return new string[] { "" }; } if (data.intersections[index].getJoint().Equals(data.jointPointA)) { List<string> options = new List<string>(); if (data.intersections[index].getPath(0) == null) options.Add("Curve AB large radius"); if (data.intersections[index].getPath(1) == null) options.Add("Curve AB small radius"); if (data.intersections[index].getPath(2) == null) options.Add("Curve AC small radius"); if (data.intersections[index].getPath(3) == null) options.Add("Curve AC large radius"); curveOptions = options.ToArray(); if (data.intersections[index].getPath(0) == null && data.intersections[index].getPath(1) == null && data.intersections[index].getPath(2) == null && data.intersections[index].getPath(3) == null) curveOptions = new string[4] { "Curve AB small radius", "Curve AB large radius", "Curve AC small radius", "Curve AC large radius" }; } if (data.intersections[index].getJoint().Equals(data.jointPointB)) { List<string> options = new List<string>(); if (data.intersections[index].getPath(0) == null) options.Add("Curve BC large radius"); if (data.intersections[index].getPath(1) == null) options.Add("Curve BC small radius"); if (data.intersections[index].getPath(2) == null) options.Add("Curve AB small radius"); if (data.intersections[index].getPath(3) == null) options.Add("Curve AB large radius"); curveOptions = options.ToArray(); if (data.intersections[index].getPath(0) == null && data.intersections[index].getPath(1) == null && data.intersections[index].getPath(2) == null && data.intersections[index].getPath(3) == null) curveOptions = new string[4] { "Curve AB small radius", "Curve AB large radius", "Curve BC small radius", "Curve BC large radius" }; } if (data.intersections[index].getJoint().Equals(data.jointPointC)) { List<string> options = new List<string>(); if (data.intersections[index].getPath(0) == null) options.Add("Curve AC large radius"); if (data.intersections[index].getPath(1) == null) options.Add("Curve AC small radius"); if (data.intersections[index].getPath(2) == null) options.Add("Curve BC small radius"); if (data.intersections[index].getPath(3) == null) options.Add("Curve BC large radius"); curveOptions = options.ToArray(); if (data.intersections[index].getPath(0) == null && data.intersections[index].getPath(1) == null && data.intersections[index].getPath(2) == null && data.intersections[index].getPath(3) == null) curveOptions = new string[4] { "Curve AC small radius", "Curve AC large radius", "Curve BC small radius", "Curve BC large radius" }; } return curveOptions; } /* * Returns the curve object according to the chosen index. * */ private Curve getCurve(int curveIndex, int intersectionIndex) { string chosenCurveName = curveOptions[curveIndex]; if (chosenCurveName == "Curve AB large radius") return data.curveABlargeRadius; if (chosenCurveName == "Curve AB small radius") return data.curveABsmallRadius; if (chosenCurveName == "Curve AC large radius") return data.curveAClargeRadius; if (chosenCurveName == "Curve AC small radius") return data.curveACsmallRadius; if (chosenCurveName == "Curve BC large radius") return data.curveBClargeRadius; if (chosenCurveName == "Curve BC small radius") return data.curveBCsmallRadius; return data.curveABsmallRadius; } void OnFocus() { // Remove and re-add the listener to make sure there is always one attached SceneView.onSceneGUIDelegate -= this.OnSceneGUI; SceneView.onSceneGUIDelegate += this.OnSceneGUI; } void OnDestroy() { // Remove the listener to stop drawing SceneView.onSceneGUIDelegate -= this.OnSceneGUI; } /* * Draws all joint points, curves, paths, and intersections to the scene view. * */ void OnSceneGUI(SceneView sceneView) { if (data == null) return; if (data.jointPointA == null) return; if (data.jointPointB == null) return; if (data.jointPointC == null) return; GUIStyle style = new GUIStyle(); style.normal.textColor = Color.black; // Real world joint points if (showJoints) { Handles.color = Color.red; Handles.SphereCap(0, data.jointPointA.getPosition(), Quaternion.identity, 0.2f); Handles.Label(data.jointPointA.getPosition(), data.jointPointA.getLabel(), style); Handles.SphereCap(0, data.jointPointA.getWalkingStartPosition(0), Quaternion.identity, 0.1f); Handles.SphereCap(0, data.jointPointA.getWalkingStartPosition(1), Quaternion.identity, 0.1f); Handles.SphereCap(0, data.jointPointA.getWalkingStartPosition(2), Quaternion.identity, 0.1f); Handles.SphereCap(0, data.jointPointA.getWalkingStartPosition(3), Quaternion.identity, 0.1f); Handles.SphereCap(0, data.jointPointB.getPosition(), Quaternion.identity, 0.2f); Handles.Label(data.jointPointB.getPosition(), data.jointPointB.getLabel(), style); Handles.SphereCap(0, data.jointPointB.getWalkingStartPosition(0), Quaternion.identity, 0.1f); Handles.SphereCap(0, data.jointPointB.getWalkingStartPosition(1), Quaternion.identity, 0.1f); Handles.SphereCap(0, data.jointPointB.getWalkingStartPosition(2), Quaternion.identity, 0.1f); Handles.SphereCap(0, data.jointPointB.getWalkingStartPosition(3), Quaternion.identity, 0.1f); Handles.SphereCap(0, data.jointPointC.getPosition(), Quaternion.identity, 0.2f); Handles.Label(data.jointPointC.getPosition(), data.jointPointC.getLabel(), style); Handles.SphereCap(0, data.jointPointC.getWalkingStartPosition(0), Quaternion.identity, 0.1f); Handles.SphereCap(0, data.jointPointC.getWalkingStartPosition(1), Quaternion.identity, 0.1f); Handles.SphereCap(0, data.jointPointC.getWalkingStartPosition(2), Quaternion.identity, 0.1f); Handles.SphereCap(0, data.jointPointC.getWalkingStartPosition(3), Quaternion.identity, 0.1f); } // Real world curves if (showCurves) { Handles.color = Color.red; Vector3 directionVector = data.jointPointB.getWalkingStartPosition(2) - data.curveABsmallRadius.getCircleCenter(); Handles.DrawWireArc(data.curveABsmallRadius.getCircleCenter(), Vector3.up, directionVector, data.curveABsmallRadius.getAngle(), data.curveABsmallRadius.getRadius()); directionVector = data.jointPointB.getWalkingStartPosition(3) - data.curveABlargeRadius.getCircleCenter(); Handles.DrawWireArc(data.curveABlargeRadius.getCircleCenter(), Vector3.up, directionVector, data.curveABlargeRadius.getAngle(), data.curveABlargeRadius.getRadius()); directionVector = data.jointPointC.getWalkingStartPosition(2) - data.curveBCsmallRadius.getCircleCenter(); Handles.DrawWireArc(data.curveBCsmallRadius.getCircleCenter(), Vector3.up, directionVector, data.curveBCsmallRadius.getAngle(), data.curveBCsmallRadius.getRadius()); directionVector = data.jointPointC.getWalkingStartPosition(3) - data.curveBClargeRadius.getCircleCenter(); Handles.DrawWireArc(data.curveBClargeRadius.getCircleCenter(), Vector3.up, directionVector, data.curveBClargeRadius.getAngle(), data.curveBClargeRadius.getRadius()); directionVector = data.jointPointA.getWalkingStartPosition(2) - data.curveACsmallRadius.getCircleCenter(); Handles.DrawWireArc(data.curveACsmallRadius.getCircleCenter(), Vector3.up, directionVector, data.curveACsmallRadius.getAngle(), data.curveACsmallRadius.getRadius()); directionVector = data.jointPointA.getWalkingStartPosition(3) - data.curveAClargeRadius.getCircleCenter(); Handles.DrawWireArc(data.curveAClargeRadius.getCircleCenter(), Vector3.up, directionVector, data.curveAClargeRadius.getAngle(), data.curveAClargeRadius.getRadius()); } // Virtual world intersections if (showIntersections) { Handles.color = Color.green; foreach (VirtualIntersection intersection in data.intersections) { // Change color for currently chosen intersection if (intersection.Equals(data.intersections[intersectionIndex])) Handles.color = Color.yellow; else Handles.color = Color.green; Handles.SphereCap(0, intersection.getPosition(), Quaternion.identity, 0.2f); Handles.Label(intersection.getPosition(), intersection.getLabel(), style); Handles.SphereCap(0, intersection.getWalkingStartPosition(0), Quaternion.identity, 0.1f); Handles.SphereCap(0, intersection.getWalkingStartPosition(1), Quaternion.identity, 0.1f); Handles.SphereCap(0, intersection.getWalkingStartPosition(2), Quaternion.identity, 0.1f); Handles.SphereCap(0, intersection.getWalkingStartPosition(3), Quaternion.identity, 0.1f); } } // Virtual world paths if (showPaths) { foreach (VirtualPath path in data.paths) { int sign = data.getSignOfCurve(path.getEndPoints()[0].getJoint(), path.getEndPoints()[1].getJoint()); int pathIndex = data.getPathIndex(path.getEndPoints()[0].getJoint(), path.getCurve()); Handles.color = Color.green; Vector3 directionVector = path.getEndPoints()[0].getWalkingStartPosition(pathIndex) - path.getCircleCenter(); Handles.DrawWireArc(path.getCircleCenter(), Vector3.up, directionVector, sign * path.getAngle(), path.getRadius()); } } Handles.BeginGUI(); // GUI stuff comes here Handles.EndGUI(); } } <file_sep>/Assets/_scripts/JointPoint.cs using System.Collections; using System.Collections.Generic; using UnityEngine; /* * A jointpoint is the (real world) crossing of several curves. * There are only three jointpoints in total. * */ [System.Serializable] public class JointPoint : ScriptableObject { [SerializeField] private Vector3 position; [SerializeField] private Vector3[] walkingStartPositions; [SerializeField] private string label; [SerializeField] private float walkingZoneRadius; public void init(Vector3 position, string label, float walkingZoneRadius) { this.position = position; this.label = label; this.walkingZoneRadius = walkingZoneRadius; this.walkingStartPositions = new Vector3[4]; } public Vector3 getPosition() { return position; } public string getLabel() { return label; } public float getWalkingZoneRadius() { return walkingZoneRadius; } public void setWalkingStartPosition(int curveIndex, Vector3 position) { this.walkingStartPositions[curveIndex] = position; } public Vector3 getWalkingStartPosition(int curveIndex) { return this.walkingStartPositions[curveIndex]; } } <file_sep>/Assets/_scripts/Redirection.cs using System.Collections; using System.Collections.Generic; using UnityEngine; /* * This class handles the redirection. * It chooses the current path and curve itself according to the position of the user. * */ public class Redirection : MonoBehaviour { public Transform orientationOffset; public Transform positionOffset; public RedirectionDataStructure data; private string pathLayoutAsset = "data"; private JointPoint currentJoint; private VirtualIntersection currentIntersection; private Curve currentCurve; private VirtualPath currentPath; public bool ready = false; private bool redirectionStarted = false; private int redirectionDirection = 0; private float angleWalkedOnRealCircle = 0; private float angleWalkedOnVirtualCircle = 0; private float oldRotation = 0; void Start() { Debug.Log("Application started"); if (data == null) this.loadPathLayout (pathLayoutAsset); else { currentIntersection = data.intersections [0]; currentJoint = currentIntersection.getJoint (); } } /* * Loads path layout asset with the specified name from a resources folder. * */ public void loadPathLayout(string layoutName) { pathLayoutAsset = layoutName; // Load data structure object (created by tool) from disk data = (RedirectionDataStructure)Resources.LoadAll(pathLayoutAsset)[0] as RedirectionDataStructure; if (data != null) { //Debug.Log("Label: " + data.jointPointA.getLabel()); currentIntersection = data.intersections[0]; currentJoint = currentIntersection.getJoint(); } else Debug.Log("Data is null"); } /* * Starts, stops, and executes the redirection. * In the beginning, "ready" button has to be pressed. Then, the user can start walking and * the redirection will be started and stopped automatically when crossing the intersections. * * "Ready" button -> startRedirection -> stopRedirection * */ void Update () { if (redirectionStarted) { doRedirection(); // if user reaches one of the endpoints of current path // stop redirection // Is user stopping at end intersection? if (isPathLeft(currentPath.getOtherIntersection(currentIntersection))) stopRedirection(currentPath.getOtherIntersection(currentIntersection), true); // Is user stopping at start intersection? else if (isPathLeft(currentIntersection)) stopRedirection(currentIntersection, false); } else if(ready) { // if user crosses boundary to one of the paths // start redirection if (currentIntersection.getPath(0) != null) { if (isPathChosen(currentIntersection.getPath(0))) startRedirection(currentIntersection.getPath(0)); } if (currentIntersection.getPath(1) != null) { if (isPathChosen(currentIntersection.getPath(1))) startRedirection(currentIntersection.getPath(1)); } if (currentIntersection.getPath(2) != null) { if (isPathChosen(currentIntersection.getPath(2))) startRedirection(currentIntersection.getPath(2)); } if (currentIntersection.getPath(3) != null) { if (isPathChosen(currentIntersection.getPath(3))) startRedirection(currentIntersection.getPath(3)); } } } /* * Checks if user reached an intersection. * */ private bool isPathLeft(VirtualIntersection intersection) { int direction = getRedirectionDirection(intersection.getJoint(), currentPath.getCurve()); int pathIndex = data.getPathIndex(intersection.getJoint(), currentPath.getCurve()); Vector3 directionToPathCircleCenter = (currentPath.getCurve().getCircleCenter() - intersection.getJoint().getWalkingStartPosition(pathIndex)).normalized; Vector3 rotatedDirectionVector = Quaternion.AngleAxis(-direction * 90f, Vector3.up) * directionToPathCircleCenter; Plane plane = new Plane(rotatedDirectionVector.normalized, intersection.getJoint().getWalkingStartPosition(pathIndex)); if (plane.GetSide(Camera.main.transform.localPosition)) return false; return true; } /* * Checks if user choosed to walk on the specified path. * */ private bool isPathChosen(VirtualPath path) { int direction = getRedirectionDirection(currentJoint, path.getCurve()); int pathIndex = data.getPathIndex(currentJoint, path.getCurve()); Vector3 directionToCurveCircleCenter = (path.getCurve().getCircleCenter() - currentJoint.getWalkingStartPosition(pathIndex)).normalized; Vector3 rotatedDirectionVector = Quaternion.AngleAxis(-direction * 90f, Vector3.up) * directionToCurveCircleCenter; Plane plane = new Plane(rotatedDirectionVector.normalized, currentJoint.getWalkingStartPosition(pathIndex)); if (plane.GetSide(Camera.main.transform.localPosition)) return true; return false; } /* * Starts redirection on the specified path. * Sets current path and current curve as well as the redirection direction. * */ private void startRedirection(VirtualPath path) { currentCurve = path.getCurve(); currentPath = path; redirectionDirection = this.getRedirectionDirection(currentJoint, currentCurve); redirectionStarted = true; Debug.Log("Redirection started with target: " + currentPath.getOtherIntersection(currentIntersection).getLabel()); } /* * Returns the direction (left or right) to that the current path is bent. * -1 is left, 1 is right. * */ private int getRedirectionDirection(JointPoint joint, Curve curve) { if (joint.Equals(data.jointPointA)) { JointPoint endJoint = curve.getOtherJointPoint(joint); if (endJoint.Equals(data.jointPointB)) return -1; if (endJoint.Equals(data.jointPointC)) return 1; } if (joint.Equals(data.jointPointB)) { JointPoint endJoint = curve.getOtherJointPoint(joint); if (endJoint.Equals(data.jointPointA)) return 1; if (endJoint.Equals(data.jointPointC)) return -1; } if (joint.Equals(data.jointPointC)) { JointPoint endJoint = curve.getOtherJointPoint(joint); if (endJoint.Equals(data.jointPointB)) return 1; if (endJoint.Equals(data.jointPointA)) return -1; } return 0; } /* * Executes the redirection according to the chosen curve and path by * calculating a position and orientation for the virtual camera. * */ private void doRedirection() { // Set offset transforms (virtual position/orientation is set to zero) orientationOffset.localRotation = Quaternion.Inverse(UnityEngine.VR.InputTracking.GetLocalRotation(UnityEngine.VR.VRNode.Head)); positionOffset.localPosition = -UnityEngine.VR.InputTracking.GetLocalPosition(UnityEngine.VR.VRNode.Head); // Get current position and rotation (data from tracking system) Vector2 realWorldCurrentPosition = switchDimensions(Camera.main.transform.localPosition); Quaternion realWorldCurrentRotation = Camera.main.transform.localRotation; //Debug.Log("Current: " + realWorldCurrentPosition); int pathIndex = data.getPathIndex(currentJoint, currentCurve); // Calculate distance between real world current position and real world circle center point float distance = Vector2.Distance(realWorldCurrentPosition, switchDimensions(currentCurve.getCircleCenter())); //Debug.Log("Distance: " + distance); // Calculate angle between start and current position //float angleWalkedOnRealCircle = Vector2.Angle(switchDimensions(switchDimensions(currentJoint.getPosition() + redirectionDirection*data.calculateOffset(currentJoint.getPosition(), currentCurve.getCircleCenter()) - currentCurve.getCircleCenter())), realWorldCurrentPosition - switchDimensions(currentCurve.getCircleCenter())); Vector3 realWalkingStartPosition = currentJoint.getWalkingStartPosition(pathIndex); angleWalkedOnRealCircle = Mathf.Acos((Vector2.Dot((switchDimensions(currentCurve.getCircleCenter()) - switchDimensions(realWalkingStartPosition)), (switchDimensions(currentCurve.getCircleCenter()) - realWorldCurrentPosition))) / ((switchDimensions(currentCurve.getCircleCenter()) - switchDimensions(realWalkingStartPosition)).magnitude * (switchDimensions(currentCurve.getCircleCenter()) - realWorldCurrentPosition).magnitude)); //Debug.Log("angleWalkedOnRealCircle: " + angleWalkedOnRealCircle); // Multiply angle and radius = walked distance float walkedDistance = angleWalkedOnRealCircle * currentCurve.getRadius(); //Debug.Log("Walked: " + walkedDistance); // Calculate side drift: d-r float sideDrift = distance - currentCurve.getRadius(); //Debug.Log("Side: " + sideDrift); // Calculate angle on virtual circle angleWalkedOnVirtualCircle = walkedDistance / currentPath.getRadius(); //Debug.Log("angleWalkedOnVirtualCircle: " + angleWalkedOnVirtualCircle); // Calculate direction from virtual circle center to intersection // - redirectionDirection*data.calculateOffset(currentIntersection.getPosition(), currentPath.getCircleCenter()) Vector3 virtualWalkingStartPosition = currentIntersection.getWalkingStartPosition(pathIndex); Vector2 directionToIntersection = switchDimensions(virtualWalkingStartPosition - currentPath.getCircleCenter()).normalized; //Debug.Log("directionToIntersection: " + directionToIntersection); // Calculate direction to virtual position by rotating direction by angle walked Vector3 directionToVirtualPosition = Quaternion.AngleAxis(redirectionDirection * angleWalkedOnVirtualCircle * Mathf.Rad2Deg, Vector3.up) * new Vector3(directionToIntersection.x, 0, directionToIntersection.y); // Multiply direction by radius + side drift directionToVirtualPosition = directionToVirtualPosition * (currentPath.getRadius() + sideDrift); //Debug.Log("virtualPosition: " + virtualPosition); // Calculate and set virtual position this.transform.position = new Vector3(currentPath.getCircleCenter().x + directionToVirtualPosition.x, Camera.main.transform.localPosition.y, currentPath.getCircleCenter().z + directionToVirtualPosition.z); //Debug.Log(this.transform.position); // Calculate and set virtual rotation: redirection + current camera rotation + old rotation float redirection = Mathf.Rad2Deg * -redirectionDirection * (angleWalkedOnRealCircle - angleWalkedOnVirtualCircle); float y = redirection + realWorldCurrentRotation.eulerAngles.y + oldRotation; Quaternion virtualRotation = Quaternion.Euler(realWorldCurrentRotation.eulerAngles.x, y, realWorldCurrentRotation.eulerAngles.z); this.transform.rotation = virtualRotation; } /* * Stops the redirection at the given intersection. * Sets current intersection and current joint to the next point. * If this intersection is not the same intersection the user started, the rotation angle is added (bool addAngle). * */ private void stopRedirection(VirtualIntersection intersection, bool addAngle) { currentIntersection = intersection; currentJoint = currentIntersection.getJoint(); if (addAngle) oldRotation += Mathf.Rad2Deg * -redirectionDirection * (angleWalkedOnRealCircle - angleWalkedOnVirtualCircle);//(Mathf.Abs(currentCurve.getAngle()) - Mathf.Abs(currentPath.getAngle())) * -redirectionDirection; redirectionStarted = false; Debug.Log("Redirection stopped at joint: " + currentJoint.getLabel() + ", intersection: " + currentIntersection.getLabel() + " (old rotation: " + oldRotation + ")"); } /* * Switches a 3-dimensional vector to a 2-dimensional vector by removing the y coordinate. * */ private Vector2 switchDimensions(Vector3 vector) { return new Vector2(vector.x, vector.z); } } <file_sep>/Assets/_scripts/VirtualPath.cs using System.Collections; using System.Collections.Generic; using UnityEngine; /* * A path is the (virtual world) connection between two intersections. * Each path has one curve as a real world counterpart. * */ [System.Serializable] public class VirtualPath : ScriptableObject { [SerializeField] private Vector3 circleCenter; [SerializeField] private float angle; [SerializeField] private float radius; [SerializeField] private float gain; [SerializeField] private List<VirtualIntersection> endPoints; [SerializeField] private Curve curve; public void init (Vector3 circleCenter, float gain, Curve curve, List<VirtualIntersection> endPoints, float radius, float angle) { this.circleCenter = circleCenter; this.gain = gain; this.radius = radius; this.curve = curve; this.endPoints = endPoints; this.angle = angle; } public Vector3 getCircleCenter() { return circleCenter; } public float getRadius() { return radius; } public float getAngle() { return angle; } public List<VirtualIntersection> getEndPoints() { return endPoints; } public VirtualIntersection getOtherIntersection(VirtualIntersection intersection) { if (intersection.Equals(endPoints[0])) return endPoints[1]; return endPoints[0]; } public Curve getCurve() { return curve; } } <file_sep>/Assets/_scripts/Curve.cs using System.Collections; using System.Collections.Generic; using UnityEngine; /* * A curve is the (real world) connection between two jointpoints. * There are only six curves in total. * */ [System.Serializable] public class Curve : ScriptableObject { [SerializeField] private Vector3 circleCenter; [SerializeField] private float angle; [SerializeField] private float radius; [SerializeField] private List<JointPoint> endPoints; public void init(Vector3 circleCenter, float radius, List<JointPoint> endPoints, bool isSmallCurve) { this.circleCenter = circleCenter; this.radius = radius; this.endPoints = endPoints; this.angle = calculateAngle(isSmallCurve); } private float calculateAngle(bool isSmallCurve) { Vector3[] walkingStartPositions = new Vector3[2]; // Calculate angle for walking zone float angle = Mathf.Rad2Deg * (endPoints[0].getWalkingZoneRadius() / radius); // Calculate direction vectors to walking start positions Vector3 directionToStartJoint = (endPoints[0].getPosition() - circleCenter).normalized; Vector3 rotatedDirectionToStartJoint = Quaternion.AngleAxis(-angle, Vector3.up) * directionToStartJoint; Vector3 directionToEndJoint = (endPoints[1].getPosition() - circleCenter).normalized; Vector3 rotatedDirectionToEndJoint = Quaternion.AngleAxis(angle, Vector3.up) * directionToEndJoint; // Set walking start positions walkingStartPositions[0] = circleCenter + rotatedDirectionToStartJoint * radius; walkingStartPositions[1] = circleCenter + rotatedDirectionToEndJoint * radius; if (isSmallCurve) { endPoints[0].setWalkingStartPosition(1, walkingStartPositions[0]); endPoints[1].setWalkingStartPosition(2, walkingStartPositions[1]); } else { endPoints[0].setWalkingStartPosition(0, walkingStartPositions[0]); endPoints[1].setWalkingStartPosition(3, walkingStartPositions[1]); } // Finally, calculate angle of curve Vector3 directionVector1 = walkingStartPositions[0] - circleCenter; Vector3 directionVector2 = walkingStartPositions[1] - circleCenter; return Vector3.Angle(directionVector1, directionVector2); } public Vector3 getCircleCenter() { return circleCenter; } public float getRadius() { return radius; } public float getAngle() { return angle; } public List<JointPoint> getEndPoints() { return endPoints; } public JointPoint getOtherJointPoint(JointPoint joint) { if (joint.Equals(endPoints[0])) return endPoints[1]; return endPoints[0]; } } <file_sep>/README.md # RDW_CurvedPathConfigurator This is a small tool that helps you to create virtual path layouts for curve-based redirected walking in virtual reality inside the unity3d editor. It is created by <NAME> from the human-computer interaction group of Hamburg University and published under the MIT license. http://hci.informatik.uni-hamburg.de/ For informations about setup and usage pleae have a look into the wiki at the github page. https://github.com/klngbhn/RDW_Demo <file_sep>/Assets/_scripts/RedirectionDataStructure.cs using System.Collections; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; #endif using UnityEngine; /* * This class keeps all the data that is necessary for the redirection. * Hence, it holds all jointpoints, curves, intersections, and paths. * Offers also methods to create and generate these data. * */ [CreateAssetMenu(fileName = "RedirectionPathLayout", menuName = "Redirection/PathLayout", order = 1)] [System.Serializable] public class RedirectionDataStructure : ScriptableObject { public string objectName = "RedirectionPathLayout"; public JointPoint jointPointA; public JointPoint jointPointB; public JointPoint jointPointC; public JointPoint startJoint; public Curve curveABsmallRadius; public Curve curveACsmallRadius; public Curve curveBCsmallRadius; public Curve curveABlargeRadius; public Curve curveAClargeRadius; public Curve curveBClargeRadius; public List<VirtualIntersection> intersections; public List<VirtualPath> paths; public void OnEnable() { if (intersections == null) intersections = new List<VirtualIntersection>(); if (paths == null) paths = new List<VirtualPath>(); if (jointPointA == null) { intersections = new List<VirtualIntersection>(); paths = new List<VirtualPath>(); } } /* * Initializes jointpoints and curves by using the defined positions. In the future * it might be comfortable to automatically generate the positions by using the size of the * tracking space. * */ public void initJointsAndCurves(Vector3 jointAPosition, Vector3 jointBPosition, Vector3 jointCPosition, float walkingZoneRadius) { // Set three joint points (real world) jointPointA = CreateInstance<JointPoint>(); jointPointA.init(jointAPosition, "A", walkingZoneRadius); jointPointB = CreateInstance<JointPoint>(); jointPointB.init(jointBPosition, "B", walkingZoneRadius); jointPointC = CreateInstance<JointPoint>(); jointPointC.init(jointCPosition, "C", walkingZoneRadius); #if UNITY_EDITOR AssetDatabase.AddObjectToAsset(jointPointA, this); AssetDatabase.AddObjectToAsset(jointPointB, this); AssetDatabase.AddObjectToAsset(jointPointC, this); EditorUtility.SetDirty(this); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); #endif // Specify curves with small radii (real world) curveABsmallRadius = createSmallCurve(jointPointA, jointPointB); curveACsmallRadius = createSmallCurve(jointPointC, jointPointA); curveBCsmallRadius = createSmallCurve(jointPointB, jointPointC); // Specify curves with large radii (real world) curveABlargeRadius = createLargeCurve(jointPointA, jointPointB, jointPointC); curveAClargeRadius = createLargeCurve(jointPointC, jointPointA, jointPointB); curveBClargeRadius = createLargeCurve(jointPointB, jointPointC, jointPointA); #if UNITY_EDITOR SceneView.RepaintAll(); #endif Debug.Log("Initialized joints and curves"); } /* * Creates a curve from joint1 to joint2 with the center between both points (plus offset for real walking area at joint point). * */ private Curve createSmallCurve(JointPoint joint1, JointPoint joint2) { Vector3 circleCenter = Vector3.Lerp(joint1.getPosition(), joint2.getPosition(), 0.5f); float radius = 0.5f * Vector3.Magnitude(joint1.getPosition() - joint2.getPosition()); List<JointPoint> endPoints = new List<JointPoint>(); endPoints.Add(joint1); endPoints.Add(joint2); Curve curve = CreateInstance<Curve>(); curve.init(circleCenter, radius, endPoints, true); #if UNITY_EDITOR AssetDatabase.AddObjectToAsset(curve, this); EditorUtility.SetDirty(this); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); #endif return curve; } /* * Creates a curve from joint1 to joint2 with the center at joint3. * */ private Curve createLargeCurve(JointPoint joint1, JointPoint joint2, JointPoint joint3) { Vector3 circleCenter = joint3.getPosition(); float radius = Vector3.Magnitude(joint1.getPosition() - joint2.getPosition()); List<JointPoint> endPoints = new List<JointPoint>(); endPoints.Add(joint1); endPoints.Add(joint2); Curve curve = CreateInstance<Curve>(); curve.init(circleCenter, radius, endPoints, false); #if UNITY_EDITOR AssetDatabase.AddObjectToAsset(curve, this); EditorUtility.SetDirty(this); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); #endif return curve; } /* * Creates a new path and the corresponding intersection at the end. * */ public void createPathAndIntersection(VirtualIntersection startIntersection, Curve curve, float gain) { // Calculate radius of virtual path float radius = curve.getRadius() * gain; // Calculate length of curve float length = Mathf.Deg2Rad * curve.getAngle() * curve.getRadius(); // Calculate angle of virtual path float angle = Mathf.Rad2Deg * (length / radius); int newPathIndex = this.getPathIndex(startIntersection.getJoint(), curve); // Calculate end joint point JointPoint endJointPoint = getCorrespondingEndJointPoint(startIntersection, curve); // Calculate the circle center of the new path Vector3 circleCenter = calculateCircleCenterOfPath(startIntersection, curve, radius); // Calculate (nomralized) direction vector from circle center to start intersection Vector3 directionToStartPath = (startIntersection.getWalkingStartPosition(newPathIndex) - circleCenter).normalized; // Calculate direction vector from circle center to end intersection by: // 1. rotating the direction vector to start intersection (around angle of path and angle of walking zone) // 2. extending the vector by the virtual radius float angleOfWalkingZone = Mathf.Rad2Deg * startIntersection.getJoint().getWalkingZoneRadius() / radius; Vector3 directionToEndPath = Quaternion.AngleAxis(this.getSignOfCurve(startIntersection.getJoint(), endJointPoint) * angle, Vector3.up) * directionToStartPath; directionToEndPath = directionToEndPath * radius; Vector3 directionToEndIntersection = Quaternion.AngleAxis(this.getSignOfCurve(startIntersection.getJoint(), endJointPoint) * angleOfWalkingZone, Vector3.up) * directionToEndPath; // Calculate position of new end intersection Vector3 positionEndIntersection = circleCenter + directionToEndIntersection; VirtualIntersection endIntersection = CreateInstance<VirtualIntersection>(); endIntersection.init(positionEndIntersection, endJointPoint, ""+intersections.Count); List<VirtualIntersection> endPoints = new List<VirtualIntersection>(); endPoints.Add(startIntersection); endPoints.Add(endIntersection); VirtualPath path = CreateInstance<VirtualPath>(); path.init(circleCenter, gain, curve, endPoints, radius, angle); intersections.Add(endIntersection); paths.Add(path); startIntersection.addPath(path, this.getPathIndex(startIntersection.getJoint(), curve)); endIntersection.addPath(path, this.getPathIndex(endJointPoint, curve)); calculateWalkingStartPositions(this.getPathIndex(endJointPoint, curve), endJointPoint, endIntersection, circleCenter, directionToEndPath); #if UNITY_EDITOR SceneView.RepaintAll(); AssetDatabase.AddObjectToAsset(endIntersection, this); AssetDatabase.AddObjectToAsset(path, this); EditorUtility.SetDirty(this); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); #endif Debug.Log("Created new path and intersection"); } /* * Calculates walking start positions for new intersection * */ private void calculateWalkingStartPositions(int pathIndex, JointPoint endJointPoint, VirtualIntersection endIntersection, Vector3 circleCenter, Vector3 directionToEndPath) { endIntersection.setWalkingStartPosition(pathIndex, circleCenter + directionToEndPath); Vector3 directionToCurve0 = endJointPoint.getWalkingStartPosition(0) - endJointPoint.getPosition(); Vector3 directionToCurve1 = endJointPoint.getWalkingStartPosition(1) - endJointPoint.getPosition(); Vector3 directionToCurve2 = endJointPoint.getWalkingStartPosition(2) - endJointPoint.getPosition(); Vector3 directionToCurve3 = endJointPoint.getWalkingStartPosition(3) - endJointPoint.getPosition(); float angleBetweenCurves01 = angle360(directionToCurve0, directionToCurve1); float angleBetweenCurves02 = angle360(directionToCurve0, directionToCurve2); float angleBetweenCurves03 = angle360(directionToCurve0, directionToCurve3); float angleBetweenCurves12 = angle360(directionToCurve1, directionToCurve2); float angleBetweenCurves13 = angle360(directionToCurve1, directionToCurve3); float angleBetweenCurves10 = angle360(directionToCurve1, directionToCurve0); float angleBetweenCurves23 = angle360(directionToCurve2, directionToCurve3); float angleBetweenCurves20 = angle360(directionToCurve2, directionToCurve0); float angleBetweenCurves21 = angle360(directionToCurve2, directionToCurve1); float angleBetweenCurves30 = angle360(directionToCurve3, directionToCurve0); float angleBetweenCurves31 = angle360(directionToCurve3, directionToCurve1); float angleBetweenCurves32 = angle360(directionToCurve3, directionToCurve2); Vector3 directionToFirstStartPosition = (circleCenter + directionToEndPath) - endIntersection.getPosition(); Vector3 directionToOtherStartPosition = new Vector3(); switch (pathIndex) { case 0: endIntersection.setWalkingStartPosition(0, circleCenter + directionToEndPath); directionToOtherStartPosition = Quaternion.AngleAxis(angleBetweenCurves01, Vector3.up) * directionToFirstStartPosition; endIntersection.setWalkingStartPosition(1, endIntersection.getPosition() + directionToOtherStartPosition); directionToOtherStartPosition = Quaternion.AngleAxis(angleBetweenCurves02, Vector3.up) * directionToFirstStartPosition; endIntersection.setWalkingStartPosition(2, endIntersection.getPosition() + directionToOtherStartPosition); directionToOtherStartPosition = Quaternion.AngleAxis(angleBetweenCurves03, Vector3.up) * directionToFirstStartPosition; endIntersection.setWalkingStartPosition(3, endIntersection.getPosition() + directionToOtherStartPosition); break; case 1: endIntersection.setWalkingStartPosition(1, circleCenter + directionToEndPath); directionToOtherStartPosition = Quaternion.AngleAxis(angleBetweenCurves12, Vector3.up) * directionToFirstStartPosition; endIntersection.setWalkingStartPosition(2, endIntersection.getPosition() + directionToOtherStartPosition); directionToOtherStartPosition = Quaternion.AngleAxis(angleBetweenCurves13, Vector3.up) * directionToFirstStartPosition; endIntersection.setWalkingStartPosition(3, endIntersection.getPosition() + directionToOtherStartPosition); directionToOtherStartPosition = Quaternion.AngleAxis(angleBetweenCurves10, Vector3.up) * directionToFirstStartPosition; endIntersection.setWalkingStartPosition(0, endIntersection.getPosition() + directionToOtherStartPosition); break; case 2: endIntersection.setWalkingStartPosition(2, circleCenter + directionToEndPath); directionToOtherStartPosition = Quaternion.AngleAxis(angleBetweenCurves23, Vector3.up) * directionToFirstStartPosition; endIntersection.setWalkingStartPosition(3, endIntersection.getPosition() + directionToOtherStartPosition); directionToOtherStartPosition = Quaternion.AngleAxis(angleBetweenCurves20, Vector3.up) * directionToFirstStartPosition; endIntersection.setWalkingStartPosition(0, endIntersection.getPosition() + directionToOtherStartPosition); directionToOtherStartPosition = Quaternion.AngleAxis(angleBetweenCurves21, Vector3.up) * directionToFirstStartPosition; endIntersection.setWalkingStartPosition(1, endIntersection.getPosition() + directionToOtherStartPosition); break; case 3: endIntersection.setWalkingStartPosition(3, circleCenter + directionToEndPath); directionToOtherStartPosition = Quaternion.AngleAxis(angleBetweenCurves30, Vector3.up) * directionToFirstStartPosition; endIntersection.setWalkingStartPosition(0, endIntersection.getPosition() + directionToOtherStartPosition); directionToOtherStartPosition = Quaternion.AngleAxis(angleBetweenCurves31, Vector3.up) * directionToFirstStartPosition; endIntersection.setWalkingStartPosition(1, endIntersection.getPosition() + directionToOtherStartPosition); directionToOtherStartPosition = Quaternion.AngleAxis(angleBetweenCurves32, Vector3.up) * directionToFirstStartPosition; endIntersection.setWalkingStartPosition(2, endIntersection.getPosition() + directionToOtherStartPosition); break; } } /* * Returns the angle between from and to in 360 degrees clockwise. * */ private float angle360(Vector3 from, Vector3 to) { Vector3 right = Vector3.Cross(Vector3.up, from); float angle = Vector3.Angle(from, to); return (Vector3.Angle(right, to) > 90f) ? 360f - angle : angle; } /* * Returns the circle center position of the new path that starts at given intersection and uses given curve and radius. * */ private Vector3 calculateCircleCenterOfPath(VirtualIntersection startIntersection, Curve curve, float radius) { int newPathIndex = this.getPathIndex(startIntersection.getJoint(), curve); Vector3 directionToCurveCircleCenter = (curve.getCircleCenter() - startIntersection.getJoint().getWalkingStartPosition(newPathIndex)).normalized; Vector3 directionToPathCircleCenter = new Vector3(); // Check which paths are connected to the intersection and pick one (first) for calculation. // New path circle center can be calculated by using the direction to the curve circle center and rotating it. for (int i = 0; i < 4; i++) { if (startIntersection.getPath(i) != null) { Vector3 directionToStartWalkingPosOnPath = (startIntersection.getWalkingStartPosition(i) - startIntersection.getPosition()).normalized; Vector3 directionToStartWalkingPosOnCurve = (startIntersection.getJoint().getWalkingStartPosition(i) - startIntersection.getJoint().getPosition()).normalized; float angle = -angle360(directionToStartWalkingPosOnPath, directionToStartWalkingPosOnCurve); directionToPathCircleCenter = Quaternion.AngleAxis(angle, Vector3.up) * directionToCurveCircleCenter; break; } if (i == 3) { // If no case was chosen this is the start joint. Then, // we can use the curve circle center for calculating the path circle center without rotating. directionToPathCircleCenter = directionToCurveCircleCenter; } } Vector3 result = startIntersection.getWalkingStartPosition(newPathIndex) + directionToPathCircleCenter.normalized * radius; return result; } /* * Returns the index at that a curve/path is connected to a joint/intersection. * 0 index is always the curve with large radius to the next joint (e.g. A to B, B to C). * Then index is increasing clockwise. * */ public int getPathIndex(JointPoint joint, Curve curve) { if (joint.Equals(jointPointA)) { if (curve.Equals(curveABsmallRadius)) return 1; if (curve.Equals(curveABlargeRadius)) return 0; if (curve.Equals(curveACsmallRadius)) return 2; if (curve.Equals(curveAClargeRadius)) return 3; } if (joint.Equals(jointPointB)) { if (curve.Equals(curveABsmallRadius)) return 2; if (curve.Equals(curveABlargeRadius)) return 3; if (curve.Equals(curveBCsmallRadius)) return 1; if (curve.Equals(curveBClargeRadius)) return 0; } if (joint.Equals(jointPointC)) { if (curve.Equals(curveBCsmallRadius)) return 2; if (curve.Equals(curveBClargeRadius)) return 3; if (curve.Equals(curveACsmallRadius)) return 1; if (curve.Equals(curveAClargeRadius)) return 0; } return 0; } /* * Returns the sign for the angle (curve to the right 1 or left -1?) * */ public int getSignOfCurve(JointPoint startJointPoint, JointPoint endJointPoint) { if (startJointPoint.Equals(jointPointA)) { if (endJointPoint.Equals(jointPointB)) return -1; if (endJointPoint.Equals(jointPointC)) return 1; } if (startJointPoint.Equals(jointPointB)) { if (endJointPoint.Equals(jointPointA)) return 1; if (endJointPoint.Equals(jointPointC)) return -1; } if (startJointPoint.Equals(jointPointC)) { if (endJointPoint.Equals(jointPointB)) return 1; if (endJointPoint.Equals(jointPointA)) return -1; } return -1; } /* * Returns the joint point that corresponds to the new end intersection that is connected to the given curve and * starts at the given intersection. * */ private JointPoint getCorrespondingEndJointPoint(VirtualIntersection intersection, Curve curve) { if (intersection.getJoint().Equals(jointPointA)) { if (curve.Equals(curveABsmallRadius)) return jointPointB; if (curve.Equals(curveABlargeRadius)) return jointPointB; if (curve.Equals(curveACsmallRadius)) return jointPointC; if (curve.Equals(curveAClargeRadius)) return jointPointC; } if (intersection.getJoint().Equals(jointPointB)) { if (curve.Equals(curveABsmallRadius)) return jointPointA; if (curve.Equals(curveABlargeRadius)) return jointPointA; if (curve.Equals(curveBCsmallRadius)) return jointPointC; if (curve.Equals(curveBClargeRadius)) return jointPointC; } if (intersection.getJoint().Equals(jointPointC)) { if (curve.Equals(curveBCsmallRadius)) return jointPointB; if (curve.Equals(curveBClargeRadius)) return jointPointB; if (curve.Equals(curveACsmallRadius)) return jointPointA; if (curve.Equals(curveAClargeRadius)) return jointPointA; } return jointPointB; } /* * Sets a joint point as the new start position. Removes all saved virtual paths and intersections. * */ public void setStartPosition(JointPoint joint) { startJoint = joint; intersections = new List<VirtualIntersection>(); paths = new List<VirtualPath>(); VirtualIntersection intersection = CreateInstance<VirtualIntersection>(); intersection.init(joint.getPosition(), joint, "" + intersections.Count); intersections.Add(intersection); intersection.setWalkingStartPosition(0, joint.getWalkingStartPosition(0)); intersection.setWalkingStartPosition(1, joint.getWalkingStartPosition(1)); intersection.setWalkingStartPosition(2, joint.getWalkingStartPosition(2)); intersection.setWalkingStartPosition(3, joint.getWalkingStartPosition(3)); #if UNITY_EDITOR SceneView.RepaintAll(); AssetDatabase.AddObjectToAsset(intersection, this); EditorUtility.SetDirty(this); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); #endif Debug.Log("Set new start position"); } }
7d6fce732dc63ea2beda58f65be61b9ac99073f1
[ "Markdown", "C#" ]
8
C#
Glokta0/RDW_CurvedPathConfigurator
bc4c3d5d8e05f8eddee449f78785903782579d19
ea7996fc66428c63a2861b0a30ebd8645192e693
refs/heads/main
<repo_name>soyl3y3nd4/react-redux-initial-template<file_sep>/src/routes/AppRouter.js import React from "react"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import { FirstScreen } from "../pages/FirstScreen"; export const AppRouter = () => { return ( <Router basename='/' > <div> <Switch> <Route exact path="/" component={FirstScreen} /> <Route path="*" component={FirstScreen} /> </Switch> </div> </Router> ) } <file_sep>/src/types/types.js export const types = { test: '[test] this is a test type' }
6e53bd932efd774400a2959c6385687b38f6a4f8
[ "JavaScript" ]
2
JavaScript
soyl3y3nd4/react-redux-initial-template
a34d6fa92c10539952e3fbdd578015d5c0abf48d
10fef4aea7312876f8b616eb3705934c1642c614
refs/heads/master
<repo_name>stolnikov/bracy-cli<file_sep>/src/Commands/BalancedBracesCommand.php <?php namespace BracyCLI\Commands; use Bracy\DTO\Bracy; use Bracy\Exceptions\EmptyContentException; use Bracy\Validators\BalancedValidator; use Bracy\Validators\CharsValidator; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class BalancedBracesCommand extends Command { protected function configure() { $defaultBracy = new Bracy('()'); $defaultCharsValidator = new CharsValidator(); $this ->setName('chkfile') ->setDescription('Checks for balanced brackets in a text file') ->addArgument('fpath', InputArgument::REQUIRED, 'Unix file path') ->addOption( 'opening-char', 'o', InputOption::VALUE_OPTIONAL, 'Opening character', $defaultBracy->getOpeningChar() ) ->addOption( 'closing-char', 'c', InputOption::VALUE_OPTIONAL, 'Closing character', $defaultBracy->getClosingChar() ) ->addOption( 'allowed-chars', 'a', InputOption::VALUE_OPTIONAL, 'String of allowed chars excluding brace characters', $defaultCharsValidator->getAllowedChars() ); } protected function execute(InputInterface $input, OutputInterface $output) { $filePath = $input->getArgument('fpath'); try { if (!file_exists($filePath) || !is_file($filePath)) { throw new EmptyContentException( \sprintf( "The file %s was not found.", $filePath ) ); } } catch (EmptyContentException $e) { $output->writeln( \sprintf("<error>%s</error>", $e->getMessage()) ); exit; } $text = file_get_contents($filePath); $bracyParams = [ $text, $input->getOption('opening-char'), $input->getOption('closing-char') ]; $bracy = new Bracy(...$bracyParams); $charsValidator = new CharsValidator( $input->getOption('allowed-chars') ); $balancedValidator = new BalancedValidator($charsValidator); try { $isValid = $balancedValidator->isValid($bracy); $response = $isValid ? 'balanced' : 'unbalanced'; } catch (EmptyContentException $e) { $output->writeln( \sprintf("<error>%s</error>", $e->getMessage()) ); exit; } catch (\InvalidArgumentException $e) { $output->writeln( \sprintf("<error>%s</error>", $e->getMessage()) ); exit; } catch (\Throwable $e) { $output->writeln( \sprintf("<error>%s</error>", $e->getMessage()) ); exit; } $output->writeln( \sprintf( "<comment>Task completed. Brackets are %s.</comment>", $response ) ); } } <file_sep>/bin/console.php #!/usr/bin/env php <?php require_once __DIR__ . '/../vendor/autoload.php'; use BracyCLI\Commands\BalancedBracesCommand; use Symfony\Component\Console\Application; $app = new Application('Bracy CLI app', '1.0.0'); $app->add(new BalancedBracesCommand()); try { $app->run(); } catch (\Exception $e) { echo sprintf("The app failed to run." . PHP_EOL . "%s", $e->getMessage()); }
9ac4545a79091a73ede373b5b8e72417ee425754
[ "PHP" ]
2
PHP
stolnikov/bracy-cli
1a783d29a58b33039ca78ddd80a31651dce8166c
02c04b3a630244fdba7ab67d06dda2b0c74100a7
refs/heads/master
<repo_name>18295979862/tp5<file_sep>/test.php <?php echo phpinfo(111); ?>
a41d2351b5959ce0136f9b9c1618e759b5ad7dfb
[ "PHP" ]
1
PHP
18295979862/tp5
500cb9213d59be4352b5d442a476530eb97b100a
face7a2fd2cdc4feda7765421dfcc0ff7cc4f920
refs/heads/master
<repo_name>41RDG6BR/lists_and_keys_03<file_sep>/src/List.js import React, { Component} from 'react' class List extends Component { render() { let list = [ { name:"Rodrigo", email:"<EMAIL>" }, { name:"rdg6", email:"<EMAIL>" } ] return ( <div> <table border="1"> <tr> <th>name</th> <th>email</th> </tr> {list.map((item)=>{ return <tr> <td> {item.name} </td> <td> {item.email} </td> </tr> })} </table> </div> ) } } export default List;
8a1073b72fd836720c4badc9786eccf8f9a5b8a9
[ "JavaScript" ]
1
JavaScript
41RDG6BR/lists_and_keys_03
d0a170615a6a061a4771bf7d07339199e52ba3c0
b592befd290d952d6bfe3ec606fbde1559cb66a2
refs/heads/master
<repo_name>janani1sam5/oops<file_sep>/src/com/exercise2/com/Appliances.java package com.exercise2.com; public class Appliances { String name; float unit; double cost; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setUnit(float unit) { this.unit = unit; } public float getUnit(float unit) { return unit; } public void setPrice(double cost) { this.cost = cost; } public double getPrice() { return cost; } } <file_sep>/src/com/exercise1/com/Flower.java /** * */ package com.exercise1.com; /** * @author VedhuSudhu * POJO Class */ public class Flower { String name; double cost; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setPrice(double cost) { this.cost = cost; } public double getPrice() { return cost; } } <file_sep>/src/com/exercise1/com/CalculateClass.java /** * */ package com.exercise1.com; /** * @author VedhuSudhu * */ public class CalculateClass { public static void main(String[] args) { Bouquet bouq = new Bouquet(); Flower flower1 = new Flower(); flower1.setName("Rose"); flower1.setPrice(1); bouq.addFlower(flower1); Flower flower2 = new Flower(); flower2.setName("Jasmine"); flower2.setPrice(2); bouq.addFlower(flower2); Flower flower3 = new Flower(); flower3.setName("Lilly"); flower3.setPrice(3); bouq.addFlower(flower3); double calculatePrice = calculatePrice(bouq); System.out.println("Cost of the Bouquet is ="+calculatePrice); } public static double calculatePrice(Bouquet bouq) { double totalPrice = 0; for(Flower totalFlower: bouq.getFlower()) { totalPrice=totalPrice+totalFlower.getPrice(); } return totalPrice; } }
2333403cc883ddd7601b5c746fb36db8af0a9f16
[ "Java" ]
3
Java
janani1sam5/oops
10707a0180c52decd9a189d25c1fa2eb5b609972
34667ca24ae3a6569c43f401590836edd4fce518
refs/heads/master
<repo_name>mudassir-ahmed3/Dispute-Sorter-game<file_sep>/Dicee Challenge/index.js function getRandomInt(max) { return Math.floor((Math.random() * Math.floor(max))+1);//without this +1 it would be ranging between 0-5 } var randomNumber1 = getRandomInt(6); document.querySelector(".img1").src = "images/dice"+randomNumber1+".png"; var randomNumber2 = getRandomInt(6); document.querySelector(".img2").src = "images/dice"+randomNumber2+".png"; if(randomNumber1>randomNumber2){ document.querySelector("h1").innerHTML = "player1 wins" }else if(randomNumber1==randomNumber2){ document.querySelector("h1").innerHTML = "it's a tie" }else{ document.querySelector("h1").innerHTML = "player2 wins" }
c01894cce010c66a031b076089704e4e124da4f4
[ "JavaScript" ]
1
JavaScript
mudassir-ahmed3/Dispute-Sorter-game
05d200e62c392993a7e78404deb652bf16c9d537
9ee5ff70fc13d7a6f17a31f0b26bf644c95ed639
refs/heads/master
<file_sep>package com.bolasepakmalaysia.bm; import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.app.FragmentManager; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.support.v4.widget.DrawerLayout; public class MainActivity extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks, NewsFragment.OnFragmentInteractionListener, SettingsFragment.OnFragmentInteractionListener, NewsDetailFragment.OnNewsDetailFragmentInteractionListener { /** * Fragment managing the behaviors, interactions and presentation of the navigation drawer. */ private NavigationDrawerFragment mNavigationDrawerFragment; /** * Used to store the last screen title. For use in {@link #restoreActionBar()}. */ private CharSequence mTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer); mTitle = getTitle(); // Set up the drawer. mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); } @Override public void onNavigationDrawerItemSelected(int position) { // update the main content by replacing fragments FragmentManager fragmentManager = getFragmentManager(); // 0: news // 1: tekaskor // 2: shop // 3: settings switch (position) { case 0: /* fragmentManager.beginTransaction() .replace(R.id.container, NewsFragment.newInstance("zz", "zz")) .commit(); */ break; case 1: Uri uriUrl = Uri.parse("http://www.bolasepakmalaysia.com/predictions"); Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl); startActivity(launchBrowser); break; case 2: Uri uribolastore = Uri.parse("http://www.bolastore.com"); Intent launchbolastore = new Intent(Intent.ACTION_VIEW, uribolastore); startActivity(launchbolastore); break; case 3: fragmentManager.beginTransaction() .replace(R.id.container, SettingsFragment.newInstance("zz", "zz")) .commit(); break; } //fragmentManager.beginTransaction() // .replace(R.id.container, NewsFragment.newInstance("zz", "zz")) // .commit(); } public void onSectionAttached(int number) { switch (number) { case 0: mTitle = getString(R.string.title_news); break; case 1: mTitle = getString(R.string.title_tekaskor); break; case 2: mTitle = getString(R.string.title_shop); break; case 3: mTitle = getString(R.string.title_settings); break; } } public void restoreActionBar() { ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(mTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (!mNavigationDrawerFragment.isDrawerOpen()) { // Only show items in the action bar relevant to this screen // if the drawer is not showing. Otherwise, let the drawer // decide what to show in the action bar. getMenuInflater().inflate(R.menu.main, menu); restoreActionBar(); return true; } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onNewsFragmentNewsDetailSelected(int postid) { FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, NewsDetailFragment.newInstance(postid)) .addToBackStack(null) .commit(); } @Override public void onFragmentInteraction(Uri uri) { } } <file_sep>package com.bolasepakmalaysia.bm.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bolasepakmalaysia.bm.R; /** * Created by zul on 06-Mar-15. */ public class NavigationDrawerRecyclerViewAdapter extends RecyclerView.Adapter<NavigationDrawerRecyclerViewAdapter.ViewHolder> { private static final int TYPE_HEADER = 0; private static final int TYPE_ITEM = 1; private String[] mNavTitles; private int[] mIcons; private String name; private int profile; private String email; public NavigationDrawerRecyclerViewAdapter( String[] navTitles, int[] icons, String name, int profile, String email ){ mNavTitles = navTitles; mIcons = icons; this.name = name; this.profile = profile; this.email = email; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if ( viewType == TYPE_ITEM ){ View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.navigationdrawer_itemrow, parent, false); ViewHolder vhItem = new ViewHolder(v, viewType); return vhItem; } else if ( viewType == TYPE_HEADER ) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.navigationdrawer_header, parent, false); ViewHolder vhHeader = new ViewHolder(v, viewType); return vhHeader; } return null; } @Override public void onBindViewHolder(ViewHolder holder, int position) { if (holder.holderid == 1) { holder.textview.setText(mNavTitles[position-1]); holder.imageView.setImageResource(mIcons[position-1]); } else { } } @Override public int getItemCount() { return 0; } public static class ViewHolder extends RecyclerView.ViewHolder { int holderid; TextView textview; ImageView imageView; ImageView ivProfile; TextView tvName; TextView tvEmail; public ViewHolder(View itemView, int viewType) { super(itemView); // set appropriate view if (viewType == TYPE_ITEM) { textview = (TextView) itemView.findViewById(R.id.navigationdrawer_itemrow_rowtext); imageView = (ImageView) itemView.findViewById(R.id.navigationdrawer_itemrow_rowicon); holderid = 1; } else { tvName = (TextView) itemView.findViewById(R.id.navigationdrawer_header_username); tvEmail = (TextView) itemView.findViewById(R.id.navigationdrawer_header_email); ivProfile = (ImageView) itemView.findViewById(R.id.navigationdrawer_header_picture); holderid = 0; } } } } <file_sep>package com.bolasepakmalaysia.bm; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ProgressBar; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.bolasepakmalaysia.bm.adapter.ListViewPostAdapter; import com.bolasepakmalaysia.bm.app.AppController; import com.bolasepakmalaysia.bm.model.ApiPostViewModel; import com.bolasepakmalaysia.bm.util.GsonRequest; import com.bolasepakmalaysia.bm.view.CommentLayout; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * A fragment representing a list of Items. * <p/> * Large screen devices (such as tablets) are supported by replacing the ListView * with a GridView. * <p/> * Activities containing this fragment MUST implement the {@link com.bolasepakmalaysia.bm.NewsFragment.OnFragmentInteractionListener} * interface. */ public class NewsFragment extends android.support.v4.app.Fragment implements AbsListView.OnItemClickListener { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private List<ApiPostViewModel> mPosts; private OnFragmentInteractionListener mListener; /** * The fragment's ListView/GridView. */ private AbsListView mListView; /** * The Adapter which will be used to populate the ListView/GridView with * Views. */ //private ListAdapter mAdapter; private ListViewPostAdapter mAdapter; private ProgressBar mProgressBar; // TODO: Rename and change types of parameters public static NewsFragment newInstance(String param1, String param2) { NewsFragment fragment = new NewsFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public NewsFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } // TODO: Change Adapter to display your content //mAdapter = new ArrayAdapter<DummyContent.DummyItem>(getActivity(), // android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS); this.mPosts = new ArrayList<ApiPostViewModel>(); mAdapter = new ListViewPostAdapter(getActivity(), mPosts); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_news, container, false); // get data // Set the adapter mListView = (AbsListView) view.findViewById(android.R.id.list); ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter); // Set OnItemClickListener so we can be notified on item clicks mListView.setOnItemClickListener(this); mProgressBar = (ProgressBar) view.findViewById(R.id.newsfragment_progressbar); //new GetPostsAsyncTask(progressBar).execute(""); // only do a request if there is no news if ( mPosts.size() == 0 ){ mProgressBar.setVisibility(View.VISIBLE); } // get posts String url = "http://www.bolasepakmalaysia.com/api/posts"; GsonRequest<ApiPostViewModel[]> gNewsReq = new GsonRequest(Request.Method.GET, url, ApiPostViewModel[].class, null, new Response.Listener<ApiPostViewModel[]>(){ @Override public void onResponse(ApiPostViewModel[] response) { for (int i = 0; i < response.length; i++) { mPosts.add(response[i]); } mAdapter = new ListViewPostAdapter(getActivity(), mPosts); mListView.setAdapter(mAdapter); mProgressBar.setVisibility(View.INVISIBLE); } }, new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError error) { } } ); // only do a request if there is no news if ( mPosts.size() == 0 ){ AppController.getInstance().addToRequestQueue(gNewsReq); } return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (null != mListener) { // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected. int postid = mPosts.get(position).getId(); mListener.onNewsFragmentNewsDetailSelected(postid); } } /** * The default content for this Fragment has a TextView that is shown when * the list is empty. If you would like to change the text, call this method * to supply the text it should use. */ public void setEmptyText(CharSequence emptyText) { View emptyView = mListView.getEmptyView(); if (emptyView instanceof TextView) { ((TextView) emptyView).setText(emptyText); } } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onNewsFragmentNewsDetailSelected(int id); } private class GetPostsAsyncTask extends AsyncTask<String, Integer, ApiPostViewModel[]> { //private ProgressDialog progressDialog; private ProgressBar progressBar; public GetPostsAsyncTask(ProgressBar progressBar){ //progressDialog = new ProgressDialog(getActivity()); this.progressBar = progressBar; } @Override protected void onPreExecute(){ // this.progressDialog.setMessage(getString(R.string.news_fragment_getpostsasynctask_gettingnews)); // this.progressDialog.show(); // show progress bar //getActivity().findViewById(R.id.newsfragment_progressbar).setVisibility(View.VISIBLE); progressBar.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(ApiPostViewModel[] vm){ // change mAdapter to show content //mAdapter = new ArrayAdapter<String>(getActivity(), // android.R.layout.simple_list_item_1, android.R.id.text1, vm); for (int i = 0; i < vm.length; i++){ mPosts.add(vm[i]); } mAdapter = new ListViewPostAdapter(getActivity(), mPosts); mListView.setAdapter(mAdapter); //if (this.progressDialog.isShowing()) { // this.progressDialog.hide(); //} // hide progress bar //getActivity().findViewById(R.id.newsfragment_progressbar).setVisibility(View.INVISIBLE); progressBar.setVisibility(View.INVISIBLE); return; } @Override protected ApiPostViewModel[] doInBackground(String... params) { // TODO: might get error ApiPostViewModel[] posts = new ApiPostViewModel[10]; try { URL url = new URL("http://www.bolasepakmalaysia.com/api/posts"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); if (con.getResponseCode() != 200) { throw new RuntimeException("HTTP error code : " + con.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream()))); Gson gson = new Gson(); posts = gson.fromJson(br, ApiPostViewModel[].class); con.disconnect(); } catch (Exception e) { //vm.issuccess = false; } return posts; } } } <file_sep>package com.bolasepakmalaysia.bm; /** * Created by zul on 17-Dec-14. */ public class getauthtokenviewmodel { public String authtoken; public boolean issuccess; public String[] errors; public String username; public String password; } <file_sep>package com.bolasepakmalaysia.bm; import android.accounts.Account; import android.accounts.AccountAuthenticatorActivity; import android.accounts.AccountManager; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import org.apache.http.client.HttpClient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class bmAuthenticatorActivity extends AccountAuthenticatorActivity { // todo: entah cleanup public final static String ARG_ACCOUNT_TYPE = "ACCOUNT_TYPE"; public final static String ARG_AUTH_TYPE = "AUTH_TYPE"; public final static String ARG_ACCOUNT_NAME = "ACCOUNT_NAME"; @Override protected void onCreate(Bundle icicle) { // TODO Auto-generated method stub super.onCreate(icicle); this.setContentView(R.layout.activity_bm_authenticator); } public void onCancelClick(View v) { this.finish(); } public void onSaveClick(View v) { TextView tvUsername; TextView tvPassword; String username; String password; boolean hasErrors = false; tvUsername = (TextView) this.findViewById(R.id.uc_txt_username); tvPassword = (TextView) this.findViewById(R.id.uc_txt_password); tvUsername.setBackgroundColor(Color.WHITE); tvPassword.setBackgroundColor(Color.WHITE); username = tvUsername.getText().toString(); password = tvPassword.getText().toString(); /* if (username.length() < 3) { hasErrors = true; tvUsername.setBackgroundColor(Color.MAGENTA); } if (password.length() < 3) { hasErrors = true; tvPassword.setBackgroundColor(Color.MAGENTA); } if (apiKey.length() < 3) { hasErrors = true; tvApiKey.setBackgroundColor(Color.MAGENTA); } if (hasErrors) { return; } */ // Now that we have done some simple "client side" validation it // is time to check with the server //new GetAuthTokenMiawTask(this).execute(username, password); // ... perform some network activity here try{ getauthtokenviewmodel vm = new GetAuthTokenMiawTask(this).execute(username, password).get(); hasErrors = !(vm.issuccess); } catch (Exception e) { hasErrors = true; } // finished String accountType = bmAuthenticator.ACCOUNT_TYPE; //this.getIntent().getStringExtra(PARAM_AUTHTOKEN_TYPE); if (accountType == null) { accountType = bmAuthenticator.ACCOUNT_TYPE; } AccountManager accMgr = AccountManager.get(getApplicationContext()); if (hasErrors) { // handel errors //tvPassword.setBackgroundColor(Color.BLUE); Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG); } else { // This is the magic that adds the account to the Android Account Manager final Account account = new Account(username, accountType); Boolean rr = accMgr.addAccountExplicitly(account, password, null); // Now we tell our caller, could be the Android Account Manager or even our own application // that the process was successful final Intent intent = new Intent(); intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, username); intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType); intent.putExtra(AccountManager.KEY_AUTHTOKEN, accountType); this.setAccountAuthenticatorResult(intent.getExtras()); if (rr) { this.setResult(RESULT_OK, intent); } else { this.setResult(RESULT_CANCELED, intent); } this.finish(); } } private void createOrDontCreateAccount(getauthtokenviewmodel vm){ Context context = getApplicationContext(); // finished String accountType = bmAuthenticator.ACCOUNT_TYPE; //this.getIntent().getStringExtra(PARAM_AUTHTOKEN_TYPE); AccountManager accMgr = AccountManager.get(getApplicationContext()); // if (vm.issuccess){ // Toast.makeText(context, "OK", Toast.LENGTH_SHORT).show(); // } else { // Toast.makeText(context, "fail", Toast.LENGTH_SHORT).show(); // } if (!vm.issuccess) { // handel errors //tvPassword.setBackgroundColor(Color.BLUE); } else { // This is the magic that adds the account to the Android Account Manager final Account account = new Account(vm.username, accountType); Boolean rr = accMgr.addAccountExplicitly(account, vm.password, null); // Now we tell our caller, could be the Andreoid Account Manager or even our own application // that the process was successful final Intent intent = new Intent(); intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, vm.username); intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType); intent.putExtra(AccountManager.KEY_AUTHTOKEN, accountType); this.setAccountAuthenticatorResult(intent.getExtras()); if (vm.issuccess) { this.setResult(RESULT_OK, intent); } else { this.setResult(RESULT_CANCELED, intent); } this.finish(); } } private class GetAuthTokenMiawTask extends AsyncTask<String, Integer, getauthtokenviewmodel> { private ProgressDialog dialog; private bmAuthenticatorActivity activity; private Context context; public GetAuthTokenMiawTask(bmAuthenticatorActivity activity) { this.activity = activity; context = activity; dialog = new ProgressDialog(getApplicationContext()); } @Override protected void onPreExecute() { //this.dialog.setMessage("Progress start"); //this.dialog.show(); } @Override protected void onPostExecute(getauthtokenviewmodel vm) { //if (dialog.isShowing()) { // dialog.hide(); //} //activity.createOrDontCreateAccount(vm); } @Override protected getauthtokenviewmodel doInBackground(String... strings) { String username = strings[0]; String password = strings[1]; getauthtokenviewmodel vm = new getauthtokenviewmodel(); vm.username = username; vm.password = <PASSWORD>; try { URL url = new URL("http://www.bolasepakmalaysia.com/account/getauthtoken?username=" + username + "&password=" + password); HttpURLConnection con = (HttpURLConnection) url.openConnection(); if (con.getResponseCode() != 200) { throw new RuntimeException("HTTP error code : " + con.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream()))); Gson gson = new Gson(); vm = gson.fromJson(br, getauthtokenviewmodel.class); con.disconnect(); } catch (Exception e) { vm.issuccess = false; } return vm; } } }<file_sep>package com.bolasepakmalaysia.bm.util; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.UnsupportedEncodingException; import java.util.Map; /** * Created by zul on 02-Feb-15. */ public class GsonRequest<T> extends Request<T> { private final Gson gson = new Gson(); private final Class<T> clazz; private final Map<String, String> headers; private final Response.Listener<T> listener; public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers, Response.Listener<T> listener, Response.ErrorListener errorListener) { super(method, url, errorListener); this.clazz = clazz; this.headers = headers; this.listener = listener; } @Override public Map<String, String> getHeaders() throws AuthFailureError { return headers != null ? headers : super.getHeaders(); } @Override protected Response<T> parseNetworkResponse(NetworkResponse response) { try { String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JsonSyntaxException e) { return Response.error(new ParseError(e)); } } @Override protected void deliverResponse(T response) { listener.onResponse(response); } } /* JsonObjectRequest newsReq = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>(){ @Override public void onResponse(JSONObject response) { ApiPostViewModel vm = new ApiPostViewModel(); try { vm.setArticle(response.getString("article")); vm.setId(response.getInt("id")); vm.setImageurl(response.getString("imageurl")); vm.setSummary(response.getString("summary")); vm.setTitle(response.getString("title")); //vm.setComments(); title.setText(vm.getTitle()); body.setText(vm.getArticle()); //img.setImageDrawable(getView().getResources().getDrawable(R.drawable.postimage)); img.setImageUrl("http://www.bolasepakmalaysia.com" + vm.getImageUrl(), AppController.getInstance().getImageLoader()); pb.setVisibility(View.INVISIBLE); } catch(JSONException e) { title.setText("error!"); } } }, new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError error) { } }); */
68fc21673d9053d3577fd61743bcfa7f8967eb01
[ "Java" ]
6
Java
zul200289/BM
d3966792fd14b9ced8bf5ea60ba9d96cad92ee1c
a3f83b2b5b777b25fa138431ce982acd3e3ebfad
refs/heads/master
<file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom_mwi #' Subject: Setup SPAM #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### NOTE ############### # This script below is sourced by all the other scripts in the data repository. # In this way, you only have to set the SPAMc parameters once. # It also ensures that the necessary packages (see below) are loaded. ############### SETUP R ############### # Install and load pacman package that automatically installs R packages if not available if("pacman" %in% rownames(installed.packages()) == FALSE) install.packages("pacman") library(pacman) # Load key packages p_load("mapspam2globiom", "countrycode", "gdalUtils", "here", "glue", "raster", "readxl", "tidyverse", "sf") # !diagnostics off # This switches off most warnings related to "Unknown or uninitialised column: ", which can be safely ignored. # R options options(scipen=999) # Supress scientific notation options(digits=4) # limit display to four digits ############### SETUP SPAMc ############### # Set the folder where the model will be stored # Note that R uses forward slashes even in Windows!! spamc_path <- "C:/Users/dijk158/Dropbox/mapspam2globiom_mwi" # Set SPAMc parameters param <- spam_par(spam_path = spamc_path, iso3c = "MWI", year = 2010, res = "5min", adm_level = 2, solve_level = 0, model = "min_entropy") # Show parameters print(param) # Create SPAMc folder structure in the spamc_path create_spam_folders(param) # clean up rm(spamc_path) <file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom #' Subject: Code to select ESA land cover map per country #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### PROCESS ############### temp_path <- file.path(param$spam_path, glue("processed_data/maps/cropland/{param$res}")) dir.create(temp_path, showWarnings = FALSE, recursive = TRUE) # Set files mask <- file.path(param$spam_path, glue("processed_data/maps/adm/{param$res}/adm_map_{param$year}_{param$iso3c}.shp")) input <- file.path(param$raw_path, glue("esacci/ESACCI-LC-L4-LCCS-Map-300m-P1Y-2010-v2.0.7.tif")) output <- file.path(param$spam_path, glue("processed_data/maps/cropland/{param$res}/esa_raw_{param$year}_{param$iso3c}.tif")) # Warp and mask output_map <- gdalwarp(srcfile = input, dstfile = output, cutline = mask, crop_to_cutline = T, srcnodata = "0", r = "near", verbose = F, output_Raster = T, overwrite = T) plot(output_map) ############### CLEAN UP ############### rm(input, mask, output, output_map, temp_path) <file_sep># mapspam2globiom_mwi This repository contains the scripts to create crop distribution maps for Malawi (MWI). It was prepared to illustrate the [mapspam2globiom](https://iiasa.github.io/mapspam2globiom) package, which must be installed first. See the package documentation for further information on this repository. <file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom_mwi #' Subject: Run model #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### RUN MODEL ############### run_spam(param) ############### COMBINE ADM1 RESULTS ############### combine_results(param) <file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom #' Subject: Code to process urban extent maps #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### LOAD DATA ############### # Adm location adm_map <- readRDS(file.path(param$spam_path, glue("processed_data/maps/adm/{param$res}/adm_map_{param$year}_{param$iso3c}.rds"))) # urban extent, select country grump_raw <- read_sf(file.path(param$raw_path, "grump/global_urban_extent_polygons_v1.01.shp")) ############### PROCESS ############### grump <- grump_raw %>% filter(ISO3 == param$iso3c) plot(adm_map$geometry) plot(grump$geometry, col = "red", add = T) ############### SAVE ############### temp_path <- file.path(param$spam_path, glue("processed_data/maps/population/{param$res}")) dir.create(temp_path, showWarnings = FALSE, recursive = TRUE) saveRDS(grump, file.path(param$spam_path, glue("processed_data/maps/population/{param$res}/urb_{param$year}_{param$iso3c}.rds"))) ############### CLEAN UP ############### rm(adm_map, grump, grump_raw, temp_path) <file_sep>#'======================================================================================================================================== #' Project: mapspam #' Subject: Code to process GMIA #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### LOAD DATA ############### load_data(c("adm_map"), param) # Raw gmia file gmia_raw <- raster(file.path(param$raw_path,"gmia/gmia_v5_aei_ha.asc")) ############### PROCESS ############### # The crs of the gmia (WGS 84) is missing and the file is not in tif. We add and save the map crs(gmia_raw) <- "+proj=longlat +datum=WGS84 +no_defs" if(!file.exists(file.path(param$raw_path, "gmia/gmia_v5_aei_ha_crs.tif"))){ writeRaster(gmia_raw, file.path(param$raw_path, "gmia/gmia_v5_aei_ha_crs.tif"), overwrite = T) } # GMIA presents the area in ha of area equiped for irrigation at 5 arcmin resolution. # Hence, we cannot simply warp to higher resolutions (e.g. 30 arcmin). # We calculate the share of irrigated area first and then warp. # In case the resolution is 5 arcmin, we only clip the map to the country borders if(param$res == "5min") { # Set files grid <- file.path(param$spam_path, glue("processed_data/maps/grid/{param$res}/grid_{param$res}_{param$year}_{param$iso3c}.tif")) mask <- file.path(param$spam_path, glue("processed_data/maps/adm/{param$res}/adm_map_{param$year}_{param$iso3c}.shp")) input <- file.path(param$raw_path, glue("gmia/gmia_v5_aei_ha_crs.tif")) output <- file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}/gmia_temp_{param$res}_{param$year}_{param$iso3c}.tif")) temp_path <- file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}")) dir.create(temp_path, showWarnings = FALSE, recursive = TRUE) # Warp and mask # use r = "near as we warp 5 arcmin to 5 arcmin. Using r = "bilinear" might result in different grid cell values output_map <- align_rasters(unaligned = input, reference = grid, dstfile = output, cutline = mask, crop_to_cutline = F, r = "near", verbose = F, output_Raster = T, overwrite = T) plot(output_map) # Calculate share of irrigated area output_map <- output_map/(area(output_map)*100) plot(output_map) # save writeRaster(output_map, file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}/gmia_{param$res}_{param$year}_{param$iso3c}.tif")) , overwrite = T) } if(param$res == "30sec") { temp_path <- file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}")) dir.create(temp_path, showWarnings = FALSE, recursive = TRUE) # Crop, making sure it also includes grid cells, which center is outside the polygon # by adding snap = "out") gmia_temp <- crop(gmia_raw, adm_map, snap = "out") # Set 0 values to NA gmia_temp <- reclassify(gmia_temp, cbind(0, NA)) # Calculate share of irrigated area gmia_temp <- gmia_temp/(area(gmia_temp)*100) plot(gmia_temp) # Save writeRaster(gmia_temp, file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}/gmia_temp_{param$year}_{param$iso3c}.tif")), overwrite = T) # Set files grid <- file.path(param$spam_path, glue("processed_data/maps/grid/{param$res}/grid_{param$res}_{param$year}_{param$iso3c}.tif")) mask <- file.path(param$spam_path, glue("processed_data/maps/adm/{param$res}/adm_map_{param$year}_{param$iso3c}.shp")) input <- file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}/gmia_temp_{param$year}_{param$iso3c}.tif")) output <- file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}/gmia_{param$res}_{param$year}_{param$iso3c}.tif")) # Warp and mask output_map <- align_rasters(unaligned = input, reference = grid, dstfile = output, cutline = mask, crop_to_cutline = F, r = "bilinear", verbose = F, output_Raster = T, overwrite = T) plot(output_map) } ############### CLEAN UP ############### rm(adm_map, gmia_raw, gmia_temp, output_map) rm(grid, input, mask, output, temp_path) <file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom #' Subject: Script to convert mapspam crop distribution maps to globiom simu input #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### CREATE GLOBIOM INPUT GDX FILES ############### # We use the ESACCI land cover map as land cover base map. # The user can replace this by a country specific product if available. # If so, a new land_cover2globiom land cover class has to be procuced and loaded # that substitues the esacci2globiom mapping. lc_file <- file.path(param$spam_path, glue("processed_data/maps/cropland/{param$res}/esa_raw_{param$year}_{param$iso3c}.tif")) lc_map <- raster(lc_file) plot(lc_map) # Update crop2globiom.csv and map coff to coff (instead of the rest category) and overwrite load_data("crop2globiom", param) crop2globiom <- crop2globiom %>% mutate(globiom_crop = ifelse(crop == "coff", "Coff", globiom_crop)) write_csv(crop2globiom, file.path(param$spam_path, "mappings/crop2globiom.csv")) # Load mapping of lc classes to globiom lc classes lc_class2globiom <- read_csv(file.path(param$spam_path, "mappings/esacci2globiom.csv")) # Aggregate land cover map to GLOBIOM land cover classes at simu level # Not that the area is expressed in 1000 ha, which is common in GLOBIOM! create_globiom_input(lc_class2globiom, lc_map, param) <file_sep>#'======================================================================================================================================== #' Project: crop_map #' Subject: Code to select GAEZ spam 1.0 input maps per country #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ########## LOAD DATA ########## load_data(c("adm_map", "grid", "gaez2crop"), param) # As some gaez maps are not available (see Convert_GAEZ_too_Suit_v4.docx, we need a specific mapping). gaez2crop <- gaez2crop %>% mutate(id = paste(crop, system, sep = "_")) ########## CREATE 5 ARCMIN MAPS FROM RAW GAEZ FOR CROPSUIT ########## # Create file lookup table lookup <- bind_rows( data.frame(files_full = list.files(file.path(param$raw_path, "gaez/cropsuitabilityindexvalue"), pattern = ".tif$", full.names = T), files = list.files(file.path(param$raw_path, "gaez/cropsuitabilityindexvalue"), pattern = ".tif$")) %>% separate(files, into = c("suit_variable", "gaez_crop", "gaez_system", "input"), sep = "_", remove = F) %>% separate(input, into = c("gaez_input", "ext"), sep = "\\.") %>% dplyr::select(-ext), data.frame(files_full = list.files(file.path(param$raw_path, "gaez/cropsuitabilityindexforcurrentcultivatedland"), pattern = ".tif$", full.names = T), files = list.files(file.path(param$raw_path, "gaez/cropsuitabilityindexforcurrentcultivatedland"), pattern = ".tif$")) %>% separate(files, into = c("suit_variable", "gaez_crop", "gaez_system", "input"), sep = "_", remove = F) %>% separate(input, into = c("gaez_input", "ext"), sep = "\\.") %>% dplyr::select(-ext)) %>% left_join(gaez2crop,., by = c("gaez_crop", "gaez_input", "gaez_system", "suit_variable")) ### WARP AND MASK # Set files grid <- file.path(param$spam_path, glue("processed_data/maps/grid/{param$res}/grid_{param$res}_{param$year}_{param$iso3c}.tif")) mask <- file.path(param$spam_path, glue("processed_data/maps/adm/{param$res}/adm_map_{param$year}_{param$iso3c}.shp")) # Function to loop over gaez files, warp and mask clip_gaez <- function(id, var, folder){ cat("\n", id) temp_path <- file.path(param$spam_path, glue("processed_data/maps/{folder}/{param$res}")) dir.create(temp_path, showWarnings = FALSE, recursive = TRUE) input <- lookup$files_full[lookup$id == id] output <- file.path(temp_path, glue("{id}_{var}_{param$res}_{param$year}_{param$iso3c}.tif")) output_map <- align_rasters(unaligned = input, reference = grid, dstfile = output, cutline = mask, crop_to_cutline = F, r = "bilinear", verbose = F, output_Raster = T, overwrite = T) plot(output_map, main = id) } # warp and mask walk(lookup$id, clip_gaez, "bs", "biophysical_suitability") ############### CLEAN UP ############### rm(lookup) ########## CREATE 5 ARCMIN MAPS FROM RAW GAEZ FOR PRODUCTIONCAPACITY ########## # Create file lookup table lookup <- bind_rows( data.frame(files_full = list.files(file.path(param$raw_path, "gaez/totalproductioncapacity"), pattern = ".tif$", full.names = T), files = list.files(file.path(param$raw_path, "gaez/totalproductioncapacity"), pattern = ".tif$")) %>% separate(files, into = c("prod_variable", "gaez_crop", "gaez_system", "input"), sep = "_", remove = F) %>% separate(input, into = c("gaez_input", "ext"), sep = "\\.") %>% dplyr::select(-ext), data.frame(files_full = list.files(file.path(param$raw_path, "gaez/potentialproductioncapacityforcurrentcultivatedland"), pattern = ".tif$", full.names = T), files = list.files(file.path(param$raw_path, "gaez/potentialproductioncapacityforcurrentcultivatedland"), pattern = ".tif$")) %>% separate(files, into = c("prod_variable", "gaez_crop", "gaez_system", "input"), sep = "_", remove = F) %>% separate(input, into = c("gaez_input", "ext"), sep = "\\.") %>% dplyr::select(-ext)) %>% left_join(gaez2crop,., by = c("gaez_crop", "gaez_input", "gaez_system", "prod_variable")) # warp and mask walk(lookup$id, clip_gaez, "py", "potential_yield") ############### CLEAN UP ############### rm(adm_loc, gaez2crop, grid, mask) rm(clip_gaez, gaez2crop, lookup) <file_sep>#'======================================================================================================================================== #' Project: globiom2mapspam #' Subject: Script to process FAOSTAT price data #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### LOAD DATA ############### # Set FAOSTAT versions faostat_crops_version <- "20200303" faostat_prices_version <- "20200303" # Crop production prod_raw <- read_csv(file.path(param$raw_path, glue("faostat/{faostat_crops_version}_faostat_crops.csv"))) # price data price_raw <- read_csv(file.path(param$raw_path, glue("faostat/{faostat_prices_version}_faostat_prices.csv"))) # faostat2crop load_data("faostat2crop", param) faostat2crop <- faostat2crop %>% dplyr::select(crop, faostat_crop_code) %>% na.omit() ############### PROCESS ############### # Clean up FAOSTAT price <- price_raw %>% setNames(tolower(names(.))) %>% filter(element == "Producer Price (USD/tonne)") %>% mutate(iso3c = countrycode(`area code`, "fao", "iso3c")) %>% filter(!is.na(iso3c)) %>% dplyr::select(iso3c, faostat_crop_code = `item code`, year, price = value) area <- prod_raw %>% setNames(tolower(names(.))) %>% filter(element == "Area harvested") %>% mutate(iso3c = countrycode(`area code`, "fao", "iso3c")) %>% filter(!is.na(iso3c)) %>% dplyr::select(iso3c, item, faostat_crop_code = `item code`, year, area = value) # Combine and calculate weighted average price for crop # We take weighted average over five years to reduce fluctuations # We take average for continents because otherwise there are many missing data (e.g. coffee in Southern Africa) price_iso3c <- full_join(price, area) %>% na.omit() %>% left_join(faostat2crop) %>% filter(!is.na(crop)) %>% group_by(iso3c, crop, year) %>% summarize(price = sum(price*area)/sum(area, na.rm = T)) %>% ungroup() %>% filter(year %in% c(param$year-1, param$year, param$year+1)) %>% mutate(continent = countrycode(iso3c, "iso3c", "continent"), region = countrycode(iso3c, "iso3c", "region")) %>% group_by(crop, continent) %>% summarize(price = mean(price, na.rm = T)) %>% ungroup() # Filter out continent prices price_iso3c <- price_iso3c %>% filter(continent == countrycode(param$iso3c, "iso3c", "continent")) %>% dplyr::select(-continent) # Check missing crop_list <- faostat2crop %>% dplyr::select(crop) %>% unique() miss_crop <- full_join(crop_list, price_iso3c) %>% complete(crop) %>% filter(is.na(price)) ########## SAVE ########## write_csv(price_iso3c, file.path(param$spam_path, glue("processed_data/agricultural_statistics/crop_prices_{param$year}_{param$iso3c}.csv"))) ########## CLEAN UP ########## rm(area, crop_list, faostat2crop, miss_crop, price, price_iso3c, price_raw, prod_raw, faostat_crops_version, faostat_prices_version) <file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom #' Subject: Script to process raw subnational statistics #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### LOAD DATA ############### ### LOAD DATA # Original data to SPAMc crop mapping orig2crop <- read_csv(file.path(param$raw_path, "subnational_statistics/spam_stat2crop.csv")) %>% dplyr::select(-crop_full) # raw administrative level statistics stat_raw <- read_csv(file.path(param$raw_path, "subnational_statistics/stat_area_all.csv"), na = c("-999", "")) # raw farming system and crop intensity statistics sy_ci_raw <- read_csv(file.path(param$raw_path, paste0("subnational_statistics/dep_list_all.csv")), na = c("-999", "")) # link table to reaggregate administrative units into those presented in the shapefile link_raw <- read_csv(file.path(param$raw_path, paste0("subnational_statistics/linktable_all.csv")), na = c("-999", "")) ########## PREPARARE STAT ########## #In the case of Malawi we are using raw data #from SPAM2010 (https://www.mapspam.info) as source. Hence there was no need to #collect data and aggregate crops. Alternatively we could have started with a #template file and use R or Excel to aggregate/split the raw statistics so they #fit in the template. # To create the templates use the following commands ha_template <- create_statistics_template("ha", param) fs_template <- create_statistics_template("fs", param) ci_template <- create_statistics_template("ci", param) # Remove columns that are not used stat <- stat_raw %>% gather(crop_stat, value_ha, -stat_code, -prod_level, -name_cntr, -name_admin, -rec_type, -unit, -ar_irr, -ar_tot, -year_data, -source) %>% dplyr::select(-source, -year_data, -stat_code, -name_cntr, -rec_type, -unit, -ar_irr, -ar_tot) # In the Malawi case the raw adm2 statistics are more detailed than the # shapefile with the location of the adm2 units. We use a linktable to aggregate # the statistics so they are comparable with the maps. # Create link table for adm1 link_adm1 <- link_raw %>% dplyr::select(region, prod_level = fips1, o_fips1, o_region) %>% unique() # Reaggregate adm1 adm1_ag <- stat %>% filter(prod_level %in% unique(link_adm1$prod_level)) %>% left_join(link_adm1) %>% group_by(crop_stat, o_region, o_fips1) %>% summarize(value_ha = sum(value_ha, na.rm = F)) %>% rename(name_admin = o_region, prod_level = o_fips1) # Create link table for adm2 link_adm2 <- link_raw %>% dplyr::select(name_admin = admin_name, prod_level = fips2, o_fips2, o_adm_name) %>% unique() # Reaggregate adm2 adm2_ag <- stat %>% filter(prod_level %in% unique(link_adm2$prod_level)) %>% left_join(link_adm2) %>% group_by(crop_stat, o_adm_name, o_fips2) %>% summarize(value_ha = sum(value_ha, na.rm = F)) %>% # rename(name_admin = o_adm_name, prod_level = o_fips2) # Combine adm0, adm1 and adm2 data stat <- bind_rows( stat %>% filter(prod_level == unique(paste0(substring(stat$prod_level, 1, 2), "00"))), adm1_ag, adm2_ag) # Add adm_level using adm codes and iso3c and rename stat <- stat %>% mutate(n_char = nchar(prod_level), iso2 = substring(prod_level, 0, 2), adm_temp = substring(prod_level, 3, n_char), adm_level = ifelse(adm_temp == "00", 0, ifelse(nchar(adm_temp) == "2", 1, 2))) %>% dplyr::select(-adm_temp, -iso2, -n_char) %>% rename(adm_code = prod_level, adm_name = name_admin) # Remove millet and coffee varietes, which are all zero and rename to SPAMc crop names stat <- stat %>% filter(!crop_stat %in% c("pearlmill", "rob_coffee")) %>% mutate(crop_stat = if_else(crop_stat == "smallmill", "millet", crop_stat), crop_stat = if_else(crop_stat == "ara_coffee", "coffee", crop_stat),) # Set adm0_name adm0_code equal to country name and iso3c code stat <- stat %>% mutate(adm_name = if_else(adm_level == 0, param$country, adm_name), adm_code = if_else(adm_level == 0, param$iso3c, adm_code)) # Recode to standard SPAM crops Also aggregate as multiple orig crops could be # linked to one SPAMc crop or crop group (not the case here). # NB: use sum with na.rm = F as we want NA+NA = NA, not NA+NA = 0! stat <- stat %>% left_join(orig2crop) %>% group_by(crop, adm_code, adm_name, adm_level) %>% summarize(value_ha = sum(value_ha, na.rm = F)) %>% ungroup() # Remove Area under National Administration as we also remove the polygon to # ensure no crops will be allocated there stat <- stat %>% filter(!adm_name %in% "Area under National Administration") # Update coff information. Secondary sources indicate coffee is grown in a # selected number of ADM2s. We set these to -999 and let the model decide. We # set ADM1 values informed by a pre SPAMc run where ADM1 values where NA. We # only add this data to be able to run the model at the ADM1 level # (param$solve_level = 1) as for this option data needs to be fully complate at # the ADM1 level. coff_adm <- c("Dedza", "Ntchisi", "Chitipa", "Nkhata Bay", "Rumphi", "Mulanje", "Thyolo", "Zomba") stat <- stat %>% mutate(value_ha = case_when( adm_name %in% coff_adm & crop == "coff" ~ -999, adm_name == "Northern Region" & crop == "coff" ~ 540, adm_name == "Central Region" & crop == "coff" ~ 1452, adm_name == "Southern Region" & crop == "coff" ~ 1009, adm_name != "Malawi" & crop == "coff" ~ 0, TRUE ~ value_ha)) # Update bana, plnt for which ADM1 and ADM2 information is zero or NA. # We replace using data from the pre-run model solution using the unchanged data stat <- stat %>% mutate(value_ha = case_when( adm_code == "MI03" & crop == "bana" ~ 1656, adm_code == "MI04" & crop == "bana" ~ 16551.67, adm_code == "MI03" & crop == "plnt" ~ 29239, adm_code == "MI04" & crop == "plnt" ~ 6642.33, TRUE ~ value_ha)) # Update ofib, rest, temf, trof, vege for which ADM1 level data is missing # completely. As this is an illustration, we use the maize ha shares to split # the national data for these crops and impute the ADM1 level data. crop_upd_share <- stat %>% dplyr::filter(adm_level %in% c(1), crop == "maiz") %>% mutate(tot = sum(value_ha, na.rm = T), share = value_ha/tot) %>% dplyr::select(adm_level, adm_code, adm_name, share) crop_upd_adm0 <- stat %>% filter(crop %in% c("ofib", "rest", "temf", "trof", "vege"), adm_level %in% c(0)) %>% dplyr::select(crop, adm0_value_ha = value_ha) crop_upd_adm1 <- stat %>% filter(crop %in% c("ofib", "rest", "temf", "trof", "vege"), adm_level %in% c(1)) %>% left_join(crop_upd_adm0) %>% left_join(crop_upd_share) %>% mutate(value_ha = share * adm0_value_ha) %>% dplyr::select(adm_level, adm_code, adm_name, value_ha, crop) stat <- bind_rows( stat %>% filter(!(crop %in% c("ofib", "rest", "temf", "trof", "vege") & adm_level == 1)), crop_upd_adm1) # Put in preferred mapspam format, adding -999 for missing values stat_mapspam <- stat %>% spread(crop, value_ha, fill = -999) %>% arrange(adm_code, adm_code, adm_level) ########## PROCESS SY_CI ########## # For most models we only need adm0 level but we also select adm1 in case the model needs to be run at adm1 level sy_ci <- sy_ci_raw %>% gather(crop_stat, value, -iso3, -prod_level, -rec_type, -name_cntr, -name_admin, -rec_type, -unit, -year_data, -source) %>% dplyr::select(-source, -year_data, -iso3, -name_cntr) %>% mutate(n_char = nchar(prod_level), iso2 = substring(prod_level, 0, 2), adm_temp = substring(prod_level, 3, n_char), adm_level = ifelse(adm_temp == "00", 0, ifelse(nchar(adm_temp) == "2", 1, 2))) %>% dplyr::select(-adm_temp, -iso2, -n_char) %>% filter(adm_level %in% c(0,1)) # Reaggregate adm1 sy_ci_adm1_ag <- sy_ci %>% filter(adm_level == 1) %>% left_join(link_adm1) %>% group_by(crop_stat, o_region, o_fips1, rec_type, adm_level) %>% summarize(value = mean(value, na.rm = T)) %>% rename(name_admin = o_region, prod_level = o_fips1) %>% ungroup() # Combine adm0, adm1 data sy_ci <- bind_rows( sy_ci %>% filter(adm_level == 0), sy_ci_adm1_ag) # Remove millet and coffee varietes that are not needed and rename sy_ci <- sy_ci %>% filter(!crop_stat %in% c("pearlmill", "rob_coffee")) %>% mutate(crop_stat = if_else(crop_stat == "smallmill", "millet", crop_stat), crop_stat = if_else(crop_stat == "ara_coffee", "coffee", crop_stat),) # Rename and select variables sy_ci <- sy_ci %>% dplyr::select(adm_code = prod_level, adm_name = name_admin, adm_level, variable = rec_type, crop_stat, value) # Set adm0_name adm0_code sy_ci <- sy_ci %>% mutate(adm_name = if_else(adm_level == 0, param$country, adm_name), adm_code = if_else(adm_level == 0, param$iso3c, adm_code)) # Recode to standard SPAM crops sy_ci <- sy_ci %>% left_join(orig2crop) %>% dplyr::select(-crop_stat) # Remove Area under National Administration as we also remove the polygon to # ensure no crops will be allocated there sy_ci <- sy_ci %>% filter(!adm_name %in% "Area under National Administration") ########## PREPARE FARMING SYSTEMS SHARE ########## # System shares sy <- sy_ci %>% filter(variable %in% c("SHIRR", "SHRFH", "SHRFS")) %>% spread(variable, value) %>% rename(H = SHRFH, I = SHIRR, S = SHRFS) %>% mutate(L = 100-H-I-S) %>% dplyr::select(crop, adm_name, adm_code, adm_level, S, H, I, L) %>% gather(system, share, -crop, -adm_name, -adm_code, -adm_level) %>% mutate(share = share/100) # Set tea and whea to 100% irrigated in line with secondary statistics sy <- sy %>% mutate(share = case_when( crop == "whea" & system == "I" ~ 1, crop == "whea" & system != "I" ~ 0, crop == "teas" & system == "I" ~ 1, crop == "teas" & system != "I" ~ 0, TRUE ~ share)) # Wide format sy_mapspam <- sy %>% spread(crop, share, fill = -999) %>% arrange(adm_code, adm_code, adm_level) ########## PREPARE CROPING INTENSITY ########## # Cropping intensity by system ci <- sy_ci %>% filter(variable %in% c("CIIRR", "CIRFH", "CIRFL")) %>% rename(ci = variable) %>% spread(ci, value) %>% rename(H = CIRFH, I = CIIRR, L = CIRFL) %>% mutate(S = L) %>% dplyr::select(crop, adm_name, adm_code, adm_level, S, H, I, L) %>% gather(system, ci, -crop, -adm_name, -adm_code, -adm_level) # Wide format ci_mapspam <- ci %>% spread(crop, ci, fill = -999) %>% arrange(adm_code, adm_code, adm_level) ############### SAVE ############### write_csv(stat_mapspam, file.path(param$raw_path, "subnational_statistics/subnational_harvested_area_2010_MWI.csv")) write_csv(ci_mapspam, file.path(param$raw_path, "subnational_statistics/cropping_intensity_2010_MWI.csv")) write_csv(sy_mapspam, file.path(param$raw_path, "subnational_statistics/farming_system_shares_2010_MWI.csv")) ############### NOTE ############### # As you probably created a lot of objects in he R memory, we recommend to # restart R at this moment and start fresh. This can be done easily in RStudio by # pressing CTRL/CMD + SHIFT + F10. <file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom #' Subject: Code to process population maps #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### PROCESS ############### # WorldPop presents population density per #grid cell (in this case 30 arcsec, # the resolution of the map). # In order to use the map at higher resolutions (e.g. 5 arcmin) we need to resample using # the average option and multiple by 100, the number of 30sec grid cells in 5 arcmin. # NOTE: the WorldPop input file is conditional on the year. So make sure you # download the map for the year set in param! grid <- file.path(param$spam_path, glue("processed_data/maps/grid/{param$res}/grid_{param$res}_{param$year}_{param$iso3c}.tif")) mask <- file.path(param$spam_path, glue("processed_data/maps/adm/{param$res}/adm_map_{param$year}_{param$iso3c}.shp")) input <- file.path(param$raw_path, glue("worldpop/ppp_{param$year}_1km_Aggregated.tif")) output <- file.path(param$spam_path, glue("processed_data/maps/population/{param$res}/pop_{param$res}_{param$year}_{param$iso3c}.tif")) if(param$res == "30sec") { temp_path <- file.path(param$spam_path, glue("processed_data/maps/population/{param$res}")) dir.create(temp_path, showWarnings = FALSE, recursive = TRUE) # Warp and mask output_map <- align_rasters(unaligned = input, reference = grid, dstfile = output, cutline = mask, crop_to_cutline = F, r = "bilinear", verbose = F, output_Raster = T, overwrite = T) plot(output_map) } if(param$res == "5min") { temp_path <- file.path(param$spam_path, glue("processed_data/maps/population/{param$res}")) dir.create(temp_path, showWarnings = FALSE, recursive = TRUE) # Warp and mask worldpop_temp <- align_rasters(unaligned = input, reference = grid, dstfile = output, cutline = mask, crop_to_cutline = F, r = "average", verbose = F, output_Raster = T, overwrite = T) # Multiple average population with 100 worldpop_temp <- worldpop_temp*100 plot(worldpop_temp) # Overwrite writeRaster(worldpop_temp, file.path(param$spam_path, glue("processed_data/maps/population/{param$res}/pop_{param$res}_{param$year}_{param$iso3c}.tif")), overwrite = T) } ############### CLEAN UP ############### rm(grid, input, mask, output, output_map, temp_path, worldpop_temp) <file_sep>#'======================================================================================================================================== #' Project: mapspam #' Subject: Code to prepare synergy irrigated map #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### LOAD DATA # Load data load_data(c("adm_map", "grid", "gmia", "gia"), param) ############### PREPARE ############### # Create grid area grid_size <- area(grid) grid_size <- grid_size * 100 # in ha names(grid_size) <- "grid_size" # Grid df grid_df <- as.data.frame(rasterToPoints(grid)) # Create id_df, combining gia and gmia. Remove values < 0.01, most of which are # probably caused by reprojecting the maps ir_df <- as.data.frame(rasterToPoints(stack(grid, grid_size, gmia, gia))) %>% filter(!is.na(gridID)) %>% dplyr::select(-x, -y) %>% mutate(gia = ifelse(gia < 0.01, 0, gia), gmia = ifelse(gmia < 0.01, 0, gmia)) # Create ranking by first taking the maximum of the irrigated area share, # calculate irrigated area, and then rank. In this way we prefer the largest # area, and hence prefer GIA over GMIA when the resolution is 30 arcsec (GIA is # 1 or 0). At a resolution of 5 arcmin the GMIA and grid cells with a lot of GIA # observations get a high rank, which is also desirable. ir_df <- ir_df %>% dplyr::mutate(ir_max = pmax(gmia, gia, na.rm = T), ir_rank = cut(ir_max, labels = c(1:10), breaks = seq(0, 1, 0.1), include.lowest = T), ir_rank = dense_rank(desc(ir_rank)), ir_max = ir_max * grid_size) %>% filter(!is.na(ir_rank), ir_max > 0) %>% dplyr::select(-gmia, -gia, -grid_size) ############### CREATE IR MAX AND IR RANK MAPS ############### # ir_max ir_max_map <- ir_df %>% left_join(grid_df,.) %>% dplyr::select(x, y, ir_max) ir_max_map <- rasterFromXYZ(ir_max_map) crs(ir_max_map) <- crs(param$crs) plot(ir_max_map) plot(adm_map$geometry, add = T) # ir_rank ir_rank_map <- ir_df %>% left_join(grid_df,.) %>% dplyr::select(x, y, ir_rank) ir_rank_map <- rasterFromXYZ(ir_rank_map) crs(ir_rank_map) <- crs(param$crs) plot(ir_rank_map) plot(adm_map$geometry, add = T) ############### SAVE ############### temp_path <- file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}")) dir.create(temp_path, showWarnings = FALSE, recursive = TRUE) writeRaster(ir_max_map, file.path(temp_path, glue::glue("ia_max_{param$res}_{param$year}_{param$iso3c}.tif")),overwrite = T) writeRaster(ir_rank_map, file.path(temp_path, glue::glue("ia_rank_{param$res}_{param$year}_{param$iso3c}.tif")),overwrite = T) ############### CLEAN UP ############### rm(adm_map, gia, gmia, grid, grid_df, grid_size, ir_df, ir_max_map, ir_rank_map, temp_path) <file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom #' Subject: Script to process FAOSTAT crops data #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### LOAD DATA ############### # Set FAOSTAT version faostat_crops_version <- "20200303" # Crop production prod <- read_csv(file.path(param$raw_path, glue("faostat/{faostat_crops_version}_faostat_crops.csv"))) # faostat2crop load_data("faostat2crop", param) ############### PROCESS ############### # faostat2crop faostat2crop <- faostat2crop %>% dplyr::select(crop, faostat_crop_code) %>% na.omit() # Extract harvested area data area <- prod %>% filter(`Area Code` == param$fao_code, Element == "Area harvested", Unit == "ha") %>% dplyr::select(faostat_crop_code = `Item Code`, year = Year, unit = Unit, value = Value) %>% left_join(., faostat2crop) %>% filter(!is.na(value)) %>% na.omit() %>%# remove rows with na values for value group_by(crop, unit, year) %>% summarize(value = sum(value, na.rm = T)) %>% ungroup() %>% mutate(source = "FAOSTAT", adm_level = 0, adm_code = param$iso3c, adm_name = param$country) summary(area) str(area) ########## SAVE ########## write_csv(area, file.path(param$spam_path, glue("processed_data/agricultural_statistics/faostat_crops_{param$year}_{param$iso3c}.csv"))) ########## CREATE FAOSTAT CROP LIST ########## faostat_crop_list <- area %>% dplyr::select(source, adm_code, adm_name, crop) %>% unique() %>% arrange(crop) write_csv(faostat_crop_list, file.path(param$spam_path, glue("processed_data/lists/faostat_crop_list_{param$year}_{param$iso3c}.csv"))) ########## CLEAN UP ########## rm(area, faostat_crop_list, faostat2crop, prod, faostat_crops_version) <file_sep>#'======================================================================================================================================== #' Project: mapspam #' Subject: Script to calculate irrigated system shares #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### LOAD DATA ############### # Adm statistics load_data(c("ha"), param) # Faostat faostat_raw <- read_csv(file.path(param$spam_path, glue("processed_data/agricultural_statistics/faostat_crops_{param$year}_{param$iso3c}.csv"))) # Faostat aquastat_raw <- read_csv(file.path(param$spam_path, glue("processed_data/agricultural_statistics/aquastat_irrigated_crops_{param$year}_{param$iso3c}.csv"))) ########## PROCESS ########## # Prepare stat ha <- ha %>% gather(crop, value_ha, -adm_name, -adm_code, -adm_level) %>% mutate(value_ha = as.numeric(value_ha), value_ha = if_else(value_ha == -999, NA_real_, value_ha), adm_code = as.character(adm_code)) aquastat <- aquastat_raw %>% filter(crop != "total", variable %in% c("Harvested irrigated permanent crop area", "Harvested irrigated temporary crop area")) %>% dplyr::select(adm_code, adm_name, adm_level, crop, ir_area = value, year) faostat <- faostat_raw %>% dplyr::select(adm_name, adm_code, adm_level, crop, year, value) # Combine ir_share <- left_join(faostat, aquastat) %>% na.omit %>% mutate(ir_share = ir_area/value*100) # plot ggplot(data = ir_share, aes(x = as.factor(year), y = ir_share, fill = crop)) + geom_col() + facet_wrap(~crop, scales = "free") # save write_csv(ir_share, file.path(param$spam_path, glue("processed_data/agricultural_statistics/share_of_irrigated_crops_{param$year}_{param$iso3c}.csv"))) <file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom #' Subject: Code process SASAM global synergy cropland map #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### PROCESS CROPRATIO (MEDIAN AREA) ############### temp_path <- file.path(param$spam_path, glue("processed_data/maps/cropland/{param$res}")) dir.create(temp_path, showWarnings = FALSE, recursive = TRUE) # Set files grid <- file.path(param$spam_path, glue("processed_data/maps/grid/{param$res}/grid_{param$res}_{param$year}_{param$iso3c}.tif")) mask <- file.path(param$spam_path, glue("processed_data/maps/adm/{param$res}/adm_map_{param$year}_{param$iso3c}.shp")) input <- file.path(param$spam_path, glue("raw_data/sasam/{param$continent}/cropland_ratio_{param$continent}.tif")) output <- file.path(param$spam_path, glue("processed_data/maps/cropland/{param$res}/cl_med_share_{param$res}_{param$year}_{param$iso3c}.tif")) # Warp and mask output_map <- align_rasters(unaligned = input, reference = grid, dstfile = output, cutline = mask, crop_to_cutline = F, r = "bilinear", verbose = F, output_Raster = T, overwrite = T) # Maps are in shares of area. We multiply by grid size to create an area map. a <- area(output_map) output_map <- output_map * a * 100 plot(output_map) writeRaster(output_map, file.path(param$spam_path, glue("processed_data/maps/cropland/{param$res}/cl_med_{param$res}_{param$year}_{param$iso3c}.tif")),overwrite = T) # clean up rm(grid, input, mask, output, output_map) ############## PROCESS CROPMAX (MAXIMUM AREA) ############### # Set files grid <- file.path(param$spam_path, glue("processed_data/maps/grid/{param$res}/grid_{param$res}_{param$year}_{param$iso3c}.tif")) mask <- file.path(param$spam_path, glue("processed_data/maps/adm/{param$res}/adm_map_{param$year}_{param$iso3c}.shp")) input <- file.path(param$spam_path, glue("raw_data/sasam/{param$continent}/cropland_max_{param$continent}.tif")) output <- file.path(param$spam_path, glue("processed_data/maps/cropland/{param$res}/cl_share_{param$res}_{param$year}_{param$iso3c}.tif")) # warp and mask output_map <- align_rasters(unaligned = input, reference = grid, dstfile = output, cutline = mask, crop_to_cutline = F, r = "bilinear", verbose = F, output_Raster = T, overwrite = T) # Maps are in shares of area. We multiply by grid size to create an area map. a <- area(output_map) output_map <- output_map * a * 100 plot(output_map) writeRaster(output_map, file.path(param$spam_path, glue("processed_data/maps/cropland/{param$res}/cl_max_{param$res}_{param$year}_{param$iso3c}.tif")),overwrite = T) # clean up rm(a, grid, input, mask, output, output_map) ############### PROCESS CROPPROB (PROBABILITY, 1 IS HIGHEST) ############### # Set files grid <- file.path(param$spam_path, glue("processed_data/maps/grid/{param$res}/grid_{param$res}_{param$year}_{param$iso3c}.tif")) mask <- file.path(param$spam_path, glue("processed_data/maps/adm/{param$res}/adm_map_{param$year}_{param$iso3c}.shp")) input <- file.path(param$spam_path, glue("raw_data/sasam/{param$continent}/cropland_confidence_level_{param$continent}.tif")) output <- file.path(param$spam_path, glue("processed_data/maps/cropland/{param$res}/cl_rank_{param$res}_{param$year}_{param$iso3c}.tif")) # warp and mask # Use r = "med" to select the median probability as probability is a categorical variable (1-32). # Remove 0 values (no cropland) before processing as they will bias taking the medium value. output_map <- align_rasters(unaligned = input, reference = grid, dstfile = output, cutline = mask, crop_to_cutline = F, srcnodata = "0", r = "med", verbose = F, output_Raster = T, overwrite = T) plot(output_map) # clean up rm(grid, input, mask, output, output_map, temp_path) <file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom #' Subject: Script to check and calibrate subnational statistics #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### LOAD DATA ############### # harvest area statistics ha_df_raw <- read_csv(file.path(param$raw_path, glue("subnational_statistics/subnational_harvested_area_{param$year}_{param$iso3c}.csv"))) # Farming systems shares fs_df_raw <- read_csv(file.path(param$raw_path, glue("subnational_statistics/farming_system_shares_{param$year}_{param$iso3c}.csv"))) # Cropping intensity ci_df_raw <- read_csv(file.path(param$raw_path, glue("subnational_statistics/cropping_intensity_{param$year}_{param$iso3c}.csv"))) # adm_list load_data("adm_list", param) # faostat fao_raw <- read_csv(file.path(param$spam_path, glue("processed_data/agricultural_statistics/faostat_crops_{param$year}_{param$iso3c}.csv"))) ############### PROCESS HA STATISTICS ############### # wide to long format ha_df <- ha_df_raw %>% gather(crop, ha, -adm_name, -adm_code, -adm_level) # Convert -999 and empty string values to NA ha_df <- ha_df %>% mutate(ha = if_else(ha == -999, NA_real_, ha), ha = as.numeric(ha)) # this will transform empty string values "" into NA and throw a warning # filter out crops which values are all zero or NA crop_na_0 <- ha_df %>% group_by(crop) %>% filter(all(ha %in% c(0, NA))) %>% dplyr::select(crop) %>% unique ha_df <- ha_df %>% filter(!crop %in% crop_na_0$crop) # Remove lower level adm data if it would in the data but not used ha_df <- ha_df %>% filter(adm_level <= param$adm_level) # Round values ha_df <- ha_df %>% mutate(ha = round(ha, 0)) # Check if the statistics add up and show where this is not the case check_statistics(ha_df, param, out = T) # Make sure the totals at higher levels are the same as subtotals # We start at the lowest level, assuming lower levels are preferred if more than one level # of data is available and data is complete. ha_df <- reaggregate_statistics(ha_df, param) # Check again check_statistics(ha_df, param, out = T) ########## HARMONIZE HA WITH FAOSTAT ########## # Compare with FAO # Process fao fao <- fao_raw %>% filter(year %in% c((param$year-1): (param$year+1))) %>% group_by(crop) %>% summarize(ha = mean(value, na.rm = T)) %>% dplyr::select(crop, ha) # Compare fao_ha <- bind_rows( fao %>% mutate(source = "fao"), ha_df %>% filter(adm_level == 0) %>% mutate(source = "ha_df") ) ggplot(data = fao_ha) + geom_col(aes(x = source, y = ha, fill = source)) + facet_wrap(~crop, scales = "free") # We scale all the data to FAOSTAT # If the data is incomplete and the sum is lower than FAOSTAT we do no adjust. # If the data is incomplete and the sum is higher than FAOSTAT we scale down. # Identify crops that are present in ha_df but not in fao and remove them from ha_df. crop_rem <- setdiff(unique(ha_df$crop), unique(fao$crop)) ha_df <- ha_df %>% filter(!crop %in% crop_rem) # Identify crops that are present in fao but not in ha_df. # We will add then to ha_df crop_add <- setdiff(unique(fao$crop), unique(ha_df$crop)) ha_df <- ha_df %>% bind_rows( fao %>% filter(crop %in% crop_add) %>% mutate( fips = unique(ha_df$adm_code[ha_df$adm_level==0]), adm_level = 0, adm = unique(ha_df$adm_name[ha_df$adm_level==0]))) # Calculate scaling factor fao_stat_sf <-bind_rows( fao %>% mutate(source = "fao"), ha_df %>% filter(adm_level == 0) %>% mutate(source = "ha_df")) %>% dplyr::select(crop, source, ha) %>% spread(source, ha) %>% mutate(sf = fao/ha_df) %>% dplyr::select(crop, sf) # rescale ha_df ha_df <- ha_df %>% left_join(fao_stat_sf) %>% mutate(ha = ha * sf) %>% dplyr::select(-sf) # Compare again fao_stat <- bind_rows( fao %>% mutate(source = "fao"), ha_df %>% filter(adm_level == 0) %>% mutate(source = "ha_df") ) ggplot(data = fao_stat) + geom_col(aes(x = source, y = ha, fill = source)) + facet_wrap(~crop, scales = "free") ############### FINALIZE HA ############### # Consistency checks check_statistics(ha_df, param) # To wide format ha_df <- ha_df %>% spread(crop, ha, fill = -999) %>% arrange(adm_code, adm_name, adm_level) ############### PROCESS FARMING SYSTEM SHARES ############### # ci does not need to be adjusted fs_df <- fs_df_raw ############### PROCESS CROPPING INTENSITY ############### # ci does not need to be adjusted ci_df <- ci_df_raw ########## SAVE ########## # Save the ha, fs and ci csv files in the Processed_data/agricultural_statistics folder # Note that they have to be saved in this folder using the names below so do not change this! write_csv(ha_df, file.path(param$spam_path, glue("processed_data/agricultural_statistics/ha_adm_{param$year}_{param$iso3c}.csv"))) write_csv(fs_df, file.path(param$spam_path, glue("processed_data/agricultural_statistics/fs_adm_{param$year}_{param$iso3c}.csv"))) write_csv(ci_df, file.path(param$spam_path, glue("processed_data/agricultural_statistics/ci_adm_{param$year}_{param$iso3c}.csv"))) ############### NOTE ############### # As you probably created a lot of objects in he R memory, we recommend to # restart R at this moment and start fresh. This can be done easily in RStudio by # pressing CTRL/CMD + SHIFT + F10. <file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom #' Subject: Code to run all core scripts that select spatial layers #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== # NOTE: if you have prefer to use alternative spatial layers you can add them # and replace some of the the global layers. ############### CROPLAND ############### source(here::here("scripts/03_spatial_data/select_esa.r")) source(here::here("scripts/03_spatial_data/select_sasam.r")) ############### IRRIGATED AREA ############### source(here::here("scripts/03_spatial_data/select_gia.r")) source(here::here("scripts/03_spatial_data/select_gmia.r")) ############### BIOPHYSICAL SUITABILITY AND POTENTIAL YIELD ############### source(here::here("scripts/03_spatial_data/select_gaez.r")) ############### ACCESSIBILITY ############### source(here::here("scripts/03_spatial_data/select_travel_time_2000_2015.r")) ############### POPULATION ############### source(here::here("scripts/03_spatial_data/select_worldpop.r")) source(here::here("scripts/03_spatial_data/select_urban_extent.r")) ############### SIMU ############### source(here::here("scripts/03_spatial_data/select_simu.r")) <file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom_mwi #' Subject: Process adm shapefile #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### LOAD DATA ############### # replace the name of the shapefile with that of your own country. iso3c_shp <- "adm_2010_MWI.shp" # load shapefile adm_map_raw <- read_sf(file.path(param$raw_path, glue("adm/{iso3c_shp}"))) # plot plot(adm_map_raw$geometry) ############### PROCESS ############### # Project to standard global projection adm_map <- adm_map_raw %>% st_transform(param$crs) # Check names head(adm_map) names(adm_map) # Change names In order to use the country polygon as input, the column names of # the attribute table have to be set. # The names of the administrative units should be set to admX_name, where X is the adm level. # The codes of the administrative units should be set to admX_code, where X is the adm code. # Set the original names, i.e. the ones that will be replaced. Remove adm1 # and/or adm2 entries if such data is not available. adm0_name_orig <- "ADM0_NAME" adm0_code_orig <- "FIPS0" adm1_name_orig <- "ADM1_NAME" adm1_code_orig <- "FIPS1" adm2_name_orig <- "ADM2_NAME" adm2_code_orig <- "FIPS2" # Replace the names names(adm_map)[names(adm_map) == adm0_name_orig] <- "adm0_name" names(adm_map)[names(adm_map) == adm0_code_orig] <- "adm0_code" names(adm_map)[names(adm_map) == adm1_name_orig] <- "adm1_name" names(adm_map)[names(adm_map) == adm1_code_orig] <- "adm1_code" names(adm_map)[names(adm_map) == adm2_name_orig] <- "adm2_name" names(adm_map)[names(adm_map) == adm2_code_orig] <- "adm2_code" # Only select relevant columns adm_map <- adm_map %>% dplyr::select(adm0_name, adm0_code, adm1_name, adm1_code, adm2_name, adm2_code) # Check names head(adm_map) names(adm_map) # Union separate polygons that belong to the same adm adm_map <- adm_map %>% group_by(adm0_name, adm0_code, adm1_name, adm1_code, adm2_name, adm2_code) %>% summarize() %>% ungroup() %>% mutate(adm0_name = param$country, adm0_code = param$iso3c) par(mfrow=c(1,2)) plot(adm_map$geometry, main = "ADM all polygons") # Set names of ADMs that need to be removed from the polygon. # These are ADMs where no crop should be allocated. Here we remove # Area under National Administration, which is the part of Lake Malawi that belongs to Malawi # and Likoma, several small islands in the lake that are not covered by the statistics. # Set the adm_name by ADM level which need to be removed. Otherwise remove the script. adm1_to_remove <- c("Area under National Administration") adm2_to_remove <- c("Likoma") # Remove ADMs adm_map <- adm_map %>% filter(adm1_name != adm1_to_remove) %>% filter(adm2_name != adm2_to_remove) plot(adm_map$geometry, main = "ADM polygons removed") par(mfrow=c(1,1)) # Create adm_list create_adm_list(adm_map, param) ############### SAVE ############### # Save adm maps temp_path <- file.path(param$spam_path, glue("processed_data/maps/adm/{param$res}")) dir.create(temp_path, showWarnings = FALSE, recursive = TRUE) saveRDS(adm_map, file.path(temp_path, glue("adm_map_{param$year}_{param$iso3c}.rds"))) write_sf(adm_map, file.path(temp_path, glue("adm_map_{param$year}_{param$iso3c}.shp"))) ############### CREATE PDF ############### # Create pdf with the location of administrative units create_adm_map_pdf(param) ############### CREATE GRID ############### create_grid(param) ############### RASTERIZE ADM_MAP ############### rasterize_adm_map(param) ############### CLEAN UP ############### rm(adm_map, adm_map_raw, iso3c_shp, temp_path) rm(list = ls()[grep("code_orig", ls())]) rm(list = ls()[grep("name_orig", ls())]) rm(list = ls()[grep("to_remove", ls())]) <file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom #' Subject: Code to select simu #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### LOAD DATA ############### # simu global map simu_global <- st_read(file.path(param$raw_path, "Simu/simu_global.shp")) # Simu area simu_area <- read_csv(file.path(param$raw_path, "simu/simu_area.csv")) load_data("grid", param) ############### PROCESS ############### # select country simu and add area info simu <- simu_global %>% filter(COUNTRY == param$iso3n) %>% left_join(simu_area) plot(simu$geometry) # rasterize simu_r <- rasterize(simu, grid, field = "SimUID") plot(simu_r) ############### SAVE ############### temp_path <- file.path(param$spam_path, glue::glue("processed_data/maps/simu/{param$res}")) dir.create(temp_path, showWarnings = F, recursive = T) saveRDS(simu, file.path(temp_path, glue::glue("simu_{param$res}_{param$year}_{param$iso3c}.rds"))) writeRaster(simu_r, file.path(temp_path, glue::glue("simu_r_{param$res}_{param$year}_{param$iso3c}.tif")), overwrite = T) ### CLEAN UP rm(grid, simu, simu_area, simu_r, simu_global, temp_path) <file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom #' Subject: Code to process GIA #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### LOAD DATA ############### # Raw gia file gia_raw <- raster(file.path(param$raw_path, "gia/global_irrigated_areas.tif")) ############### PROCESS ############### # The crs of the gia (WGS 84) is missing for some reason. We add and save the map crs(gia_raw) <- "+proj=longlat +datum=WGS84 +no_defs" if(!file.exists(file.path(param$raw_path, "gia/global_irrigated_areas_crs.tif"))){ writeRaster(gia_raw, file.path(param$raw_path, "gia/global_irrigated_areas_crs.tif"), overwrite = T) } # Gia assumes full 30sec (the resolution of the map) are irrigated and uses a categorical # variable (1-4) to indicate irrigated areas (see README.txt). # In order to use the map at higher resolutions (e.g. 5 arcmin) we need to reclassify these into # 1 (100%) and use gdalwarp with "average" to calculate the share of irrigated area at larger grid cells. # If res is 30sec, we can clip the raw map and reclassify c(1:4) values to 1. # Set files grid <- file.path(param$spam_path, glue("processed_data/maps/grid/{param$res}/grid_{param$res}_{param$year}_{param$iso3c}.tif")) mask <- file.path(param$spam_path, glue("processed_data/maps/adm/{param$res}/adm_map_{param$year}_{param$iso3c}.shp")) input <- file.path(param$raw_path, "gia/global_irrigated_areas_crs.tif") output <- file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}/gia_temp_{param$year}_{param$iso3c}.tif")) temp_path <- file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}")) dir.create(temp_path, showWarnings = FALSE, recursive = TRUE) # Clip to adm # Warp and mask # Use r = "near" for categorical values. # Use crop to cutline to crop. # TODO probably does not work at 30sec!! gia_temp <- align_rasters(unaligned = input, reference = grid, dstfile = output, cutline = mask, crop_to_cutline = F, r = "near", verbose = F, output_Raster = T, overwrite = T) # Reclassify gia_temp <- reclassify(gia_temp, cbind(1, 4, 1)) names(gia_temp) <- "gia" plot(gia_temp) if(param$res == "30sec") { temp_path <- file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}")) dir.create(temp_path, showWarnings = FALSE, recursive = TRUE) writeRaster(gia_temp, file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}/gia_{param$res}_{param$year}_{param$iso3c}.tif")), overwrite = T) } if(param$res == "5min"){ temp_path <- file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}")) dir.create(temp_path, showWarnings = FALSE, recursive = TRUE) # Save temporary file with 1 for irrigated area writeRaster(gia_temp, file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}/gia_temp_{param$year}_{param$iso3c}.tif")), overwrite = T) # Set files grid <- file.path(param$spam_path, glue("processed_data/maps/grid/{param$res}/grid_{param$res}_{param$year}_{param$iso3c}.tif")) mask <- file.path(param$spam_path, glue("processed_data/maps/adm/{param$res}/adm_map_{param$year}_{param$iso3c}.shp")) input <- file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}/gia_temp_{param$year}_{param$iso3c}.tif")) output <- file.path(param$spam_path, glue("processed_data/maps/irrigated_area/{param$res}/gia_{param$res}_{param$year}_{param$iso3c}.tif")) # Warp and mask # Use average to calculate share of irrigated area gia_temp <- align_rasters(unaligned = input, reference = grid, dstfile = output, cutline = mask, crop_to_cutline = F, r = "average", verbose = F, output_Raster = T, overwrite = T) plot(gia_temp) } ############### CLEAN UP ############### rm(gia_raw, gia_temp, input, grid, mask, output, temp_path) <file_sep>#'======================================================================================================================================== #' Project: mapspam #' Subject: Script to process aquastat irrigation data #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### LOAD DATA ############### # Set aquastat version aquastat_version <- "20200303" # Aquastat raw aquastat_raw <- read_excel(file.path(param$raw_path, glue("aquastat/{aquastat_version}_aquastat_irrigation.xlsx")), sheet = "data") # Crop mapping aquastat2crop <- read_csv(file.path(param$spam_path, "mappings/aquastat2crop.csv")) ############### PROCESS ############### # Clean up database aquastat <- aquastat_raw %>% filter(`Area Id` == param$fao) %>% mutate(adm_code = param$iso3c, adm_name = param$country, adm_level = 0) %>% transmute(adm_name, adm_code, adm_level, variable = `Variable Name`, variable_code = `Variable Id`, year = Year, value = Value) # Create irrigated area df # Note that "Total harvested irrigated crop area (full control irrigation)" (4379) is only presented if all crops are included ir_area <- aquastat %>% dplyr::filter(grepl("Harvested irrigated temporary crop area", variable)| grepl("Harvested irrigated permanent crop area", variable)| variable_code %in% c(4379, 4313)) %>% separate(variable, c("variable", "aquastat_crop"), sep = ":") %>% mutate(aquastat_crop = trimws(aquastat_crop), aquastat_crop = ifelse(is.na(aquastat_crop), "Total", aquastat_crop), aquastat_crop = ifelse(aquastat_crop == "total", "Total", aquastat_crop), value = value * 1000) # to ha # Map to crops ir_area <- ir_area %>% left_join(aquastat2crop) %>% group_by(adm_name, adm_code, adm_level, variable, year, crop) %>% summarize(value = sum(value, na.rm = T), aquastat_crop = paste(aquastat_crop, collapse = ", ")) %>% mutate(system = "I") %>% filter(crop != "REMOVE") # removes fodder ########## USER INPUT ########## # AQUASTAT uses "Other fruits" as a category, which can either be mapped to # tropical fruits (trof) or temperate fruits (temf) in mapspam. # The standard is to map it to trof. If this is fine there is no need for any changes. # If temf is more appropriate change trof to temf below. # Check if the Other fruits category is present. other_fruits <- ir_area %>% filter(crop %in% c("trof, temf")) if(NROW(other_fruits) == 0) { message("There is no Other fruits category") } else { message("There is an Other fruits category") } # If you want to change Other fruits to temf, change "trof" to "temf" in the statement below ir_area <- ir_area %>% mutate(crop = if_else(aquastat_crop == "Other fruits", "trof", crop)) ############### SAVE ############### write_csv(ir_area, file.path(param$spam_path, glue("processed_data/agricultural_statistics/aquastat_irrigated_crops_{param$year}_{param$iso3c}.csv"))) ############### CLEAN UP ############### rm(aquastat, aquastat_raw, aquastat_version, aquastat2crop, ir_area, other_fruits) <file_sep>#'======================================================================================================================================== #' Project: mapspam #' Subject: Script to combine and harmonize input data #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### PREPARE PHYSICAL AREA ############### prepare_physical_area(param) ############### CREATE SYNERGY CROPLAND INPUT ############### prepare_cropland(param) ############### PROCESS ############### prepare_irrigated_area(param) ############### HARMONIZE INPUT DATA ############### harmonize_inputs(param) ############### PREPARE SCORE ############### prepare_priors_and_scores(param) ############### COMBINE MODEL INPUTS ############### combine_inputs(param) <file_sep>#'======================================================================================================================================== #' Project: mapspam #' Subject: Code to process travel time maps #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### PROCESS ############### temp_path <- file.path(param$spam_path, glue("processed_data/maps/accessibility/{param$res}")) dir.create(temp_path, showWarnings = FALSE, recursive = TRUE) # Set files grid <- file.path(param$spam_path, glue("processed_data/maps/grid/{param$res}/grid_{param$res}_{param$year}_{param$iso3c}.tif")) mask <- file.path(param$spam_path, glue("processed_data/maps/adm/{param$res}/adm_map_{param$year}_{param$iso3c}.shp")) output <- file.path(param$spam_path, glue("processed_data/maps/accessibility/{param$res}/acc_{param$res}_{param$year}_{param$iso3c}.tif")) # There are two products, one for around 2000 and one for around 2015, we select on the basis of reference year if (param$year <= 2007){ input <- file.path(param$raw_path, "travel_time_2000/acc_50.tif") } else { input <- file.path(param$raw_path, "travel_time_2015/2015_accessibility_to_cities_v1.0.tif") } # Warp and mask output_map <- align_rasters(unaligned = input, reference = grid, dstfile = output, cutline = mask, crop_to_cutline = F, srcnodata = "-9999", r = "bilinear", verbose = F, output_Raster = T, overwrite = T) plot(output_map) ############### CLEAN UP ############### rm(input, mask, output, grid, output_map, temp_path) <file_sep>#'======================================================================================================================================== #' Project: mapspam2globiom_mwi #' Subject: Run model #' Author: <NAME> #' Contact: <EMAIL> #'======================================================================================================================================== ############### SOURCE PARAMETERS ############### source(here::here("scripts/01_model_setup/01_model_setup.r")) ############### INSPECT RESULTS ############### view_panel("rice", var = "ha", param) view_stack("rice", var = "ha", param) ############### CREATE TIF ############### create_all_tif(param)
60b331909ece25829790cfac43a4bdd312387ecc
[ "Markdown", "R" ]
24
R
iiasa/mapspam2globiom_mwi
354f76921dcee85a8493233aae26ff113f15c90f
764ce148fae964c17adec02a5ef358d8e2b7fa5f
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using WebApplication5.Models; namespace WebApplication5.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } [HttpPost] public IActionResult Download(string url) { try { var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("URL", url) }); List<VideoResultViewModel> viewModel = Helper.StaticHttp.GetVideo("https://twdown.net/download.php", content).Result; return View("About", viewModel); } catch (Exception) { return View("Error"); } } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } [HttpGet] [Route("sitemap.xml")] public IActionResult SitemapXml() { String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"; xml += "<url>"; xml += "<loc>http://localhost:4251/home</loc>"; xml += "<lastmod>" + DateTime.Now.ToString("yyyy-MM-dd") + "</lastmod>"; xml += "</url>"; xml += "<url>"; xml += "<loc>http://localhost:4251/counter</loc>"; xml += "<lastmod>" + DateTime.Now.ToString("yyyy-MM-dd") + "</lastmod>"; xml += "</url>"; xml += "</urlset>"; return Content(xml, "text/xml"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApplication5.Models { public class VideoResultViewModel { public string HrefAttribute { get; set; } public string Resolution { get; set; } } }
62ad928a49e3f256be958d57455f923455e00275
[ "C#" ]
2
C#
stevengau/WebApplication5
54aa61ea6e587de689a8d9e48a0cd5ca34b7d83f
e8c807c9c70f2c56f330cc5291dc6b4c6e9b50ac
refs/heads/master
<file_sep>package com.gentalion; import java.util.Random; public class Game { public static int MONTHS_IN_YEAR = 12; public static double YOUNG_SURVIVAL_CHANCE = 0.75; public static double ADULT_BIRTH_RATE = 0.9; public static double OLD_BIRTH_RATE = 0.8; public static double OLD_MORTALITY = 0.3; public static double UNEXPECTED_MORTALITY = 0.05; public static int INITIAL_MONEY = 5000; public static boolean CREDIT_MONEY = false; private Farm farm; private Contract contract; private int yearsPast; private int totalIncome; private int totalFeedPurchased; private int totalYoungAnimalsSold; private int totalAdultAnimalsSold; private int totalOldAnimalsSold; public Farm getFarm() { return farm; } public Contract getContract() { return contract; } public int getYearsPast() { return yearsPast; } public int getTotalIncome() { return totalIncome; } public int getTotalFeedPurchased() { return totalFeedPurchased; } public int getTotalYoungAnimalsSold() { return totalYoungAnimalsSold; } public int getTotalAdultAnimalsSold() { return totalAdultAnimalsSold; } public int getTotalOldAnimalsSold() { return totalOldAnimalsSold; } public Game() { newGame(); } public void newGame () { Random random = new Random(); farm = new Farm (INITIAL_MONEY, 0, random.ints(100,200).findFirst().getAsInt(), random.ints(100,200).findFirst().getAsInt(), random.ints(100,200).findFirst().getAsInt()); contract = new Contract(3, farm); yearsPast = 0; totalIncome = 0; totalFeedPurchased = 0; totalYoungAnimalsSold = 0; totalAdultAnimalsSold = 0; totalOldAnimalsSold = 0; } public boolean simulateYear () { int forfeit = 0; int notPurchasedFeed = contract.getFeedPerYear() - farm.getFeedPurchased(); forfeit += (notPurchasedFeed > 0 ? notPurchasedFeed * contract.getFeedCost() * 2 : 0); int notSoldYoungAnimals = contract.getYoungAnimalsPerYear() - farm.getAdultAnimalsSold(); forfeit += (notSoldYoungAnimals > 0 ? notSoldYoungAnimals * contract.getYoungAnimalCost() : 0); int notSoldAdultAnimals = contract.getAdultAnimalsPerYear() - farm.getAdultAnimalsSold(); forfeit += (notSoldAdultAnimals > 0 ? notSoldAdultAnimals * contract.getAdultAnimalCost() : 0); int notSoldOldAnimals = contract.getOldAnimalsPerYear() - farm.getOldAnimalsSold(); forfeit += (notSoldOldAnimals > 0 ? notSoldOldAnimals * contract.getAdultAnimalCost() : 0); farm.setMoney(farm.getMoney() - forfeit); totalIncome = farm.getMoney() - INITIAL_MONEY; totalFeedPurchased += farm.getFeedPurchased(); totalYoungAnimalsSold += farm.getYoungAnimalsSold(); totalAdultAnimalsSold += farm.getAdultAnimalsSold(); totalOldAnimalsSold += farm.getOldAnimalsSold(); farm.simulateYear(); yearsPast++; if (yearsPast == contract.getYears()) { return true; } return false; } public void fulfillAllContractTerms () { int unsoldYoungAnimals = contract.getYoungAnimalsPerYear() - farm.getYoungAnimalsSold(); if (unsoldYoungAnimals > 0) { farm.sellYoungAnimals(unsoldYoungAnimals, contract.getYoungAnimalCost()); } int unsoldAdultAnimals = contract.getAdultAnimalsPerYear() - farm.getAdultAnimalsSold(); if (unsoldAdultAnimals > 0) { farm.sellAdultAnimals(unsoldAdultAnimals, contract.getAdultAnimalCost()); } int unsoldOldAnimals = contract.getOldAnimalsPerYear() - farm.getOldAnimalsSold(); if (unsoldOldAnimals > 0) { farm.sellOldAnimals(unsoldOldAnimals, contract.getOldAnimalCost()); } int unpurchasedFeed = contract.getFeedPerYear() - farm.getFeedPurchased(); if (unpurchasedFeed > 0) { farm.purchaseFeed(unpurchasedFeed, contract.getFeedCost()); } } }
e8e02662f1406d8893f5a92b886a86313ca427b3
[ "Java" ]
1
Java
Gentalion/FarmSim
f26159ddc9fa21eea85069e731447bfa201571cf
0c9b0a9cb8ee725ab3e4f920a808b0f5c6b3cd8c
refs/heads/master
<repo_name>TongChang/guestbook<file_sep>/Guestbook/src/jp/co/DDJ/guestbook/util/UserInfo.java package jp.co.DDJ.guestbook.util; import javax.servlet.http.HttpServletRequest; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; /** * * <p> * ユーザ情報管理クラス。 * </p> * * <pre> * ユーザ情報を管理します。 * </pre> * * @author としふに * */ public final class UserInfo { /** * ユーザサービス情報。 */ private UserService _userservice; /** * ユーザ情報。 */ private User _user; /** * HTTPリクエスト。 */ private HttpServletRequest _req; /** * * <p> * コンストラクタ。 * </p> * * <pre> * コンストラクタにて、ユーザ情報の設定を行います。 * ユーザの取得可否については、サーブレット側で精査してください。 * </pre> * * @param req HTTPリクエスト */ public UserInfo(HttpServletRequest req) { // ユーザーサービスの初期化 this._userservice = UserServiceFactory.getUserService(); this._user = _userservice.getCurrentUser(); this._req = req; } /** * * <p> * ユーザ情報取得。 * </p> * * <pre> * ユーザ情報を返却します。 * </pre> * * @return User ユーザ情報 */ public User getUser() { return this._user; } /** * * <p> * ユーザログアウトURL取得。 * </p> * * <pre> * ユーザのログアウト用URLを返却します。 * </pre> * * @return String ログアウト用URL */ public String getLogoutURL() { return _userservice.createLogoutURL(this._req.getRequestURI()); } /** * * <p> * ユーザログインURL取得。 * </p> * * <pre> * ユーザのログイン用URLを返却します。 * </pre> * * @return String ログアウト用URL */ public String getLoginURL() { return _userservice.createLoginURL(this._req.getRequestURI()); } } <file_sep>/Guestbook/src/jp/co/DDJ/guestbook/datastore/dao/package-info.java /** * DAO(DataAccessObject)パッケージ。 * ============================================================== * DAOはSelectとかInsertとか、DBにアクセスしてくれる人のこと。 * 結果としてEntityを返してくれたりする。 * 引用元:http://daipresents.com/2009/dao_dto_vo_entity/ * ============================================================== * */ package jp.co.DDJ.guestbook.datastore.dao;<file_sep>/Guestbook/src/jp/co/DDJ/guestbook/util/package-info.java /** * 共通機能パッケージ。 */ package jp.co.DDJ.guestbook.util;<file_sep>/Guestbook/src/jp/co/DDJ/guestbook/servlet/SignGuestbookServlet.java package jp.co.DDJ.guestbook.servlet; import java.io.IOException; import java.util.Date; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jp.co.DDJ.guestbook.datastore.dao.GreetingDAO; import jp.co.DDJ.guestbook.util.Request; import jp.co.DDJ.guestbook.util.UserInfo; /** * * <p> * ゲストブック登録用サーブレットクラス。 * </p> * * <pre> * ゲストブックにデータを登録するための業務ロジッククラスです。 * </pre> * * @author としふに * */ public class SignGuestbookServlet extends HttpServlet { /** * * <p> * doPostメソッド。 * </p> * * <pre> * postリクエスト時に呼び出されるメソッドです。 * 渡されたリクエストを使用して、ゲストブックにデータを登録します。 * </pre> * * @param req HTTPレスポンス * @param resp HHTPレスポンス */ public final void doPost(HttpServletRequest req, HttpServletResponse resp) { // ユーザ情報を取得 UserInfo ui = new UserInfo(req); // ログイン情報取得精査 if (ui.getUser() == null) { try { // 未ログインの場合はログインページへ遷移 resp.sendRedirect(ui.getLoginURL()); } catch (IOException ioe) { // エラーページに飛べたらいいなぁ ioe.printStackTrace(); } } // リクエスト情報からGreetingへ登録 GreetingDAO.insert(ui.getUser(), req.getParameter("content"), new Date()); // トップにリダイレクト Request.doRedirect(resp, "/guestbook"); } } <file_sep>/Guestbook/src/jp/co/DDJ/guestbook/util/Request.java package jp.co.DDJ.guestbook.util; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * <p> * Request関連処理の共通クラス。 * </p> * * <pre> * URL間の遷移機能を持ちます。 * </pre> * * @author としふに * */ public final class Request { /** * * <p> * コンストラクタ(アクセス不可)。 * </p> * * <pre> * プライベートコンストラクタ。 * </pre> * */ private Request() { } /** * * <p> * フォワード処理。 * </p> * * <pre> * 引数のHTTPリクエスト、HTTPレスポンス、遷移先URLより * 遷移先URLへフォワードします。 * </pre> * * @param req HTTPリクエスト * @param resp HTTPレスポンス * @param url 遷移先URL */ public static void doFoward(HttpServletRequest req, HttpServletResponse resp, String url) { // URLへ遷移 RequestDispatcher dispatcher = req.getRequestDispatcher(url); try { dispatcher.forward(req, resp); } catch (IOException ioe) { // TODO ログ吐いてエラーページに遷移 ioe.printStackTrace(); } catch (ServletException se) { // TODO ログ吐いてエラーページに遷移 se.printStackTrace(); } } /** * * <p> * リダイレクト処理。 * </p> * * <pre> * 引数のHTTPレスポンス、遷移先URLより * 遷移先URLへリダイレクトします。 * </pre> * * @param resp HTTPレスポンス * @param url 遷移先URL */ public static void doRedirect(HttpServletResponse resp, String url) { try { // URLへ遷移 resp.sendRedirect(url); } catch (IOException ioe) { // TODO ログ吐いてエラーページに遷移 ioe.printStackTrace(); } } } <file_sep>/Guestbook/src/jp/co/DDJ/guestbook/servlet/package-info.java /** * サーブレット用パッケージ。 */ package jp.co.DDJ.guestbook.servlet;
249f3c3c04bb12f2944443078d7f9830e251c1f8
[ "Java" ]
6
Java
TongChang/guestbook
a0c36ac4001c580cc0576549c8d4bfd94412c009
d4d0da0c27585c3a414894b97bd1f3b146061114
refs/heads/main
<repo_name>DongCX-LDHSP/AAHelper<file_sep>/README.md # AAHelper 一个均摊辅助工具,受合租时水电燃气费均摊的启发而做。 ## 功能点 ### 普通AA - 最普通的均摊,基于总费用和人数直接进行均分 - 该功能点用于处理最普通的情况,在实际中可能并不需要使用这个功能 ### 按天AA - 按照天数将总费用均摊到每个人身上 - 该功能点可能更加常用,因为实际中室友并不总是在同一时间点入住的 ### 按人AA - 该功能点的需求**尚不明确**,有待跟“甲方(经验丰富的室友)”进行沟通,(●ˇ∀ˇ●) - 不过该功能点将会用于应对**一个房间有多个人**的情况 - 为什么这样做呢?我的猜想是电费可能更适合**按照房间来均摊** ### 租房Tip - 在这里保存一些租房注意事项,帮助避坑 ### 关于AAHelper AAHelper的诞生原因及其目的,何处获取维护帮助 ## 设计 ### 包划分 - `AAActivities` - `SimpleAAActivity`:普通AA的页面 - `DayAAActivity`:按天AA的页面 - `PersonAAActivity`:按人AA的页面 - `ShowResultActivity`:展示**计算过程**及结果的页面 - `Bean`:实体类,用于封装数据,亟待设计,用于应对页面间数据传递 - `Utils`:工具类 - `ToastMaker`:展示Toast的工具类,现在使用的是最基本的Toast。设计这个工具类的好处就是:在后期设计个性化的Toast样式时,只需要修改这个工具类就可以了,算是一种抽象 - `CountDays`:计算天数的工具类 ### 关键功能点 - **生成计算过程** - **计算天数** ### 设想功能点 - 实现每一次水电燃气费均摊的记录 - 可以保存房屋内室友的状态,进而实现每次只需要输入水电燃气费就能一键计算,而不需要频繁录入室友的入住,离开信息 - 可以保存入住时的房屋状态: - 厨房用品:水龙头、冰箱、燃气灶、抽油烟机、橱柜等等 - 个人房间用品:床、衣柜、书桌、椅子、空调、遥控器、窗帘、灯 - 洗手间:马桶、水池、热水器、拖把、扫把、洗衣机、灯暖、淋雨头、镜子 - 公共区域:沙发、电视、大门、踢脚线、墙壁粉刷状态 - 租房日志:保存房间何时因为什么而进行了何种维修 - (基于房间局域网的信息共享功能,说实话有点鸡肋,也太大了,不必要) ## 运行环境 - `Android`本地运行,应用并不需要联网(实际上是由于我不了解网络开发以及不想买服务器(●ˇ∀ˇ●)) ## 开发目标 - 实现基本的功能点 - 尽力或尝试实现设想功能点 ## 其他 - 开发者:`DongCX-LDHSP` - 来源:水电燃气费均摊计算 ## 致谢 **可爱而强大的室友**<file_sep>/app/src/main/java/com/dcx/AAHelper/InfoActivities/AboutAAHelperActivity.java package com.dcx.AAHelper.InfoActivities; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import com.dcx.AAHelper.R; import com.dcx.AAHelper.Utils.ToastMaker; /** * @author DongCX-LDHSP * @date 2021.08.21 * 展示关于AAHelper的一些信息: * - 作者 * - 开源仓库地址 * - 何处寻求帮助 */ public class AboutAAHelperActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about_a_a_helper); ToastMaker.showShortToast(this, getString(R.string.aboutAAHelperMessage)); } }<file_sep>/app/src/main/java/com/dcx/AAHelper/InfoActivities/RentTipActivity.java package com.dcx.AAHelper.InfoActivities; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import com.dcx.AAHelper.R; import com.dcx.AAHelper.Utils.ToastMaker; /** * @author DongCX-LDHSP * @date 2021.08.21 * 展示一些租房建议,最好能实现成在线获取的形式 */ public class RentTipActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rent_tip); ToastMaker.showShortToast(this, getString(R.string.rentTipMessage)); } }
b553812ea7033f4b076fb5cc464cd9ec28d95534
[ "Markdown", "Java" ]
3
Markdown
DongCX-LDHSP/AAHelper
83a11046c8c16895c167b0f0df6cfd3a2d6bae90
f771af511ef59539efc761320feb23ea3aa357e7
refs/heads/main
<repo_name>sangil-huinno/ecg_gan<file_sep>/ecg/noise_cluster.py import pickle import tensorflow as tf import numpy as np from numpy.linalg import norm from tensorflow.python.keras import Model from tensorflow.python.keras.models import load_model def label_processing(total_data): for label in ['label1', 'label2', 'label3', 'label4', 'label5']: total_data.loc[total_data[label] == '8', label] = '2' total_data.loc[total_data[label] == '10', label] = '3' total_data.loc[total_data[label].isin(['7', '12', '14']), label] = '10' total_data.loc[total_data[label].isin(['15', '16', '17', '18', '19']), label] = None # label 번호 당기기 total_data.loc[total_data[label] == '9', label] = '7' total_data.loc[total_data[label] == '11', label] = '8' total_data.loc[total_data[label] == '13', label] = '9' # label processing - if label1 = 1, label2 not None, label1 = label2, label2 = label 3,... total_data = total_data.reset_index(drop=True) for i in range(len(total_data['label1'])): if total_data.loc[i,'label2'] is not None: if total_data.loc[i,'label1'] == '1': total_data.loc[i,'label1'] = total_data.loc[i,'label2'] total_data.loc[i,'label2'] = total_data.loc[i,'label3'] total_data.loc[i,'label3'] = total_data.loc[i,'label4'] total_data.loc[i,'label4'] = total_data.loc[i,'label5'] total_data.loc[i,'label5'] = None # label processing - if label1 not 1, label 2 not None ,, label1 is None-> remove notidx = (((total_data['label1'] != '1') & (total_data['label2'].notnull())) | total_data['label1'].isnull()) total_data = total_data[~notidx] total_data = total_data.reset_index(drop=True) return total_data if __name__ == '__main__': my_model = load_model("C:\\Users\\user\\Documents\\SEResNet_6class_NewDBv2_Noise\\result\\" + "SEResNet152_6class_lead2_size2000_ver1_2.h5", custom_objects={'relu6': tf.nn.relu6}) lead_1_pkl = '/media/sangil/477A156111D616D6/data/gunguk/konkuk_v2_7_1_lead1.pkl' load_pickle = open(lead_1_pkl, 'rb') load_data = pickle.load(load_pickle) load_pickle.close() load_data = label_processing(load_data) X_l = np.array(load_data.iloc[:, 11:], dtype=float) model = Model(inputs=my_model.input, outputs=my_model.get_layer("global_average_pooling2d_51").output) get_features = model.predict(X_l) num_cluster = 100 kmeans = tf.compat.v1.estimator.experimental.KMeans( num_clusters=num_cluster, use_mini_batch=False, distance_metric='cosine') def input_fn(): return tf.compat.v1.train.limit_epochs( tf.convert_to_tensor(get_features, dtype=tf.float32), num_epochs=1) ####### train ######### num_iterations = 50 for _ in range(num_iterations): kmeans.train(input_fn) cluster_centers = kmeans.cluster_centers() # cosine_similarity def cos_sim(a, b): l2_norm_a = norm(a, axis=1, keepdims=True) l2_norm_b = norm(b, axis=1, keepdims=True) l2_norm_a = np.divide(a, l2_norm_a, where=l2_norm_a != 0) l2_norm_b = np.divide(b, l2_norm_b, where=l2_norm_b != 0) return np.dot(l2_norm_a, l2_norm_b.T) cosine = cos_sim(get_features, cluster_centers) print(cosine.shape) cluster_indices = list(kmeans.predict_cluster_index(input_fn)) # find the index of closest clustering center <file_sep>/ecg/ecg_noise_trainer_sgemented.py import argparse import pickle import time import cv2 import torch from sklearn import preprocessing from torch.autograd import Variable from torchsummary import summary from torchvision.utils import save_image from ecg_wgan_denoiser import Generator, Generator16, Discriminator16 from ecg_wgan_denoiser import Discriminator import numpy as np import pandas as pd import os import matplotlib.pyplot as plt import scipy.signal as sig from scipy.interpolate import splrep, splev parser = argparse.ArgumentParser() parser.add_argument("--n_epochs", type=int, default=20, help="number of epochs of training") parser.add_argument("--batch_size", type=int, default=4, help="size of the batches") parser.add_argument("--lr", type=float, default=0.0005, help="adam: learning rate") parser.add_argument("--b1", type=float, default=0.5, help="adam: decay of first order momentum of gradient") parser.add_argument("--b2", type=float, default=0.999, help="adam: decay of first order momentum of gradient") parser.add_argument("--n_cpu", type=int, default=8, help="number of cpu threads to use during batch generation") parser.add_argument("--latent_dim", type=int, default=250, help="dimensionality of the latent space") parser.add_argument("--img_size", type=int, default=28, help="size of each image dimension") parser.add_argument("--channels", type=int, default=1, help="number of image channels") parser.add_argument("--sample_interval", type=int, default=50, help="interval between image sampling") parser.add_argument("--n_critic", type=int, default=5, help="number of training steps for discriminator per iter") ecg_type= 'normalcor2' # ecg_type= 'testtest' noise_type =0 OUT_PATH = 'Generator'+ ecg_type + str(noise_type) opt = parser.parse_args() print(opt) img_shape = (opt.channels, opt.img_size, opt.img_size) cuda = True if torch.cuda.is_available() else False print(cuda) def compute_gradient_penalty(D, real_samples, fake_samples): """Calculates the gradient penalty loss for WGAN GP""" # Random weight term for interpolation between real and fake samples alpha = Tensor(np.random.random((real_samples.size(0), 1, 1))) # Get random interpolation between real and fake samples interpolates = (alpha * real_samples + ((1 - alpha) * fake_samples)).requires_grad_(True) d_interpolates = D(interpolates) fake = Variable(Tensor(real_samples.shape[0], 1).fill_(1.0), requires_grad=False) # Get gradient w.r.t. interpolates gradients = torch.autograd.grad( outputs=d_interpolates, inputs=interpolates, grad_outputs=fake, create_graph=True, retain_graph=True, only_inputs=True, )[0] gradients = gradients.view(gradients.size(0), -1) # print(gradients.shape ) # print(gradients.norm(2, dim=1)) gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean() return gradient_penalty def seg_signal(data,rpeaks): #return 250, 1d signal with rpeaks # print(data.shape) l = len(rpeaks) seged = np.empty(shape=(l,256),dtype=float) segedList =[] for i in range(l): if rpeaks[i] -56 <0 : l -=1 continue if rpeaks[i] +200 > data.shape[0]: l -=1 break segedList.append( data[rpeaks[i]-56:rpeaks[i]+200].cpu().detach().numpy()) # print(segedList) ss = np.array(segedList,dtype=float) return ss,ss.shape[0] # seg signal and interporlation def seg_signal2(data,rpeaks): #return 250, 1d signal with rpeaks # print(data.shape) l = len(rpeaks) - 1 segedList =[] for i in range(l): if rpeaks[i] - 56 < 0: #l -= 1 continue seg1 = data[rpeaks[i]:rpeaks[i+1]].cpu().detach().numpy() r_range = rpeaks[i + 1] - rpeaks[i] -1 if r_range< 50: continue x0 = np.linspace(0,r_range,r_range+1) # print(len(x0),seg1.shape) spl = splrep(x0, seg1) x1 = np.linspace(0, r_range, 256) y1 = splev(x1, spl) # print ('[seg_signal2] y1.shape:', len(y1)) segedList.append(y1) ss = np.array(segedList,dtype=float) return ss,ss.shape[0] def fill_channel16(data,l_original): # print('filling',data.shape,l_original) if l_original >= 16: return data[0:16] else: newdata = data for i in range (16-l_original): newdata = np.vstack((newdata,data[i%l_original])) return newdata def normalized(a, axis=-1, order=2): l2 = np.atleast_1d(np.linalg.norm(a, order, axis)) l2[l2==0] = 1 return a / np.expand_dims(l2, axis) def correlate(A,B): A_nom = normalized(A) B_nom = normalized(B) dim = len(A.shape) if dim == 2 : n = A.shape[0] corel = 0 for i in range(n): corel += np.max(np.correlate(A_nom[i], B_nom[i], 'full')) corel = corel / n return corel elif dim == 3: pass else: print('[correlate_max] : dimiension is not 2d or 3d') def dot(A,B): A_nom = normalized(A) B_nom = normalized(B) dim = len(A.shape) if dim == 2: n = A.shape[0] dot = 0 for i in range(n): dot += np.dot(A_nom[i], B_nom[i]) dot = dot / n return dot elif dim == 3: pass else: print('[correlate_max] : dimiension is not 2d or 3d') #normalize first lead_1_pkl = '/data/data/gunguk/konkuk_v2_7_1_lead1.pkl' load_pickle = open(lead_1_pkl, 'rb') load_data = pickle.load(load_pickle) load_pickle.close() load_data = load_data[load_data.label1 == '1'] X_real = np.array(load_data.iloc[:, 11:], dtype=np.float32) df= pd.read_csv('../patch_noise_integrated_20201216_noiselabed.csv') df = df [df['nlabel'] == noise_type] X = df.iloc[:,12:2012].to_numpy(dtype=np.float32) ratio_konkuk = 2000/5000 X = cv2.resize(X_real, None, fx=ratio_konkuk, fy=1, interpolation=cv2.INTER_AREA) X = preprocessing.minmax_scale(X, axis=1) * 2 - 1 # X_l = cv2.resize(X_l, None, fx=ratio_konkuk, fy=1, interpolation=cv2.INTER_AREA) # counter = 0 # X = preprocessing.minmax_scale(X_l,axis=1)* 2 - 1 print(np.argwhere(np.isnan(X))) assert not np.any(np.isnan(X)) # X = np.array(X,dtype=np.float) # print(X) generator = Generator16() generator.to('cuda:0') summary(generator, tuple([250])) discriminator = Discriminator16() discriminator.to('cuda:0') summary(discriminator,(16,256)) optimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor iterator_train = torch.utils.data.DataLoader(X, batch_size=opt.batch_size, shuffle=True, pin_memory=True, num_workers=1) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") adversarial_loss = torch.nn.MSELoss() if cuda: generator.cuda() discriminator.cuda() # adversarial_loss.cuda() batches_done = 0 lambda_gp = 1 counter = 0 for epoch in range(opt.n_epochs): # for i, (imgs) in enumerate(data): for i, (imgs) in enumerate(iterator_train): if imgs.shape[0] != opt.batch_size: continue counter += 1 arr3D = imgs.reshape(opt.batch_size,1,2000) from biosppy import storage from biosppy.signals import ecg arr3D_segmented = [] for i in range(opt.batch_size): signal = arr3D[i][0] # process it and plot rpeaks = ecg.ecg(signal=signal, sampling_rate=100., show=False)[2] segmentedsignal,num_seged = seg_signal2(signal,rpeaks) # print(rpeaks,num_seged) if num_seged == 0: print(num_seged) break segmentedsignal16 = fill_channel16(segmentedsignal,num_seged) # segmentedsignal16.reshape(16,256) arr3D_segmented.append(segmentedsignal16) # print(i,opt.batch_size) if num_seged == 0: continue arr3D_segmented = np.array(arr3D_segmented) if len(arr3D_segmented.shape) < 2: continue # print(arr3D_segmented.shape[1]) # if np.isnan(np.sum(arr3D_segmented)): # print('nan!!!' ) # continue arr3D = Tensor(arr3D_segmented) img = arr3D.to(device) real_imgs = Variable(Tensor(img)) # real_imgs = real_imgs.reshape(1,64,64) # priint(real_imgs) # --------------------- # Train Discriminator # --------------------- # print(real_imgs.) optimizer_D.zero_grad() # Sample noise as generator input z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], opt.latent_dim)))) # Generate a batch of images fake_imgs = generator(z) fake_validity = discriminator(fake_imgs) real_validity = discriminator(real_imgs) if counter % 1000 == 0: # print('img show start') imgshow = np.array(real_imgs.cpu(), dtype=float)[0][0] plt.figure(figsize=(20, 4)) plt.plot(imgshow) # plt.imshow(imgshow) plt.title('real image') plt.show() plt.close() imgshow = np.array(real_imgs.cpu(), dtype=float)[0].flatten() plt.figure(figsize=(20, 4)) plt.plot(imgshow) # plt.imshow(imgshow) plt.title('real image') plt.show() plt.close() # print(fake_imgs.shape) npshow = fake_imgs[0][0].cpu().detach().numpy() plt.figure(figsize=(20, 4)) plt.plot(npshow) plt.title('fake image') # plt.imshow(np.array(fake_imgs.cpu(), dtype=float)) plt.show() plt.close() npshow_list = fake_imgs[0].cpu().detach().numpy() npshow= npshow_list.flatten()#reshape((1,-1)) plt.figure(figsize=(20, 4)) plt.plot(npshow) plt.title('fake image') # plt.imshow(np.array(fake_imgs.cpu(), dtype=float)) plt.show() plt.close() # print(real_validity, fake_validity) # Gradient penalty gradient_penalty = compute_gradient_penalty(discriminator, real_imgs.data, fake_imgs.data) # Adversarial loss # d_loss = (-real_validity + -fake_validity) / 2 d_loss = -torch.mean(real_validity) + torch.mean(fake_validity) + lambda_gp * gradient_penalty # print(d_loss.shape) d_loss.backward() optimizer_D.step() optimizer_G.zero_grad() # Train the generator every n_critic steps if counter % opt.n_critic == 0: # ----------------- # Train Generator # ----------------- real_extracted = discriminator.getinermediate() # Generate a batch of images fake_imgs = generator(z) # Loss measures generator's ability to fool the discriminator # Train on fake images fake_validity = discriminator(fake_imgs) subimg = (fake_imgs) - real_imgs l1loss = subimg.norm(1, dim=1).mean() l2loss = subimg.norm(1, dim=2).mean() # print(l1loss) valid = Variable(Tensor(imgs.shape[0], 1).fill_(1.0), requires_grad=False) lsloss = adversarial_loss(fake_validity, valid) fake_extracted = discriminator.getinermediate() # print('extracted :', real_extracted) # print('extracted :', fake_extracted) #g_loss = -torch.mean(fake_validity) + l1loss #g_loss = -torch.mean(fake_validity) + l2loss summer = 0 for i in range(opt.batch_size): corel = correlate(fake_imgs[i].cpu().detach().numpy(), real_imgs[i].cpu().detach().numpy()) summer += corel summer = summer / opt.batch_size summer_dot = 0 for i in range(opt.batch_size): dotter = dot(fake_imgs[i].cpu().detach().numpy(), real_imgs[i].cpu().detach().numpy()) summer_dot += dotter summer_dot = summer_dot / opt.batch_size regulizer = fake_imgs.norm(1, dim=2).mean() # print(regulizer) # print(real_extracted.shape) sub_ext=real_extracted.cpu().detach().numpy()-fake_extracted.cpu().detach().numpy() # print(sub_ext.norm(2, dim=1)) ext_loss = np.linalg.norm(sub_ext,2,1).mean() # print(ext_loss) # g_loss = Variable(Tensor(1).fill_(ext_loss), requires_grad=True) + 0.01*l2loss g_loss = -torch.mean(fake_validity) + l2loss * 0.01 + (1-summer) * 80 # print(g_loss) print('correlsummer : ', summer) with open(OUT_PATH + '_correler.txt', 'a') as the_file: the_file.write(str(summer) + '\n') print('dotsummer : ', summer_dot) with open(OUT_PATH+ '_dotter.txt', 'a') as the_file: the_file.write(str(summer_dot) + '\n') g_loss.backward() optimizer_G.step() print( "[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]" % (epoch, opt.n_epochs, i, 1, d_loss.item(), g_loss.item()) ) with open(OUT_PATH + '_dloss.txt', 'a') as the_file: the_file.write(str( float(d_loss.cpu().detach())) + '\n') with open(OUT_PATH + '_gloss.txt', 'a') as the_file: the_file.write(str( float(g_loss.cpu().detach())) + '\n') # if batches_done % opt.sample_interval == 0: # save_image(fake_imgs.data[:25], "images/%d.png" % batches_done, nrow=5, normalize=True) batches_done += opt.n_critic #for lst img end torch.save(generator.state_dict(), OUT_PATH )<file_sep>/ecg/noise_adder.py import argparse import pickle import time import cv2 import torch from sklearn import preprocessing from torch.autograd import Variable from torchsummary import summary from torchvision.utils import save_image import noise_extractor from ecg_wgan_denoiser import Generator from ecg_wgan_denoiser import Discriminator import numpy as np import pandas as pd import os import matplotlib.pyplot as plt import scipy.signal as sig generator = Generator() noise_type = '0' OUT_PATH = 'Generator'+ str(noise_type) generator.to('cuda:1') model.load_state_dict(torch.load(PATH)) model.eval() N = 1000 list = [] for i in range(N): # Sample noise as generator input z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], opt.latent_dim)))) # Generate a batch of images fake_imgs = generator(z) ar = [0,0,0,0,0,0,0,0,0,0] ar.extend(fake_imgs) list.append(fake_imgs) df = pd.DataFrame(list) df.to_pickle("noise_generated.pkl") <file_sep>/ecg/ecg_wgan_denoiser.py import torchvision from sklearn import preprocessing from torch import nn, autograd import torch import argparse import os import numpy as np import math import matplotlib.pyplot as plt from torch.autograd import Variable from torchsummary import summary from torchvision import datasets import torchvision.transforms as transforms from torchvision.utils import save_image parser = argparse.ArgumentParser() parser.add_argument("--n_epochs", type=int, default=2000, help="number of epochs of training") parser.add_argument("--batch_size", type=int, default=4, help="size of the batches") parser.add_argument("--lr", type=float, default=0.0002, help="adam: learning rate") parser.add_argument("--b1", type=float, default=0.5, help="adam: decay of first order momentum of gradient") parser.add_argument("--b2", type=float, default=0.999, help="adam: decay of first order momentum of gradient") parser.add_argument("--n_cpu", type=int, default=8, help="number of cpu threads to use during batch generation") parser.add_argument("--latent_dim", type=int, default=250, help="dimensionality of the latent space") parser.add_argument("--img_size", type=int, default=64, help="size of each image dimension") parser.add_argument("--channels", type=int, default=1, help="number of image channels") parser.add_argument("--sample_interval", type=int, default=50, help="interval between image sampling") parser.add_argument("--n_critic", type=int, default=5, help="number of training steps for discriminator per iter") opt = parser.parse_args() print(opt) img_shape = (opt.channels, opt.img_size, opt.img_size) cuda = True if torch.cuda.is_available() else False # cuda = False # class Generator(nn.Module): def __init__(self): super(Generator, self).__init__() # self.init_size = opt.img_size // 4 # print( 128 * self.init_size ** 2) self.l1 = nn.Sequential(nn.Linear(opt.latent_dim,64 * 500)) self.conv_blocks = nn.Sequential( nn.BatchNorm1d(256), nn.Upsample(scale_factor=2), nn.Conv1d(256, 128, 9, stride=1, padding=4), nn.BatchNorm1d(128), nn.LeakyReLU(0.2, inplace=True), nn.Upsample(scale_factor=2), nn.Conv1d(128, 32, 9, stride=1, padding=4), nn.BatchNorm1d(32), nn.LeakyReLU(0.2, inplace=True), nn.Upsample(scale_factor=2), nn.Conv1d(32, 8, 9, stride=1, padding=4), nn.BatchNorm1d(8), nn.LeakyReLU(0.2, inplace=True), nn.Upsample(scale_factor=2), nn.Conv1d(8, opt.channels, 9, stride=1, padding=4), nn.BatchNorm1d(1), nn.Tanh(), ) def forward(self, z): out = self.l1(z) out = out.view(out.shape[0], 256, 125) img = self.conv_blocks(out) return img class Discriminator(nn.Module): def __init__(self): super(Discriminator, self).__init__() def discriminator_block(in_filters, out_filters, bn=True): block = [nn.Conv1d(in_filters, out_filters, 9, 2, 4), nn.LeakyReLU(0.2, inplace=True), nn.Dropout(0.25)] if bn: block.append(nn.BatchNorm1d(out_filters)) return block # self.model = nn.Sequential( # *discriminator_block(opt.channels, 64, bn=False), # *discriminator_block(64, 128), # *discriminator_block(128, 256), # *discriminator_block(256, 512), # ) self.model = nn.Sequential( *discriminator_block(opt.channels, 8, bn=False), *discriminator_block(8, 32, bn=False), *discriminator_block(32, 128, bn=False), *discriminator_block(128, 256, bn=False), ) # The height and width of downsampled image # ds_size = opt.img_size // 2 ** 4 ds_size = 2000 // 2** 4 self.adv_layer = nn.Sequential(nn.Linear(125*256 , 1), nn.Sigmoid()) def forward(self, img): out = self.model(img) out = out.view(out.shape[0], -1) validity = self.adv_layer(out) return validity class Generator16(nn.Module): def __init__(self): super(Generator16, self).__init__() # self.init_size = opt.img_size // 4 # print( 128 * self.init_size ** 2) self.l1 = nn.Sequential(nn.Linear(opt.latent_dim,16 * 256)) self.conv_blocks = nn.Sequential( nn.BatchNorm1d(256), nn.Upsample(scale_factor=2), nn.Conv1d(256, 128, 9, stride=1, padding=4), # nn.BatchNorm1d(128), nn.LeakyReLU(0.2, inplace=True), nn.Upsample(scale_factor=2), nn.Conv1d(128, 64, 9, stride=1, padding=4), # nn.BatchNorm1d(64), nn.LeakyReLU(0.2, inplace=True), nn.Upsample(scale_factor=2), nn.Conv1d(64, 32, 9, stride=1, padding=4), # nn.BatchNorm1d(32), nn.LeakyReLU(0.2, inplace=True), nn.Upsample(scale_factor=2), nn.Conv1d(32, 16, 9, stride=1, padding=4), # nn.BatchNorm1d(16), nn.Tanh(), ) def forward(self, z): out = self.l1(z) out = out.view(out.shape[0], 256, 16) img = self.conv_blocks(out) return img class Discriminator16(nn.Module): def __init__(self): super(Discriminator16, self).__init__() def discriminator_block(in_filters, out_filters, bn=True): block = [nn.Conv1d(in_filters, out_filters, 5, 2, 2), nn.LeakyReLU(0.2, inplace=True), nn.Dropout(0.25)] if bn: block.append(nn.BatchNorm1d(out_filters)) return block # self.model = nn.Sequential( # *discriminator_block(opt.channels, 64, bn=False), # *discriminator_block(64, 128), # *discriminator_block(128, 256), # *discriminator_block(256, 512), # ) self.model = nn.Sequential( *discriminator_block(16, 32, bn=False), *discriminator_block(32, 64), *discriminator_block(64, 128), *discriminator_block(128, 256), ) # The height and width of downsampled image # ds_size = opt.img_size // 2 ** 4 ds_size = 256 // 2** 4 self.adv_layer = nn.Sequential(nn.Linear(16*256 , 1), nn.Sigmoid()) def forward(self, img): out = self.model(img) out = out.view(out.shape[0], -1) validity = self.adv_layer(out) self.lastout = out return validity def getinermediate(self): return self.lastout def weights_init_normal(m): classname = m.__class__.__name__ if classname.find("Conv") != -1: torch.nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find("BatchNorm2d") != -1: torch.nn.init.normal_(m.weight.data, 1.0, 0.02) torch.nn.init.constant_(m.bias.data, 0.0) def compute_gradient_penalty(D, real_samples, fake_samples): """Calculates the gradient penalty loss for WGAN GP""" # Random weight term for interpolation between real and fake samples alpha = Tensor(np.random.random((real_samples.size(0), 1, 1, 1))) # Get random interpolation between real and fake samples interpolates = (alpha * real_samples + ((1 - alpha) * fake_samples)).requires_grad_(True) # print(real_samples.shape) # print(fake_samples.shape) d_interpolates = D(interpolates) fake = Variable(Tensor(real_samples.shape[0], 1).fill_(1.0), requires_grad=False) # Get gradient w.r.t. interpolates gradients = autograd.grad( outputs=d_interpolates, inputs=interpolates, grad_outputs=fake, create_graph=True, retain_graph=True, only_inputs=True, )[0] gradients = gradients.view(gradients.size(0), -1) gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean() return gradient_penalty # Loss function adversarial_loss = torch.nn.BCELoss() if __name__ == "__main__": # Initialize generator and discriminator generator = Generator() # summary(generator, tuple([256])) discriminator = Discriminator() # summary(discriminator, (1,28,28)) # exit(0) cuda = False if cuda: generator.cuda() discriminator.cuda() adversarial_loss.cuda() # Initialize weights generator.apply(weights_init_normal) discriminator.apply(weights_init_normal) # Configure data loader os.makedirs("data/mnist", exist_ok=True) import gzip num_images = 1000 image_size = 28 data = np.empty(shape=(num_images,1, image_size, image_size), dtype=np.float32) f = gzip.open('datasets/train-images-idx3-ubyte.gz', 'r') g = gzip.open('datasets/train-labels-idx1-ubyte.gz', 'r') g.read(8) f.read(16) for i in range(num_images): buf_target = g.read(1) buf = f.read(image_size * image_size) buf_data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32) # print(buf_data.shape) buf_data = buf_data.reshape( image_size, image_size) # plt.imshow(buf_data) # plt.show() # if int.from_bytes(buf_target,'big') != 0: # i-=1 # continue data[i] = buf_data.reshape( 1,image_size, image_size) / 256 # data[i] = preprocessing.minmax_scale(data[i] /256) # print(data.shape) # print(buf_target) print(data.shape) # Optimizers optimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) cuda = False Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor iterator_train = torch.utils.data.DataLoader(data, batch_size=32, shuffle=True, pin_memory=True, num_workers=1) # ---------- # Training # ---------- lambda_gp = 10 batches_done = 0 for epoch in range(opt.n_epochs): # for i, (imgs) in enumerate(data): for i, (imgs) in enumerate(iterator_train): # imgs = torch.reshape(imgs[0],(1,28,28)) imgs.cuda # Configure input # print(imgs.shape) real_imgs = Variable(Tensor(imgs)) # --------------------- # Train Discriminator # --------------------- optimizer_D.zero_grad() # Sample noise as generator input z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], opt.latent_dim)))) # Generate a batch of images fake_imgs = generator(z) # print(real_imgs.shape) # Real images real_validity = discriminator(real_imgs) # Fake images fake_validity = discriminator(fake_imgs) print(real_validity,fake_validity) # Gradient penalty gradient_penalty = compute_gradient_penalty(discriminator, real_imgs.data, fake_imgs.data) # Adversarial loss # d_loss = (-real_validity + -fake_validity) / 2 d_loss = -torch.mean(real_validity) + torch.mean(fake_validity) + lambda_gp * gradient_penalty # print(d_loss.shape) d_loss.backward() optimizer_D.step() optimizer_G.zero_grad() # Train the generator every n_critic steps if i % opt.n_critic == 0: # ----------------- # Train Generator # ----------------- # Generate a batch of images fake_imgs = generator(z) # Loss measures generator's ability to fool the discriminator # Train on fake images fake_validity = discriminator(fake_imgs) g_loss = -torch.mean(fake_validity) print(g_loss.shape) g_loss.backward() optimizer_G.step() print( "[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]" % (epoch, opt.n_epochs, i, 1, d_loss.item(), g_loss.item()) ) # if batches_done % opt.sample_interval == 0: # save_image(fake_imgs.data[:25], "images/%d.png" % batches_done, nrow=5, normalize=True) batches_done += opt.n_critic<file_sep>/ecg/adder.py from itertools import chain import torch from torch.autograd import Variable from ecg_wgan_denoiser import Generator16 import numpy as np import os import matplotlib.pyplot as plt def flatten(listOfLists): "Flatten one level of nesting" return chain.from_iterable(listOfLists) cuda = True if torch.cuda.is_available() else False generator = Generator16() noise_type = '3' PATH = 'Generatornormalcor20'#+ str(noise_type) imgPATH = PATH +'_img' generator.to('cuda:0') generator.load_state_dict(torch.load(PATH)) generator.eval() Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor latent_dim = 256 os.makedirs(imgPATH) N = 20 list = [] for i in range(N): # Sample noise as generator input z = Variable(Tensor(np.random.normal(0, 1, (1, 250)))) # Generate a batch of images fake_imgs = generator(z) # ar = [0,0,0,0,0,6,0,0,0,0,0] # ar.extend(flatten(flatten(fake_imgs.tolist()))) # list.append(ar) # print(ar) npshow_list = fake_imgs[0].cpu().detach().numpy() npshow = npshow_list.flatten() # reshape((1,-1)) plt.figure(figsize=(20, 4)) plt.plot(npshow) plt.title('fake image'+ str(i)) plt.savefig(imgPATH+'/fake'+str(i) + '.png') # plt.imshow(np.array(fake_imgs.cpu(), dtype=float)) plt.show() plt.close() # df = pd.DataFrame(list,columns= ['filename', 'patient_id', 'hospital_name', 'method', # 'lead', 'label1', 'label2', 'label3', # 'label4', 'label5']) # df = pd.DataFrame(list) # df.to_pickle('noise_generated'+noise_type+'.pkl') <file_sep>/ecg/ecg_noise_trainer.py import argparse import pickle import cv2 import torch from sklearn import preprocessing from torch.autograd import Variable from torchsummary import summary from ecg_wgan_denoiser import Generator from ecg_wgan_denoiser import Discriminator import numpy as np import pandas as pd import matplotlib.pyplot as plt parser = argparse.ArgumentParser() parser.add_argument("--n_epochs", type=int, default=20000, help="number of epochs of training") parser.add_argument("--batch_size", type=int, default=4, help="size of the batches") parser.add_argument("--lr", type=float, default=0.0002, help="adam: learning rate") parser.add_argument("--b1", type=float, default=0.5, help="adam: decay of first order momentum of gradient") parser.add_argument("--b2", type=float, default=0.999, help="adam: decay of first order momentum of gradient") parser.add_argument("--n_cpu", type=int, default=8, help="number of cpu threads to use during batch generation") parser.add_argument("--latent_dim", type=int, default=250, help="dimensionality of the latent space") parser.add_argument("--img_size", type=int, default=28, help="size of each image dimension") parser.add_argument("--channels", type=int, default=1, help="number of image channels") parser.add_argument("--sample_interval", type=int, default=50, help="interval between image sampling") parser.add_argument("--n_critic", type=int, default=5, help="number of training steps for discriminator per iter") noise_type =0 OUT_PATH = 'Generator'+ str(noise_type) opt = parser.parse_args() print(opt) img_shape = (opt.channels, opt.img_size, opt.img_size) cuda = True if torch.cuda.is_available() else False print(cuda) def compute_gradient_penalty(D, real_samples, fake_samples): """Calculates the gradient penalty loss for WGAN GP""" # Random weight term for interpolation between real and fake samples alpha = Tensor(np.random.random((real_samples.size(0), 1, 1))) # Get random interpolation between real and fake samples # print(real_samples.shape) # print(fake_samples.shape) interpolates = (alpha * real_samples + ((1 - alpha) * fake_samples)).requires_grad_(True) # print(interpolates.shape) # print(real_samples.shape) # print(fake_samples.shape) d_interpolates = D(interpolates) fake = Variable(Tensor(real_samples.shape[0], 1).fill_(1.0), requires_grad=False) # Get gradient w.r.t. interpolates gradients = torch.autograd.grad( outputs=d_interpolates, inputs=interpolates, grad_outputs=fake, create_graph=True, retain_graph=True, only_inputs=True, )[0] gradients = gradients.view(gradients.size(0), -1) # print(gradients.shape ) print(gradients.norm(2, dim=1)) gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean() return gradient_penalty def normalized(a, axis=-1, order=2): l2 = np.atleast_1d(np.linalg.norm(a, order, axis)) l2[l2==0] = 1 return a / np.expand_dims(l2, axis) def correlate(A,B): A_nom = normalized(A) B_nom = normalized(B) dim = len(A.shape) if dim == 2 : n = A.shape[0] corel = 0 for i in range(n): corel += np.max(np.correlate(A_nom[i], B_nom[i], 'full')) return corel elif dim == 3: pass else: print('[correlate_max] : dimiension is not 2d or 3d') #normalize first lead_1_pkl = '/data/data/gunguk/konkuk_v2_7_1_lead1.pkl' load_pickle = open(lead_1_pkl, 'rb') load_data = pickle.load(load_pickle) load_pickle.close() load_data = load_data[load_data.label1 == '1'] X_real = np.array(load_data.iloc[:, 11:], dtype=np.float32) df= pd.read_csv('../patch_noise_integrated_20201216_noiselabed.csv') df = df [df['nlabel'] == noise_type] X = df.iloc[:,12:2012].to_numpy(dtype=np.float32) ratio_konkuk = 2000/5000 X = cv2.resize(X_real, None, fx=ratio_konkuk, fy=1, interpolation=cv2.INTER_AREA) OUT_PATH = 'Generator_normal' X = preprocessing.minmax_scale(X, axis=1) * 2 - 1 # X_l = cv2.resize(X_l, None, fx=ratio_konkuk, fy=1, interpolation=cv2.INTER_AREA) # counter = 0 # X = preprocessing.minmax_scale(X_l,axis=1)* 2 - 1 print(np.argwhere(np.isnan(X))) assert not np.any(np.isnan(X)) # X = np.array(X,dtype=np.float) # print(X) generator = Generator() generator.to('cuda:0') summary(generator, tuple([250])) discriminator = Discriminator() discriminator.to('cuda:0') summary(discriminator,(1,2000)) optimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor iterator_train = torch.utils.data.DataLoader(X, batch_size=opt.batch_size, shuffle=True, pin_memory=True, num_workers=1) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") adversarial_loss = torch.nn.MSELoss() if cuda: generator.cuda() discriminator.cuda() # adversarial_loss.cuda() batches_done = 0 lambda_gp = 1 counter = 0 for epoch in range(opt.n_epochs): # for i, (imgs) in enumerate(data): for i, (imgs) in enumerate(iterator_train): if imgs.shape[0] != opt.batch_size: continue counter += 1 arr3D = imgs.reshape(opt.batch_size,1,2000) # arr3D = np.repeat (imgs.reshape(1,1,2000), 1,axis=1) # # scaler = 1.000 # for i in range(64): # # arr3D[0,i,:] = arr3D[0,i,:] * scaler # arr3D[0,i,:] = torch.from_numpy(np.roll(arr3D[0,i,:],i) * scaler) # scaler -= 0.001 # print(arr3D.shape) img = arr3D.to(device) real_imgs = Variable(Tensor(img)) # real_imgs = real_imgs.reshape(1,64,64) # priint(real_imgs) # --------------------- # Train Discriminator # --------------------- # print(real_imgs.) optimizer_D.zero_grad() # Sample noise as generator input z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], opt.latent_dim)))) # Generate a batch of images fake_imgs = generator(z) # print(real_imgs.shape) # Real images real_validity = discriminator(real_imgs) # Fake images # print(real_validity.shape) # print(fake_imgs.shape) fake_validity = discriminator(fake_imgs) # print(fake_validity) imgshow = np.array(real_imgs.cpu(), dtype=float)[0][0] # print(imgshow) if counter % 1000 == 0: plt.plot(imgshow) # plt.imshow(imgshow) plt.title('real image') plt.figure(figsize=(20, 4)) plt.show() # print(fake_imgs.shape) npshow = fake_imgs[0][0].cpu().detach().numpy() # npshow = np.array((npshow+1)*128, dtype=int) # npshow = npshow.reshape(64,64,1) # print(npshow.shape) # plt.imshow(npshow) plt.figure(figsize=(20, 4)) plt.plot(npshow) plt.title('fake image') # plt.imshow(np.array(fake_imgs.cpu(), dtype=float)) plt.show() # print(real_validity, fake_validity) # Gradient penalty gradient_penalty = compute_gradient_penalty(discriminator, real_imgs.data, fake_imgs.data) # Adversarial loss # d_loss = (-real_validity + -fake_validity) / 2 d_loss = -torch.mean(real_validity) + torch.mean(fake_validity) + lambda_gp * gradient_penalty # print(d_loss.shape) d_loss.backward() optimizer_D.step() optimizer_G.zero_grad() # Train the generator every n_critic steps if counter % opt.n_critic == 0: # ----------------- # Train Generator # ----------------- # Generate a batch of images fake_imgs = generator(z) # Loss measures generator's ability to fool the discriminator # Train on fake images fake_validity = discriminator(fake_imgs) subimg = (fake_imgs) - real_imgs l1loss = subimg.norm(1, dim=1).mean() # print(l1loss) valid = Variable(Tensor(imgs.shape[0], 1).fill_(1.0), requires_grad=False) lsloss = adversarial_loss(fake_validity, valid) lambda_l1 = 1 summer = 0 for i in range(opt.batch_size): fake_img_cpu = fake_imgs[i][0].cpu().detach().numpy() real_img_cpu = real_imgs[i][0].cpu().detach().numpy() corel = correlate(fake_imgs[i].cpu().detach().numpy(),real_imgs[i][0].cpu().detach().numpy()) summer += corel summer = summer / opt.batch_size print('corelsummer : ',summer) with open('correler.txt', 'a') as the_file: the_file.write(str(summer)) g_loss = lsloss +l1loss * lambda_l1 g_loss = -torch.mean(fake_validity) + l1loss # print(g_loss) # print(g_loss.shape) g_loss.backward() optimizer_G.step() print( "[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]" % (epoch, opt.n_epochs, i, 1, d_loss.item(), g_loss.item()) ) # if batches_done % opt.sample_interval == 0: # save_image(fake_imgs.data[:25], "images/%d.png" % batches_done, nrow=5, normalize=True) batches_done += opt.n_critic #for lst img end torch.save(generator.state_dict(), OUT_PATH )
43cca8550d3a7b755a9dfb13916356a774984d06
[ "Python" ]
6
Python
sangil-huinno/ecg_gan
dc0681a0e28ae19912a53b763c7bfe686a5532bc
ae6a47a09284e46dbc05974e69ddf19af245e173
refs/heads/master
<repo_name>mrwizard82d1/protein_tracker_java<file_sep>/README.md # protein_tracker_java Java code from PluralSight course "Creating Acceptance Tests with FitNesse" An implementation of the demo code for this class using Java. <file_sep>/src/com/cjl_magistri/protein_tracker/HistoryItem.java package com.cjl_magistri.protein_tracker; /** * Created by ljones on 4/11/2015. */ public class HistoryItem { private final int _historyId; private final int _amount; private final String _operation; private final int _total; public HistoryItem(int historyId, int amount, String operator, int total) { _historyId = historyId; _amount = amount; _operation = operator; _total = total; } } <file_sep>/src/com/cjl_magistri/protein_tracker/fit/TrackingServiceSetupFixture.java package com.cjl_magistri.protein_tracker.fit; import com.cjl_magistri.protein_tracker.tests.TrackingServiceSUT; import fitlibrary.SetUpFixture; /** * Created by ljones on 4/12/2015. * * This class initialize the tracking service prior to executing tests. * */ public class TrackingServiceSetupFixture extends SetUpFixture { public void reset (boolean isResetting) { if (isResetting) { TrackingServiceSUT.INSTANCE.reset(); } } } <file_sep>/src/com/cjl_magistri/protein_tracker/fit/TrackingServiceDoFixture.java package com.cjl_magistri.protein_tracker.fit; import com.cjl_magistri.protein_tracker.TrackingService; import com.cjl_magistri.protein_tracker.tests.TrackingServiceSUT; import fitlibrary.DoFixture; /** * Created by ljones on 4/12/2015. * * This class implements the "do fixture" (a script or scenario) on the * test page: * | set goal | 100 | * | add | 5 | times with | 10 | * | total is | 50 | * | add |1 | times with | 50 | * | total is | 100 | * | goal is met | * | total is | 150 | * * When run, FitNesse tells us the that these members might be missing: * - public Type setGoal(Type1 arg1) { } * - public Type addTimesWith(Type1 arg1, Type2 arg2) { } * - public Type totalIs(Type1 arg1) { } * - public Type goalIsMet() { } * */ public class TrackingServiceDoFixture extends DoFixture { private TrackingService _sut = TrackingServiceSUT.INSTANCE.sut(); public void setGoal(int value) { _sut.setGoal(value); } public void addTimesWith(int count, int amount) { for(int i = 0; i < count; i++) { _sut.addProtein(amount); } } public boolean totalIs(int expectedTotal) { return (expectedTotal == _sut.getTotal()); } public boolean goalIsMet() { return (_sut.isGoalMet()); } } <file_sep>/src/com/cjl_magistri/protein_tracker/tests/TrackingServiceSUT.java package com.cjl_magistri.protein_tracker.tests; import com.cjl_magistri.protein_tracker.TrackingService; /** * Created by ljones on 4/11/2015. * * This class simplifies some testing tasks such as retaining state * between test runs. * * I have made it an enum as recommended by <NAME> in the * Pluralsight module 2. * */ public enum TrackingServiceSUT { // Only contains a single enumeration. INSTANCE; // Java enums can have state, .... private static TrackingService _trackingService = new TrackingService(); // ... a method to return the subject under test, ... public TrackingService sut() { return _trackingService; } // ... and to reset the SUT to a new instance. public void reset() { _trackingService = new TrackingService(); } }
182644318c98ed11ed7978622eab9b131a09f6f5
[ "Markdown", "Java" ]
5
Markdown
mrwizard82d1/protein_tracker_java
6bbbd1e7aa878f776792c90b2924b92a43771c0f
988d083b03476b8a293b1fb1e6612c5bf1a0bc0c
refs/heads/master
<repo_name>Marcus-Jon/IoT<file_sep>/AWS_SDK/raspberry_pi_sub.py # Raspberry Pi MQTT subscriber using AWS import ssl from matplotlib import pyplot as plt import numpy as np from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient import json def customCallback(client, userdata, message): print "new message received" print message.topic print message.payload def cert_assignment(): MQTTclient = AWSIoTMQTTClient("rasp_pi_sub") Shadowclient = AWSIoTMQTTShadowClient("rasp_pi_sub_shadow") MQTTclient.configureEndpoint("endpoint", 8883) Shadowclient.configureEndpoint("endpoint", 8883) MQTTclient.configureCredentials("rootCA.pem", "private key", "certificate") Shadowclient.configureCredentials("rootCA.pem", "private key", "certificate") return MQTTclient, Shadowclient def sub_MQTT(client, topic): client.connect() while True: client.subscribe(topic, 1, customCallback) client.disconnect() def sub_shadow(shadow_client): shadowclient = shadow_client.getMQTTConnection() shadowclient.connect() while True: shadowclient.subscribe("shadow update accepted topic", 1, customCallback) shadowclient.disconnect() def main(): print "MQTT subscriber" topic = "test_pi" client, shadow_client = cert_assignment() sub_shadow(shadow_client) #sub_MQTT(client, topic) if __name__ == '__main__': main() <file_sep>/AWS_SDK/raspberry_pi_pub.py # Raspberry Pi MQTT publisher using AWS import ssl from matplotlib import pyplot as plt import numpy as np from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient import json def cert_assignment(): MQTTclient = AWSIoTMQTTClient("rasp_pi") Shadowclient = AWSIoTMQTTShadowClient("rasp_pi_shadow") MQTTclient.configureEndpoint("endpoint", 8883) Shadowclient.configureEndpoint("endpoint", 8883) MQTTclient.configureCredentials("rootCA.pem", "private key", "certificate") Shadowclient.configureCredentials("rootCA.pem", "private key", "certificate") return MQTTclient, Shadowclient def update_shadow(client): shadow_state = {} shadow_state = {"state": {"reported": {"color": "green"}}} shadow_js = json.dumps(shadow_state) client = client.getMQTTConnection() client.connect() client.publish("shadow update topic", shadow_js, 1) client.disconnect() def connect(MQTTclient, topic, payload): MQTTclient.connect() MQTTclient.publish(topic, payload, 0) MQTTclient.disconnect() def main(): print 'MQTT Publisher' client, shadowclient = cert_assignment() topic = "test_pi" payload = {} payload['Allomancy'] = [] payload['Allomancy'].append({'Iron': 'Pull', 'Steel': 'Push', 'Copper': 'Pull'}) js = json.dumps(payload) with open('data.json', 'w') as outfile: json.dump(payload, outfile, indent = 4) connect(client, topic, js) #update_shadow(shadowclient) if __name__ == '__main__': main() <file_sep>/README.md # Internet of Things #### Programs created for the connection of a Raspberry Pi to AWS, using the AWS SDK _____________________________________________________________________________________ The AWS_SDK folder contains to python files, one for publishing to the AWS IoT core and the other for subscribing to it. The end_device python program is used to publish an update to a device shadow which will cause a connected device to take a picture. The raspberry_pi_device file is designed to be run on a raspberry pi with a connected camera. It will wait for updates to the device shadow, and when one is detected it will take a photo and upload it to an S3 bucket. <file_sep>/rasp_pi_device.py import ssl from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient import json from time import sleep import PIL as image from picamera import PiCamera as pc from boto.s3.connection import S3Connection from boto.s3.key import Key def customCallback(client, userdata, message): print message.topic print message.payload callback_state = message.payload[36:40] pi = rasp_pi() print 'state: ', callback_state if callback_state == 'True': global state state = callback_state class rasp_pi: def __init__(self): pass def assign_certificates(self): client = AWSIoTMQTTClient("client id") client.configureEndpoint("your endpoint", 8883) client.configureCredentials("rootCA.pem", "private key", "certificate") client.configureOfflinePublishQueueing(-1) return client def assign_shadow_certificates(self): shadow_client = AWSIoTMQTTShadowClient("client id") shadow_client.configureEndpoint("your endpoint", 8883) shadow_client.configureCredentials("rootCA.pem", "private key", "certificate") return shadow_client def send_image(self, client): # Connect to MQTT broker to publish current status. topic = "topic name" client.connect() # upload file to the s3 bucket. # get keys from file key_file = open('keys.txt', 'r') keys = key_file.readlines() access_key = keys[0] secret_key = keys[1] access_key = access_key.strip() # connect to S3 bucket. connection = S3Connection(access_key, secret_key) bucket = connection.get_bucket('bucket name') key = Key(bucket) key.key = ('key name') key.set_contents_from_filename('filename') # payload for notification. payload = {} payload = {"state":{"file": "uploaded"}} payload = json.dumps(payload) client.publish(topic, payload, 1) client.disconnect() def take_image(self): # take image with raspberry pi camera. camera = pc() camera.resolution = (1024, 768) camera.start_preview() sleep(2) camera.capture('filename') client = self.assign_certificates() self.send_image(client) def check_update(self, shadow_client): running = True global state payload = {} payload = {"state": {"reported": {"take_photo":"idle"}}} shadow_payload = json.dumps(payload) shadow_client = shadow_client.getMQTTConnection() shadow_client.configureOfflinePublishQueueing(-1) shadow_client.connect() while running == True: shadow_client.publish("$aws/things/thing name/shadow/get", "", 1) shadow_client.subscribe("$aws/things/thing name/shadow/get/accepted", 1, customCallback) shadow_state = state if shadow_state == "True": shadow_client.publish("$aws/things/thing name/shadow/update", shadow_payload, 1) print 'state has been changed to idle' state = "idle" self.take_image() running = False shadow_client.disconnect() def main(): pi = rasp_pi() global state state = "idle" shadow_client = pi.assign_shadow_certificates() pi.check_update(shadow_client) if __name__ == '__main__': main() <file_sep>/end_device.py import ssl from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient import json from boto.s3.connection import S3Connection from boto.s3.key import Key from PIL import Image, ImageDraw, ExifTags, ImageColor, ImageFont import boto3 from time import sleep def assign_certificates(): # assign the certificates for the connection to AWS IoT. client = AWSIoTMQTTClient("client id") client.configureEndpoint("your endpoint", 8883) client.configureCredentials("rootCA.pem", "private key", "certificate") return client def assign_shadow_certificates(): # assign the certificates for the connection to the device shadow on the IoT core. shadowclient = AWSIoTMQTTShadowClient("client id") shadowclient.configureEndpoint("your endpoint", 8883) shadowclient.configureCredentials("rootCA.pem", "private key", "certificate") return shadowclient def get_keys(): key_file = open('keys.txt', 'r') keys = key_file.readlines() access_key = keys[0] secret_key = keys[1] access_key.strip() return access_key, secret_key def get_image(): # get the image stored on the S3 bucket, and save it to a local file. connection = S3Connection() bucket = connection.get_bucket('S3 bucket name') key = Key(bucket) key.key = ('test') key.get_contents_to_filename('filename') def update_shadow(): # send an update to the device shadow to get the other device to take the picture. shadow_client = assign_shadow_certificates() shadow_state = {} shadow_state = {"state": {"reported": {"take_photo": "True"}}} shadow_payload = json.dumps(shadow_state) shadow_client = shadow_client.getMQTTConnection() shadow_client.connect() shadow_client.publish("$aws/things/thing_name/shadow/update", shadow_payload, 1) shadow_client.disconnect() def detect_label(bucket, photo): # using the rekognition service to perform label detection on the stored image. rekognition = boto3.client('rekognition', region_name = 'region') response = rekognition.detect_labels(Image={'S3Object':{'Bucket': bucket, 'Name': photo}}, MaxLabels = 10) # call to get image. get_image() # open the image using PIL so that bounding boxes can be drawn to it. image = Image.open('filename') img_width, img_height = image.size draw = ImageDraw.Draw(image) print "" print "Detected labels for " + photo print "" # print the results of the labels that have been detected in the image. for label in response['Labels']: print 'label: ' + label['Name'] print 'confidence: ' + str(label['Confidence']) # draw the bounding boxes. if 'Instances' in label: for instance in label['Instances']: box = instance['BoundingBox'] left = img_width * box['Left'] top = img_height * box['Top'] width = img_width * box['Width'] height = img_height * box['Height'] points = ((left, top), (left + width, top), (left + width, top + height), (left, top + height), (left, top)) draw.line(points, fill = '#00d400', width = 2) draw.text((left, top), label['Name'], (255, 255, 255)) image.show() def user_function(): user_input = raw_input("take_photo? ") if user_input == 'y': update_shadow() sleep(10) detect_label('bucket name','key') def main(): user_function() if __name__ == '__main__': main()
809c4d8a8d98592a9b271d6e7cfa9ece96d70947
[ "Markdown", "Python" ]
5
Python
Marcus-Jon/IoT
05e8e90dd7e84d204c1d42793f568cd6879e9e82
1bbc185ae3bf70bd7c79d3ab6380c8d9a07ead57
refs/heads/main
<repo_name>nadeemhaj/ERP-Spring-Boot-Angular-Microservices<file_sep>/hr_service/src/main/java/com/programming/techie/repository/EmployeeRepository.java package com.programming.techie.repository; import com.programming.techie.model.Employee; import org.springframework.data.jpa.repository.JpaRepository; public interface EmployeeRepository extends JpaRepository<Employee, Long> { } <file_sep>/finance_service/src/main/java/com/programming/techie/model/Transaction_in.java package com.programming.techie.model; import javax.persistence.*; import java.util.Date; import java.util.List; @Entity @Table(name = "transaction_in") public class Transaction_in { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "date") private Date date; @Column(name = "amount") private float amount; @OneToMany(mappedBy="transaction") private List<Offer_approval> offer_approvalList; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public float getAmount() { return amount; } public void setAmount(float amount) { this.amount = amount; } public List<Offer_approval> getOffer_approvalList() { return offer_approvalList; } public void setOffer_approvalList(List<Offer_approval> offer_approvalList) { this.offer_approvalList = offer_approvalList; } } <file_sep>/hr_service/src/main/resources/application.properties spring.application.name=hr_service server.port=6060 spring.cloud.config.uri=http://localhost:8888 <file_sep>/angular app/src/app/app.module.ts import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {HttpClientModule} from '@angular/common/http'; import {RouterModule} from '@angular/router'; import {ToastrModule} from 'ngx-toastr'; import {AppComponent} from './app.component'; import {AdminLayoutComponent} from './layouts/admin-layout/admin-layout.component'; import {AuthLayoutComponent} from './layouts/auth-layout/auth-layout.component'; import {NgbModule} from '@ng-bootstrap/ng-bootstrap'; import {AppRoutingModule} from './app-routing.module'; import {ComponentsModule} from './components/components.module'; import {ProductDashboardComponent} from './pages/products/productDashboard/ProductDashboard.component'; import {ProfileComponent} from './pages/profile/profile.component'; import {BoardModeratorComponent} from './pages/board-moderator/board-moderator.component'; import {BoardUserComponent} from './pages/board-user/board-user.component'; import {BoardAdminComponent} from './pages/board-admin/board-admin.component'; import {HomeComponent} from './pages/home/home.component'; import {RegisterComponent} from './pages/register/register.component'; import {LoginComponent} from './pages/login/login.component'; import { StockHandlerComponent } from './pages/products/stock-handler/stock-handler.component'; import { WarehousesComponent } from './pages/warehouses/warehouses.component'; import { CreateWarehouseComponent } from './pages/warehouses/create-warehouse/create-warehouse.component'; import { StockMovementsComponent } from './pages/warehouses/stock-movements/stock-movements.component'; import { ReplenishmentComponent } from './pages/warehouses/replenishment/replenishment.component'; import { TiersComponent } from './pages/tiers/tiers.component'; import { CreateTiersComponent } from './pages/tiers/create-tiers/create-tiers.component'; import { CreateSuplierComponent } from './pages/tiers/create-suplier/create-suplier.component'; import { CreateClientComponent } from './pages/tiers/create-client/create-client.component'; import { TiersDashboardComponent } from './pages/tiers/tiers-dashboard/tiers-dashboard.component'; import { WarehouseDashboardComponent } from './pages/warehouses/warehouse-dashboard/warehouse-dashboard.component'; import { UsersComponent } from './pages/users/users.component'; import { CompanyComponent } from './pages/company/company.component'; @NgModule({ imports: [ BrowserAnimationsModule, FormsModule, HttpClientModule, ComponentsModule, NgbModule, RouterModule, AppRoutingModule, ToastrModule.forRoot() ], declarations: [ AppComponent, AdminLayoutComponent, AuthLayoutComponent, ProductDashboardComponent, AppComponent, LoginComponent, RegisterComponent, HomeComponent, BoardAdminComponent, BoardUserComponent, BoardModeratorComponent, ProfileComponent, StockHandlerComponent, WarehousesComponent, CreateWarehouseComponent, StockMovementsComponent, ReplenishmentComponent, TiersComponent, CreateTiersComponent, CreateSuplierComponent, CreateClientComponent, TiersDashboardComponent, WarehouseDashboardComponent, UsersComponent, CompanyComponent ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/angular app/src/app/pages/warehouses/stock-movements/stock-movements.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-stock-movements', templateUrl: './stock-movements.component.html', styleUrls: ['./stock-movements.component.scss'] }) export class StockMovementsComponent implements OnInit { constructor() { } ngOnInit(): void { } } <file_sep>/hr_service/src/main/java/com/programming/techie/repository/LeavesRepository.java package com.programming.techie.repository; import com.programming.techie.model.Leave_type; import com.programming.techie.model.Leaves; import org.springframework.data.jpa.repository.JpaRepository; public interface LeavesRepository extends JpaRepository<Leaves, Long> { } <file_sep>/finance_service/src/main/java/com/programming/techie/model/Transaction_out.java package com.programming.techie.model; import javax.persistence.*; import java.util.Date; import java.util.List; @Entity @Table(name = "transaction_out") public class Transaction_out { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "date") private Date date; @Column(name = "amount") private float amount; @OneToMany(mappedBy="transaction") private List<Salary_approval> salary_approvalList; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public float getAmount() { return amount; } public void setAmount(float amount) { this.amount = amount; } public List<Salary_approval> getSalary_approvalList() { return salary_approvalList; } public void setSalary_approvalList(List<Salary_approval> salary_approvalList) { this.salary_approvalList = salary_approvalList; } } <file_sep>/angular app/src/app/layouts/admin-layout/admin-layout.routing.ts import {Routes} from '@angular/router'; import {DashboardComponent} from '../../pages/dashboard/dashboard.component'; import {IconsComponent} from '../../pages/icons/icons.component'; import {MapComponent} from '../../pages/map/map.component'; import {NotificationsComponent} from '../../pages/notifications/notifications.component'; import {ProductDashboardComponent} from '../../pages/products/productDashboard/ProductDashboard.component'; import {TablesComponent} from '../../pages/tables/tables.component'; import {TypographyComponent} from '../../pages/typography/typography.component'; import {CreateProductComponent} from '../../pages/products/createProduct/createProduct.component'; import {CreateWarehouseComponent} from '../../pages/warehouses/create-warehouse/create-warehouse.component'; import {ReplenishmentComponent} from '../../pages/warehouses/replenishment/replenishment.component'; import {StockMovementsComponent} from '../../pages/warehouses/stock-movements/stock-movements.component'; import {CreateTiersComponent} from '../../pages/tiers/create-tiers/create-tiers.component'; import {CreateSuplierComponent} from '../../pages/tiers/create-suplier/create-suplier.component'; import {CreateClientComponent} from '../../pages/tiers/create-client/create-client.component'; import {WarehouseDashboardComponent} from '../../pages/warehouses/warehouse-dashboard/warehouse-dashboard.component'; import {TiersDashboardComponent} from '../../pages/tiers/tiers-dashboard/tiers-dashboard.component'; import {UsersComponent} from '../../pages/users/users.component'; import {CompanyComponent} from '../../pages/company/company.component'; // import { RtlComponent } from "../../pages/rtl/rtl.component"; export const AdminLayoutRoutes: Routes = [ {path: 'dashboard', component: DashboardComponent}, {path: 'icons', component: IconsComponent}, {path: 'maps', component: MapComponent}, {path: 'users', component: UsersComponent}, {path: 'company', component: CompanyComponent}, {path: 'notifications', component: NotificationsComponent}, {path: 'products', component: ProductDashboardComponent}, {path: 'tables', component: TablesComponent}, {path: 'typography', component: TypographyComponent}, {path: 'products', component: ProductDashboardComponent}, {path: 'products/create', component: CreateProductComponent}, {path: 'warehouses', component: WarehouseDashboardComponent}, {path: 'warehouses/create', component: CreateWarehouseComponent}, {path: 'warehouses/replenishment', component: ReplenishmentComponent}, {path: 'warehouses/stock-movements', component: StockMovementsComponent}, {path: 'tiers', component: TiersDashboardComponent}, {path: 'tiers/create', component: CreateTiersComponent}, {path: 'tiers/supliers/create', component: CreateSuplierComponent}, {path: 'tiers/clients/create', component: CreateClientComponent} // { path: "rtl", component: RtlComponent } ]; <file_sep>/docker-compose.yml version: '3' services: discovery: image: zakariaelattar/register_microservice:latest ports: - 8761:8761 depends_on: - config config: image: zakariaelattar/config_microservice:latest environment: - JAVA_OPTS= -DEUREKA_SERVER=http://discovery:8761/eureka ports: - 8888:8888 database: image: zakariaelattar/db_microservice:latest environment: - JAVA_OPTS= -DEUREKA_SERVER=http://discovery:8761/eureka depends_on: - discovery - config proxy: image: zakariaelattar/proxy_microservice:latest environment: - JAVA_OPTS= - DEUREKA_SERVER=http://discovery:8761/eureka restart: on-failure depends_on: - discovery - config ports: - 8088:8088 Product: image: zakariaelattar/db_microservice:latest environment: - JAVA_OPTS= - DEUREKA_SERVER=http://discovery:8761/eureka depends_on: - discovery - config <file_sep>/angular app/src/app/components/sidebar/sidebar.component.ts import {Component, OnInit} from '@angular/core'; declare interface RouteInfo { path: string; title: string; rtlTitle: string; icon: string; class: string; } export const ROUTES: RouteInfo[] = [ { path: '/dashboard', title: 'Dashboard', rtlTitle: 'لوحة القيادة', icon: 'icon-chart-pie-36', class: '' }, { path: '/icons', title: 'Users', rtlTitle: 'الرموز', icon: 'icon-single-02', class: '' }, { path: '/company', title: 'Company', rtlTitle: 'خرائط', icon: 'icon-components', class: '' }, { path: '/users', title: 'Customers and Suppliers', rtlTitle: 'إخطارات', icon: 'icon-link-72', class: '' }, { path: '/products', title: 'Products and services', rtlTitle: 'ملف تعريفي للمستخدم', icon: 'icon-bag-16', class: 'dropdown' }, { path: '/products/create', title: 'Add product', rtlTitle: 'ملف تعريفي للمستخدم', icon: 'icon-bag-16', class: 'dropdown-item' }, { path: '/warehouses', title: 'Warehouses', rtlTitle: 'ملف تعريفي للمستخدم', icon: 'icon-bag-16', class: 'dropdown' }, { path: '/warehouses/create', title: 'add a warehouse', rtlTitle: 'ملف تعريفي للمستخدم', icon: 'icon-bag-16', class: '' }, { path: '/warehouses/replenishment', title: 'Replenishment', rtlTitle: 'ملف تعريفي للمستخدم', icon: 'icon-bag-16', class: 'dropdown-item' }, { path: '/warehouses/stock-movements', title: 'Stock movements', rtlTitle: 'ملف تعريفي للمستخدم', icon: 'icon-bag-16', class: 'dropdown-item' }, { path: '/tiers', title: 'Tiers', rtlTitle: 'ملف تعريفي للمستخدم', icon: 'icon-bag-16', class: '' }, { path: '/tiers/create', title: 'Add a tiers', rtlTitle: 'ملف تعريفي للمستخدم', icon: 'icon-bag-16', class: '' }, { path: '/tiers/suplier/create', title: 'Add a suplier', rtlTitle: 'ملف تعريفي للمستخدم', icon: 'icon-bag-16', class: '' }, { path: 'tiers/client/create', title: 'Add a client', rtlTitle: 'ملف تعريفي للمستخدم', icon: 'icon-bag-16', class: '' }, { path: '/tables', title: 'Purshases', rtlTitle: 'قائمة الجدول', icon: 'icon-money-coins', class: '' }, { path: '/typography', title: 'Sales', rtlTitle: 'طباعة', icon: 'icon-coins', class: '' }, { path: '/typography', title: 'Financial Statements', rtlTitle: 'طباعة', icon: 'icon-bank', class: '' }, { path: '/typography', title: 'Digital Marketing', rtlTitle: 'طباعة', icon: 'icon-chart-bar-32', class: '' }, { path: '/typography', title: 'Reports', rtlTitle: 'طباعة', icon: 'icon-notes', class: '' }, { path: '/typography', title: 'Setting', rtlTitle: 'طباعة', icon: 'icon-settings', class: '' }, { path: '/typography', title: 'Support', rtlTitle: 'طباعة', icon: 'icon-support-17', class: '' }, { path: '/rtl', title: 'RTL Support', rtlTitle: 'ار تي ال', icon: 'icon-world', class: '' } ]; @Component({ selector: 'app-sidebar', templateUrl: './sidebar.component.html', styleUrls: ['./sidebar.component.css'] }) export class SidebarComponent implements OnInit { menuItems: any[]; constructor() { } ngOnInit() { this.menuItems = ROUTES.filter(menuItem => menuItem); } isMobileMenu() { return window.innerWidth <= 991; } }
6231dce9731ccf1e43266203fc7171329ce7076d
[ "Java", "TypeScript", "YAML", "INI" ]
10
Java
nadeemhaj/ERP-Spring-Boot-Angular-Microservices
150204c4ce4826c9bc93712d352b7a869450a541
0cd3644b1059dfca16f1c44f916b018fb14d5afe
refs/heads/master
<repo_name>PRANATIBEHERA/K-MEANS<file_sep>/Kmeans.py import numpy as np from sklearn.cluster import KMeans read_file=open("BCLL.txt",'r') read_content= read_file.read() all_data= read_content.splitlines() #print (all_data) No_data_points=len(all_data) print ("Number of the data points ", No_data_points) features = all_data[0].split("\t") print ("features of the data points ", features) No_of_dimension = len(features) print ("Number the dimensions", No_of_dimension) a=np.zeros((No_data_points,No_of_dimension-2)) counter = 0 for lines in all_data[1: ]: values=lines.split('\t')[2:No_of_dimension] # print (values) for i in range(0,(No_of_dimension-2)): a[counter][i]= values[i] counter+=1 import os def eucledianDistance(arg1,arg2): distance=0 distanceRoot=0 for i in range(len(arg1)): distance= distance + (arg1[i]-arg2[i])**2 distanceRoot=(distance)**0.5 return distanceRoot def toleranceLevel(arg1,arg2): level=0 for i in range(len(arg1)): level= level + abs(((arg2[i]-arg1[i])/arg1[i])) return level from random import randrange n=int((No_data_points)**0.5) print("Square root no is",n) for i in range(0,10): iteration=i ncluster=randrange(2,n) print("Random no is",ncluster) kmeans = KMeans(n_clusters=ncluster) print (kmeans) np.random.seed(1) newArray=np.zeros((No_data_points,No_of_dimension-2)) #K means will work till max-iterations or tolerance level convergence # for i in range(0,kmeans.max_iter) : for m in range(0,3) : centroids=np.zeros((ncluster,No_of_dimension-2)) centroidsNew=np.zeros((ncluster,No_of_dimension-2)) for j in range(0,ncluster): centroids[j]=a[j] distances=np.zeros((ncluster)) for k in range(0,No_data_points): for j in range(0,ncluster): distances[j]=eucledianDistance(a[k],centroids[j]) minIndex = np.argmin(distances) filename_cluster="Cluster_number_"+ str(iteration)+"\Cluster_ "+ str(minIndex) + ".txt" os.makedirs(os.path.dirname(filename_cluster),exist_ok=True) with open(filename_cluster,"a+") as f1: np.savetxt(f1,np.array(a[k]),delimiter='\n', newline='\t' ) f1.write("\n") for j in range(0,ncluster): counter = 0 filename_cluster="Cluster_number_"+ str(iteration)+"\Cluster_ "+ str(j) + ".txt" f= open(filename_cluster,"r+") read_content= f.read() all_cluster_points= read_content.splitlines() No_cluster_points=len(all_cluster_points) cluster_datapoints=np.zeros((No_cluster_points,No_of_dimension-2)) for lines in all_cluster_points: values=lines.split('\t') for p in range(0,(No_of_dimension-2)): cluster_datapoints[counter][p]= values[p] counter+=1 centroidsNew[j]=np.mean(cluster_datapoints,axis=0,keepdims=1) f.close(); for j in range(0,ncluster): # if m < (kmeans.max_iter-1) : if m < 2 : filename_cluster="Cluster_number_"+ str(iteration)+"\Cluster_ "+ str(j) + ".txt" if os.path.exists(filename_cluster): os.remove(filename_cluster) else: print("The file does not exist") convergence=np.zeros((1,ncluster)) for l in range(0,ncluster): x1 = centroids[l] x2 = centroidsNew[l] print("Old Centroid",centroids[l]) print("New Centroid",centroidsNew[l]) level=toleranceLevel(x1,x2) # print("level",level) if level>0.001 : convergence = 0 break; else: convergence = 1 if convergence : print("break") break<file_sep>/README.md # K-MEANS Clustering algorithm such as k-means(from the scratch without libraries), is imple- mented for grouping 4,655 instances of genes in a total of 21 groups.
6ab81e239ba75dac43f179f92a6fc045d9610652
[ "Markdown", "Python" ]
2
Python
PRANATIBEHERA/K-MEANS
6f2a8e348ec8901742f6ef41b1d62849d287f7c4
6195c3944105592d0a64fba4485ef56f7cf383e3
refs/heads/master
<file_sep><?php /* Plugin Name: Headline Images Plugin URI: http://www.coldforged.org/image-headlines-plugin-for-wordpress-15/ Description: Replaces Post headlines with PNG images of text, from ALA's <a href="http://www.alistapart.com/articles/dynatext/">Dynamic Text Replacement</a>. Includes soft-shadows, improved configuration, and previews. Configure on the <a href="../wp-admin/admin.php?page=image-headlines.php">Headline Images Configuration</a> page. Version: 2.6 Author: Brian "ColdForged" Dupuis Author URI: http://www.coldforged.org */ /* Bundled font is the beautiful Warp 1 by <NAME>. Take a gander at some of his other fonts at http://www.project.com/alex/fonts/index.html */ /* Plugin originally by Joel “Jaykul” Bennett, but heavily modified to the point seen here. Dynamic Heading Generator By <NAME> http://www.stewartspeak.com/headings/ http://www.alistapart.com/articles/dynatext/ This script generates PNG images of text, written in the font/size that you specify. These PNG images are passed back to the browser. Optionally, they can be cached for later use. If a cached image is found, a new image will not be generated, and the existing copy will be sent to the browser. Additional documentation on PHP's image handling capabilities can be found at http://www.php.net/image/ */ define( "IMAGEHEADLINES_VERSION", "2.5" ); if (! isset($wp_version)) { require_once (dirname(dirname(dirname(__FILE__))) . "/wp-config.php"); global $wp_version; } if (substr($wp_version, 0, 3) == "1.1" || substr($wp_version, 0, 3) == "1.0" || substr($wp_version, 0, 3) == "1.2" ) { echo "The Image Headlines Plugin requires at least WordPress version 1.3"; return; } define( "FONT_DIRECTORY", dirname(dirname(__FILE__))."/image-headlines" ); if (function_exists('load_plugin_textdomain')) { load_plugin_textdomain('headlinedomain'); } if (! function_exists('ImageHeadline_update_option')) { function ImageHeadline_update_option($option, $new_settings) { update_option($option, $new_settings); } function ImageHeadline_get_settings($option) { $settings = get_settings($option); // HACK for problems with some WordPress 1.3 installations. if( is_string($settings) ) { $unserialized = @ unserialize(stripslashes($settings)); if( $unserialized !== FALSE ) $settings = $unserialized; } return $settings; } } if (! function_exists('ImageHeadline_option_set')) { function ImageHeadline_option_set($option) { if (! $options = ImageHeadline_get_settings('ImageHeadline_options')) return false; else return (in_array($option, $options)); } } if (! function_exists('ImageHeadline_add_options_page')) { function ImageHeadline_add_options_page() { if (function_exists('add_options_page')) add_options_page(__("Headline Options Page"), __('Headlines'), 7, basename(__FILE__)); } } if (! function_exists('ImageHeadline_option_set')) { function ImageHeadline_option_set($option) { if (! $options = ImageHeadline_get_settings('ImageHeadline_options')) return false; else return (in_array($option, $options)); } } if (!function_exists('ImageHeadline_check_flag')) { function ImageHeadline_check_flag($flagname, $allflags) { echo (in_array($flagname, $allflags) ? 'checked="checked"' : ''); } } if (!function_exists('ImageHeadline_check_select')) { function ImageHeadline_check_select($flagname, $allflags, $value) { echo ($allflags[$flagname] == $value ? ' selected="selected"' : ''); } } if (!function_exists('ImageHeadline_check_radio')) { function ImageHeadline_check_radio($flagname, $allflags, $value) { echo ($allflags[$flagname] == $value ? 'checked="checked"' : ''); } } if( !function_exists('ImageHeadline_gd_version' ) ) { function ImageHeadline_gd_version() { static $gd_version_number = null; if ($gd_version_number === null) { // Use output buffering to get results from phpinfo() // without disturbing the page we're in. Output // buffering is "stackable" so we don't even have to // worry about previous or encompassing buffering. ob_start(); phpinfo(8); $module_info = ob_get_contents(); ob_end_clean(); if (preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i", $module_info,$matches)) { $gd_version_number = $matches[1]; } else { $gd_version_number = 0; } } return $gd_version_number; } } if( !function_exists('ImageHeadline_readint')) { function ImageHeadline_readint( $file, $offset, $size ) { @fseek( $file, $offset, SEEK_SET ); $string = @fread( $file, $size ); $myarray = @unpack( (( $size == 2 ) ? "n" : "N")."*", $string ); return intval($myarray[1]); } } if( !function_exists('ImageHeadline_get_ttf_font_name')) { function ImageHeadline_get_ttf_font_name( $fullpath ) { $return_string = ''; $thefile = @fopen( $fullpath, "rb" ); if( $thefile ) { // Read the number of records. $num_tables = ImageHeadline_readint( $thefile, 4, 2 ); // Loop through looking for the name record. $offset = 12; $name_offset = 0; $name_length = 0; for( $x = 0; ( $x < $num_tables ) && !feof( $thefile ) && ( $name_offset == 0 ); $x++ ) { @fseek( $thefile, $offset, SEEK_SET ); $tag = @fread( $thefile, 4 ); if( !strcmp( $tag, 'name' ) ) { // Found the 'name' tag so read the offset into the file of // the name table. $offset += 8; $name_offset = ImageHeadline_readint( $thefile, $offset, 4 ); $name_length = ImageHeadline_readint( $thefile, $offset+4, 4 ); } else { $offset += 16; } } // See if we have an offset to the name table. if( $name_offset != 0 ) { // Yay, likely this is a valid TTF file. That's nice. See how many name entries // we have. $num_names = ImageHeadline_readint( $thefile, $name_offset+2, 2 ); $string_storage_offset = ImageHeadline_readint( $thefile, $name_offset+4, 2 ); $name_id_offset = $name_offset + 12; // Let's find the name record that we desire. We're looking for a name ID // of 4. $name_string_offset = 0; $good_count = 0; $preferred = 0; for( $x = 0; ( $x < $num_names ) && !feof( $thefile ) /*&& ( $name_string_offset == 0 )*/; $x++ ) { $name_id = ImageHeadline_readint( $thefile, $name_id_offset, 2 ); if( $name_id == 4 ) { $good_names[$good_count]["platform_id"] = ImageHeadline_readint( $thefile, $name_id_offset-6, 2 ); $good_names[$good_count]["encoding_id"] = ImageHeadline_readint( $thefile, $name_id_offset-4, 2 ); $good_names[$good_count]["language_id"] = ImageHeadline_readint( $thefile, $name_id_offset-2, 2 ); // Odd I know... we're searching for a Windows platform string with these // precise parameters. It's the most common among fonts that I've seen. Not that this is a // Unicode string so we'll have to deal with that rather naively below. The problem with // the other formats is that many shareware/freeware fonts -- which a lot of people // will probably use -- is that they're inconsistent with their string settings (like the // bundled font... one of the strings is left at "Arial". if( ( $good_names[$good_count]["platform_id"] == 3 ) && ( $good_names[$good_count]["encoding_id"] == 1 ) && ( $good_names[$good_count]["language_id"] == 1033 ) ) { $preferred = $good_count; } $good_names[$good_count]["string_length"] = ImageHeadline_readint( $thefile, $name_id_offset+2, 2 ); $good_names[$good_count++]["string_offset"] = ImageHeadline_readint( $thefile, $name_id_offset+4, 2 ); } $name_id_offset += 12; } // Did we find one? if( $good_count ) { // This getting old yet? What a goofy file format, and PHP is far from the most // efficient binary file parsers available. Anyway, we apparently have our string. // Let's read out the damned thing and have done with it. @fseek( $thefile, $name_offset + $string_storage_offset + $good_names[$preferred]["string_offset"], SEEK_SET ); $return_string = @fread( $thefile, $good_names[$preferred]["string_length"] ); for( $x = 0; $x < 32; $x++ ) $unicode_chars[] = chr($x); $return_string = str_replace( $unicode_chars, "", $return_string ); } } fclose( $thefile ); } return $return_string; } } if( !function_exists( 'ImageHeadline_clear_cache' ) ) { function ImageHeadline_clear_cache( $dirname, $lifetime ) { if( ( $mydir = @opendir( $dirname ) ) !== false ) { while( ( $file = @readdir( $mydir ) ) !== false ) { if( preg_match("/[a-f0-9]{32}\.png/i", $file) ) { $difftime = ( time() - filectime( "$dirname/$file" ) ) / 60 / 60 / 24; if( $difftime > $lifetime ) { @unlink( "$dirname/$file" ); } } } } } } if( !function_exists( 'ImageHeadline_maybe_clear_cache' ) ) { function ImageHeadline_maybe_clear_cache( $dirname, $lifetime ) { $clearit = false; // Determine if the cache needs clearing. We do this every 12 hours. if( file_exists( "$dirname/cache.info" ) ) { $difftime = time() - filectime( "$dirname/cache.info" ); if( $difftime > ( 12 * 60 * 60 ) ) { $clearit = true; @touch( "$dirname/cache.info" ); } } else { if( ( $file = @fopen( "$dirname/cache.info", "wb" ) ) !== false ) { @fwrite( $file, "Hi there." ); @fclose( $file ); } $clearit = true; } if( $clearit ) { ImageHeadline_clear_cache($dirname, $lifetime); } } } if( !function_exists( 'ImageHeadline_traverse_directory' ) ) { function ImageHeadline_traverse_directory($dirname, &$return_array) { $current_num = count($return_array); // Get a list of files in the directory. if( ($mydir = @opendir( $dirname )) !== false ) { while(($file = readdir($mydir))!== false ) { if ($file != "." && $file != "..") { $font_name = ImageHeadline_get_ttf_font_name( $dirname."/".$file ); if( $font_name != '' ) { $return_array[$current_num]["font_name"] = $font_name; $return_array[$current_num++]["font_file"] = $dirname."/".$file; } } } closedir($mydir); } return $current_num; } } if( !function_exists( 'ImageHeadline_get_fonts' ) ) { /* Returns an associative array of font file names and the corresponding font name */ function ImageHeadline_get_fonts() { $num_fonts = 0; $return_array = Array(); // Get a list of files in the directory. We'll also check the upload directory // since that's an easy place for WordPress administrators to put new files. ImageHeadline_traverse_directory( FONT_DIRECTORY, $return_array ); ImageHeadline_traverse_directory( get_settings('fileupload_realpath'), $return_array ); // For each supposed font file parse out a font name string. return $return_array; } } if( !function_exists( 'ImageHeadline_gaussian' ) ) { function ImageHeadline_gaussian( &$image, $width, $height, $spread ) { $use_GD1 = ImageHeadline_option_set( 'only_use_imagecreate' ); if( $use_GD1 ) return; // Check for silly spreads if( $spread == 0 ) return; if( $spread > 10 ) $spread = 10; if( strlen( $memory_limit = trim(ini_get('memory_limit' )) ) > 0 ) { $last = strtolower($memory_limit{strlen($memory_limit)-1}); switch($last) { // The 'G' modifier is available since PHP 5.1.0 case 'g': $memory_limit *= 1024; case 'm': $memory_limit *= 1024; case 'k': $memory_limit *= 1024; } if( $memory_limit <= 8 * 1024 * 1024 ) { $use_low_memory_method = true; } } else { $use_low_memory_method = false; } // Perform gaussian blur convlution. First, prepare the convolution // kernel and precalculated multiplication array. Algorithm // adapted from the simply exceptional code by <NAME> // <http://incubator.<EMAIL>>. Kernel is essentially an // approximation of a gaussian distribution by utilizing squares. $kernelsize = $spread*2-1; $kernel = array_fill( 0, $kernelsize, 0 ); $mult = array_fill( 0, $kernelsize, array_fill( 0, 256, 0 ) ); for( $i = 1; $i < $spread; $i++ ) { $smi = $spread - $i; $kernel[$smi-1]=$kernel[$spread+$i-1]=$smi*$smi; for( $j = 0; $j < 256; $j++ ) { $mult[$smi-1][$j] = $mult[$spread+$i-1][$j] = $kernel[$smi-1]*$j; } } $kernel[$spread-1]=$spread*$spread; for( $j = 0; $j < 256; $j++ ) { $mult[$spread-1][$j] = $kernel[$spread-1]*$j; } if( !$use_low_memory_method ) { // Kernel and multiplication array calculated, let's get the image // read out into a usable format. $imagebytes = $width*$height; $i = 0; for( $x = 0; $x < $width; $x++ ) { for( $y = 0; $y < $height; $y++ ) { $rgb = imagecolorat( $image, $x, $y ); $imagearray[$i++] = $rgb; } } } // Everything's set. Let's run the first pass. Our first pass will be a // vertical pass. for( $x = 0; $x < $width; $x++ ) { for( $y = 0; $y < $height; $y++ ) { $sum = 0; $cr = $cg = $cb = 0; for( $j = 0; $j < $kernelsize; $j++ ) { $kernely = $y + ( $j - ( $spread - 1 ) ); if( ( $kernely >= 0 ) && ( $kernely < $height ) ) { if( !$use_low_memory_method ) { $ci = ( $x * $height ) + $kernely; $rgb = $imagearray[$ci]; } else { $rgb = imagecolorat( $image, $x, $kernely ); } $cr += $mult[$j][($rgb >> 16 ) & 0xFF]; $cg += $mult[$j][($rgb >> 8 ) & 0xFF]; $cb += $mult[$j][$rgb & 0xFF]; $sum += $kernel[$j]; } } $ci = ( $x * $height ) + $y; $shadowarray[$ci] = ( ( intval(round($cr/$sum)) & 0xff ) << 16 ) | ( ( intval(round($cg/$sum)) & 0xff ) << 8 ) | ( intval(round($cb/$sum)) & 0xff ); } } // Free up some memory if( isset( $imagearray ) ) { unset( $imagearray ); } // Now let's make with the horizontal passing. That sentence // contruct never gets old: "make with the". Oh the humor. for( $x = 0; $x < $width; $x++ ) { for( $y = 0; $y < $height; $y++ ) { $sum = 0; $cr = $cg = $cb = 0; for( $j = 0; $j < $kernelsize; $j++ ) { $kernelx = $x + ( $j - ( $spread - 1 ) ); if( ( $kernelx >= 0 ) && ( $kernelx < $width ) ) { $ci = ( $kernelx * $height ) + $y; $cr += $mult[$j][($shadowarray[$ci] >> 16 ) & 0xFF]; $cg += $mult[$j][($shadowarray[$ci] >> 8 ) & 0xFF]; $cb += $mult[$j][$shadowarray[$ci] & 0xFF]; $sum += $kernel[$j]; } } $r = intval(round($cr/$sum)); $g = intval(round($cg/$sum)); $b = intval(round($cb/$sum)); if( $r < 0 ) $r = 0; else if( $r > 255 ) $r = 255; if( $g < 0 ) $g = 0; else if( $g > 255 ) $g = 255; if( $b < 0 ) $b = 0; else if( $b > 255 ) $b = 255; $color = ( $r << 16 ) | ($g << 8 ) | $b; if( !isset( $colors[ $color ] ) ) { $colors[ $color ] = imagecolorallocate( $image, $r, $g, $b ); } imagesetpixel( $image, $x, $y, $colors[$color] ); } } } } /* To override the format for a particular transformation, specify the name of the settings to override followed by an '=' and the value to set it to. Separate multiple settings with an ampersand (&) */ if( !function_exists( 'ImageHeadline_render' ) ) { function ImageHeadline_render($text, $format_override='') { $current_settings = ImageHeadline_get_settings('ImageHeadline_settings'); global $DebugImgHead; // Clear the cache if necessary. ImageHeadline_maybe_clear_cache( $current_settings['cache_folder'], isset($current_settings['image_lifetime']) ? $current_settings['image_lifetime'] : 14 ); // Check for format overrides. if( $format_override != '' ) { $formats = explode( '&', $format_override ); foreach( $formats as $format ) { $setting = explode( "=", $format, 2 ); if( isset( $current_settings[ $setting[0] ] ) ) { $current_settings[ $setting[0] ] = $setting[1]; } } } $mime_type = 'image/png' ; $extension = '.png' ; $send_buffer_size = 4096 ; $retVal = $text; // check for GD support if(get_magic_quotes_gpc()) $text = stripslashes($text) ; $hashinput = basename($current_settings['font_file']) . IMAGEHEADLINES_VERSION . $current_settings['font_size'] . $current_settings['font_color'] . $current_settings['background_color'] . $current_settings['left_padding'] . $current_settings['max_width'] . $current_settings['space_between_lines'] . $current_settings['line_indent'] . $current_settings['background_image'] . ImageHeadline_option_set('transparent_background') . ImageHeadline_option_set('shadows') . ImageHeadline_option_set('split_lines') . $current_settings['soft_shadows'] . $text; // look for cached copy, send if it exists if( ImageHeadline_option_set( 'shadows' ) ) { if( !$current_settings['soft_shadows'] ) { $hash = md5( $hashinput . $current_settings['shadow_first_color'] . $current_settings['shadow_second_color'] . $current_settings['shadow_offset']) ; } else { $hash = md5( $hashinput . $current_settings['shadow_color'] . $current_settings['shadow_horizontal_offset'] . $current_settings['shadow_vertical_offset'] . $current_settings['shadow_spread']) ; } } else { $hash = md5($hashinput) ; } $cache_filename = $current_settings['cache_folder'] . '/' . $hash . $extension ; $generated_url = $current_settings['cache_url'] . '/' . $hash . $extension ; if( file_exists( $cache_filename )) { list($width, $height, $type, $attr) = getimagesize($cache_filename); $retVal = "<img src='$generated_url' alt='$text' width='$width' height='$height' />" ; } elseif( is_writable( $current_settings['cache_folder'] ) ){ // check font availability $font_found = is_readable($current_settings['font_file']) ; if( !$font_found ) { if( $DebugImgHead ) echo('Error: The server is missing the specified font.') ; $retVal = $text; } else { // create image $background_rgb = ImageHeadline_hex_to_rgb($current_settings['background_color'], $DebugImgHead) ; $font_rgb = ImageHeadline_hex_to_rgb($current_settings['font_color'], $DebugImgHead) ; $box["width"] = 0; $box["height"] = 0; $current_y = -1; $max_y = -1; // Calculate how much additional space is needed for shadows. $vertical_shadow_spacing = $horizontal_shadow_spacing = 0; if( ImageHeadline_option_set( 'shadows' ) ) { if( !$current_settings['soft_shadows'] ) { $vertical_shadow_spacing = $horizontal_shadow_spacing = 2; } else { $vertical_shadow_spacing += $current_settings['shadow_vertical_offset'] + $current_settings['shadow_spread']; $horizontal_shadow_spacing += $current_settings['shadow_horizontal_offset'] + $current_settings['shadow_spread']; } } // Split the text into complete lines of no greater than max_width if we've been // told to split lines. Otherwise, work with the whole text regardless of line length. if( ImageHeadline_option_set( 'split_lines' ) ) { $text_array = ImageHeadline_break_text_into_lines( $text, $current_settings ); } else { $text_array[] = $text; } // Now we need to calculate the overall dimensions of the resultant image. We have to //take into account the number of lines, all formatting options (e.g. space between // lines, indent) as well as use of shadows and spreads for shadows. foreach( $text_array as $line ) { $bbox = @ImageTTFBBox($current_settings['font_size'],0,$current_settings['font_file'],$line); $width = $current_settings['left_padding'] + $horizontal_shadow_spacing + ( max($bbox[0],$bbox[2],$bbox[4],$bbox[6]) - min($bbox[0],$bbox[2],$bbox[4],$bbox[6]) ) + 2; $height = ( max($bbox[1],$bbox[3],$bbox[5],$bbox[7]) - min($bbox[1],$bbox[3],$bbox[5],$bbox[7]) ) + $vertical_shadow_spacing; // If this isn't the first line of multi-line text, we have to take into account // the space between each line vertically as well any line indent horizontally. if( $max_y > 0 ) { $box["height"] += $current_settings['space_between_lines']; $width += $current_settings['line_indent']; } if( $height > $max_y ) { $max_y = $height; } if( $current_y == -1 ) { $current_y = abs(min($bbox[5], $bbox[7])) - 1; } // Increment height and latch width to the widest line. if( $box["width"] < $width ) { $box["width"] = $width; } } $box["height"] += count( $text_array ) * $max_y; // Creat the image and fill it with our background color. if( ImageHeadline_option_set( 'only_use_imagecreate' ) ) { $image = @ImageCreate($box["width"],$box["height"]); } else { $image = @ImageCreateTrueColor($box["width"],$box["height"]); } $background_color = @ImageColorAllocate($image,$background_rgb['red'], $background_rgb['green'], $background_rgb['blue'] ) ; imagefill( $image, 0, 0, $background_color ); if( !$image || !$box ) { if( $DebugImgHead ) echo('Error: The server could not create this heading image.') ; $retVal = $text; } else { // allocate colors and draw text $current_settings['font_color'] = @ImageColorAllocate($image,$font_rgb['red'], $font_rgb['green'], $font_rgb['blue']) ; // Blit the background image in there. This is always fun. if( ImageHeadline_option_set('use_background_image') ) { if(!empty( $current_settings['background_image'] ) && is_readable( $current_settings['background_image'] ) ) { list($widthi, $heighti, $typei, $attri) = getImageSize($current_settings['background_image']); $backgroundimage = ImageCreateFromPNG( $current_settings['background_image'] ); //NOTE use png for this ImageColorTransparent($backgroundimage,$background_color); // merge the two together with alphablending on! ImageAlphaBlending($backgroundimage, true); ImageCopyMerge ( $image, $backgroundimage, 0, 0, 0, 0, $widthi, $heighti, 99); } else { if( $debug ) echo "Image not found: ".$current_settings['background_image']." is apparently missing."; } } $saved_y = $current_y; // Render the shadows depending on the selected method. if( ImageHeadline_option_set( 'shadows' ) ) { if( !$current_settings['soft_shadows'] ) { // "Classic" method of text drawn in two different colors. $current_x = 0; $shadow_rgb = ImageHeadline_hex_to_rgb($current_settings['shadow_first_color'], $DebugImgHead); $shadow_1 = @ImageColorAllocate($image,$shadow_rgb['red'], $shadow_rgb['green'], $shadow_rgb['blue']); $shadow_rgb = ImageHeadline_hex_to_rgb($current_settings['shadow_second_color'], $DebugImgHead); $shadow_2 = @ImageColorAllocate($image,$shadow_rgb['red'], $shadow_rgb['green'], $shadow_rgb['blue']); foreach( $text_array as $line ) { ImageTTFText($image, $current_settings['font_size'], 0, $current_x + $current_settings['left_padding'] + $current_settings['shadow_offset'] * 2, $current_y + $current_settings['shadow_offset'] * 2, $shadow_2, $current_settings['font_file'], $line) ; ImageTTFText($image, $current_settings['font_size'], 0, $current_x + $current_settings['left_padding'] + $current_settings['shadow_offset'], $current_y + $current_settings['shadow_offset'], $shadow_1, $current_settings['font_file'], $line) ; $current_y += $max_y + $current_settings['space_between_lines']; if( $current_x == 0 ) { $current_x += $current_settings['line_indent']; } } } else /* soft shadows */ { // Gaussian blurred "soft-shadow" method. if( ImageHeadline_option_set( 'only_use_imagecreate' ) ) { $shadow_image = @ImageCreate( $box['width'], $box['height']); } else { $shadow_image = @ImageCreateTrueColor( $box['width'], $box['height']); } imagefill( $shadow_image, 0, 0, $background_color ); $shadow_rgb = ImageHeadline_hex_to_rgb($current_settings['shadow_color'], $DebugImgHead); $shadow_color = @ImageColorAllocate($shadow_image,$shadow_rgb['red'], $shadow_rgb['green'], $shadow_rgb['blue']); $current_x = 0; foreach( $text_array as $line ) { ImageTTFText($shadow_image, $current_settings['font_size'], 0, $current_x + $current_settings['left_padding'] + $current_settings['shadow_horizontal_offset'], $current_y + $current_settings['shadow_vertical_offset'], $shadow_color, $current_settings['font_file'], $line) ; $current_y += $max_y + $current_settings['space_between_lines']; if( $current_x == 0 ) { $current_x += $current_settings['line_indent']; } } ImageHeadline_gaussian( $shadow_image, $box['width'], $box['height'], $current_settings['shadow_spread'] ); if(ImageHeadline_option_set('transparent_background')) ImageColorTransparent($shadow_image,$background_color) ; ImageAlphaBlending($shadow_image, true ); ImageCopyMerge( $image, $shadow_image, 0,0,0,0, $box["width"], $box["height"],50); ImageDestroy($shadow_image); } } $current_x = 0; $current_y = $saved_y; foreach( $text_array as $line ) { ImageTTFText($image, $current_settings['font_size'], 0, $current_x + $current_settings['left_padding'], $current_y, $current_settings['font_color'], $current_settings['font_file'], $line) ; $current_y += $max_y + $current_settings['space_between_lines']; if( $current_x == 0 ) { $current_x += $current_settings['line_indent']; } } // set transparency if(ImageHeadline_option_set('transparent_background')) ImageColorTransparent($image,$background_color) ; @ImagePNG($image,$cache_filename) ; ImageDestroy($image) ; if( file_exists( $cache_filename ) ) { $retVal = "<img src='$generated_url' alt='".addslashes($text)."' width='".$box['width']."' height='".$box['height']."' />" ; } else { if( $DebugImgHead ) echo( "Unknown Error creating file." ); $retVal = $text; } } } } else { if( $DebugImgHead ) echo( "Error: The Folder [".dirname( $cache_filename )."] is not writeable." ); $retVal = $text; } return $retVal; } } if( !function_exists( 'ImageHeadline_hex_to_rgb' ) ) { /* decode an HTML hex-code into an array of R,G, and B values. accepts these formats: (case insensitive) #ffffff, ffffff, #fff, fff */ function ImageHeadline_hex_to_rgb($hex, $DebugImgHead) { // remove '#' if(substr($hex,0,1) == '#') $hex = substr($hex,1) ; // expand short form ('fff') color if(strlen($hex) == 3) { $hex = substr($hex,0,1) . substr($hex,0,1) . substr($hex,1,1) . substr($hex,1,1) . substr($hex,2,1) . substr($hex,2,1) ; } if(strlen($hex) != 6 && $DebugImgHead ) { echo('Error: Invalid color "'.$hex.'"') ; } // convert $rgb['red'] = hexdec(substr($hex,0,2)) ; $rgb['green'] = hexdec(substr($hex,2,2)) ; $rgb['blue'] = hexdec(substr($hex,4,2)) ; return $rgb ; } } if( !function_exists( 'ImageHeadline_break_text_into_lines' ) ) { /* Break the line into several lines if it exceeds the maximum allowed width. */ function ImageHeadline_break_text_into_lines( $text, $current_settings ) { // the returned array of strings to be on separate lines. $text_array = array(); // Figure out how big a space is. Yes, I'm being anal. $bbox = imagettfbbox($current_settings['font_size'],0, $current_settings['font_file'], ' '); $space_width = max($bbox[2],$bbox[4]) - min($bbox[0], $bbox[6]); // Split the array into word components. $words = explode( ' ', $text ); $current_line = ''; $current_width = $current_settings['left_padding']; foreach( $words as $word ) { $bbox = imagettfbbox($current_settings['font_size'], 0, $current_settings['font_file'], $word ); $word_width = max($bbox[2],$bbox[4]) - min($bbox[0], $bbox[6]); // See if the current word will fit on the line. if( $word_width + $current_width + $space_width > $current_settings['max_width'] ) { // It won't. Check the border case where we have a friggin' // huge first word. If so, it'll have to be rendered on the // line regardless. if( $current_line != '' ) { $text_array[] = $current_line; $current_width = $word_width + $current_settings['left_padding'] + $current_settings['line_indent']; $current_line = $word; } else { $text_array[] = $word; $current_width = $current_settings['left_padding'] + $current_settings['line_indent']; $current_line = ''; } continue; } // Word fits, so append it. if( $current_line != '' ) { $current_line .= ' '; } $current_line .= $word; $current_width += $word_width + $space_width; } if( $current_line != '' ) { $text_array[] = $current_line; } return $text_array; } } if( !function_exists( 'imageheadlines' ) ) { /* Main workhorse function for actually replacing headlines with text. */ function imageheadlines($text) { $current_settings = ImageHeadline_get_settings('ImageHeadline_settings'); global $DebugImgHead; // Check for XML feeds. Don't replace in feeds. // If you have $before set, and it doesn't match, we're done. if( strpos($text, $current_settings['before_text']) === FALSE ) { return $text; } else { if( !empty($current_settings['before_text']) ) { $text = substr( $text, strlen($current_settings['before_text']) ); } // If you have problems, set this to TRUE and see what pops up ;-) $DebugImgHead = true; if( ImageHeadline_option_set( 'disable_headlines' ) ) { return $text; } else { // get/make an image for this text. return ImageHeadline_render( $text ); } } } } if( is_plugin_page() ) { global $user_level; // Set up the default settings. $default_settings = array( 'font_file' => FONT_DIRECTORY."/warp1.ttf", 'font_size' => 18, 'font_color' => '#FF0000', 'background_color' => '#FFF', 'shadow_color' => '#000', 'shadow_spread' => 3, 'shadow_vertical_offset' => 2, 'shadow_horizontal_offset' => 2, 'left_padding' => 0, 'max_width' => 450, 'space_between_lines' => 5, 'line_indent' => 10, 'preview_text' => 'The quick brown fox jumped over the lazy dog.', 'cache_url' => ( get_option('use_fileupload') ? get_settings('fileupload_url'):get_settings( 'siteurl' )."/wp-content/image-headlines" ), 'cache_folder' => ( get_option('use_fileupload') ? get_settings('fileupload_realpath'):dirname(dirname(__FILE__))."/image-headlines" ), 'soft_shadows' => 1, 'shadow_first_color' => '#FFF', 'shadow_second_color' => '#BBB', 'shadow_offset' => 1, 'background_image' => '', 'before_text' => '-image-', 'image_lifetime' => 14 ); $default_options = array( 'shadows', 'split_lines', 'transparent_background', ); global $ImageHeadline_options; if( isset( $_POST['update_options'] ) ) { ImageHeadline_update_option('ImageHeadline_options', $_POST['ImageHeadline_options']); $new_settings = array_merge(ImageHeadline_get_settings('ImageHeadline_settings'), $_POST['ImageHeadline_settings']); foreach($default_settings as $key => $val) if (!isset($new_settings[$key])) $new_settings[$key] = $val; // A bit of error checking. if( $new_settings['shadow_spread'] <= 0 ) { $new_settings['shadow_spread'] = 1; } if( $new_settings['shadow_spread'] > 10 ) { $new_settings['shadow_spread'] = 10; } $new_settings['preview_text'] = apply_filters('title_save_pre', $new_settings['preview_text']); ImageHeadline_update_option('ImageHeadline_settings', $new_settings); echo '<div class="updated"><p><strong>' . __('Options updated.', 'headlinedomain') . '</strong></p></div>'; $ImageHeadline_options = ImageHeadline_get_settings('ImageHeadline_options'); $ImageHeadline_settings = ImageHeadline_get_settings('ImageHeadline_settings'); if(!is_array($ImageHeadline_settings)) $ImageHeadline_settings = $default_settings; if(!is_array($ImageHeadline_options)) $ImageHeadline_options = $default_options; } else { add_option('ImageHeadline_options', $default_options); add_option('ImageHeadline_settings', $default_settings); $ImageHeadline_options = ImageHeadline_get_settings('ImageHeadline_options'); $ImageHeadline_settings = ImageHeadline_get_settings('ImageHeadline_settings'); if(!is_array($ImageHeadline_settings)) $ImageHeadline_settings = $default_settings; if(!is_array($ImageHeadline_options)) $ImageHeadline_options = $default_options; } $ImageHeadline_settings = array_merge( $default_settings, $ImageHeadline_settings ); ImageHeadline_update_option('ImageHeadline_settings', $ImageHeadline_settings); $edited_preview_text = format_to_edit($ImageHeadline_settings['preview_text']); $edited_preview_text = apply_filters('title_edit_pre', $edited_preview_text); $render_title = apply_filters('the_title', $ImageHeadline_settings['preview_text']); // Check for some errors. if( ( ImageHeadline_gd_version() < 2 ) || (!function_exists( 'ImageCreate' ) ) ) { if( function_exists( 'ImageCreate' ) ) { $ImageHeadline_options[] = 'only_use_imagecreate'; if(ImageHeadline_option_set( 'disable_headlines' ) ) { // Somebody must have installed what we need... enable us again. unset($ImageHeadline_options[array_search('disable_headlines',$ImageHeadline_options)]); $ImageHeadline_options = array_values( $ImageHeadline_options ); } if( $ImageHeadline_settings['soft_shadows'] == 1 ) { $ImageHeadline_settings['soft_shadows'] = 0; ImageHeadline_update_option('ImageHeadline_settings', $ImageHeadline_settings); } } else { $ImageHeadline_options[] = 'disable_headlines'; echo '<div class="updated" style="background-color: #FF8080;border: 3px solid #F00;"><p><strong>' . __('FATAL: Your PHP installation does not support the ImageCreateTrueColor() or the ImageCreate() function. Unforunately, there is not much this plugin can do without that. Talk to your hosting administrator about upgrading to a version that supports image manipulation and try again with the plugin.', 'headlinedomain') . '</strong></p></div>'; } ImageHeadline_update_option('ImageHeadline_options', $ImageHeadline_options); } else { if( ImageHeadline_option_set( 'disable_headlines' ) ) { unset($ImageHeadline_options[array_search('disable_headlines',$ImageHeadline_options)]); $ImageHeadline_options = array_values( $ImageHeadline_options ); ImageHeadline_update_option('ImageHeadline_options', $ImageHeadline_options); } if(ImageHeadline_option_set( 'only_use_imagecreate' ) && function_exists( 'ImageCreateTrueColor' ) ) { unset($ImageHeadline_options[array_search('only_use_imagecreate',$ImageHeadline_options)]); $ImageHeadline_options = array_values( $ImageHeadline_options ); ImageHeadline_update_option('ImageHeadline_options', $ImageHeadline_options); } } if( !ImageHeadline_option_set( 'disable_headlines' ) ) { if( !file_exists( $ImageHeadline_settings['cache_folder'] ) ) { if( !@mkdir ( $ImageHeadline_settings['cache_folder'], 0755 ) ) { echo '<div class="updated" style="background-color: #FF8080;border: 3px solid #F00;"><p><strong>' . __('FATAL: The directory you specified to cache the image files did not exist and I could not create it. Either create it for me or select a different directory.', 'headlinedomain') . '</strong></p></div>'; } } if( !is_writable( $ImageHeadline_settings['cache_folder'] ) ) { echo '<div class="updated" style="background-color: #FF8080;border: 3px solid #F00;"><p><strong>' . __('FATAL: The directory you specified to cache the image files is not writeable from the Apache task. Either select a different directory or make the directory you specified writable by the Apache task (chmod 755 the directory).', 'headlinedomain') . '</strong></p></div>'; $cache_folder_error = true; } $fonts = ImageHeadline_get_fonts(); $allowed_types = explode(' ', trim(strtolower(get_settings('fileupload_allowedtypes')))); if ( ( get_option('use_fileupload') ) && $user_level >= get_settings('fileupload_minlevel') ) { if( in_array('ttf', $allowed_types) ) { $upload_text = __('. You may use the <a href="','headlinedomain').get_settings( 'siteurl' )."/wp-admin/upload.php\">".__('Upload</a> feature of WordPress to upload more fonts','headlinedomain'); } else { $upload_text = __('. Upload more fonts using the Upload feature of WordPress, but first you must <a href="','headlinedomain').get_settings( 'siteurl' )."/wp-admin/options-misc.php\">".__('allow</a> TTF files to be uploaded','headlinedomain'); } } else { $upload_text = ''; } ?> <div class="wrap"> <h2><?php _e("Headline Image Options", 'headlinedomain') ?></h2> <form name="headline_form" method="post"> <fieldset class="options"> <legend> <?php _e("Preview", 'headlinedomain')?> </legend> <?php _e('This is a preview of your current settings. Save your settings to update the preview.', 'headlinedomain' ) ?> <p> <?php echo imageheadlines( $ImageHeadline_settings['before_text'].$render_title ); ?> </p> <label for="preview_text"> <?php _e('Preview text to display:', 'headlinedomain' ) ?> </label> <input type="text" name="ImageHeadline_settings[preview_text]" value="<?php echo stripslashes($edited_preview_text) ?>" size="70"> </fieldset> <fieldset class="options"> <legend> <?php _e("General Configuration", 'headlinedomain')?> </legend> <table width="100%" cellspacing="2" cellpadding="5" class="editform"> <tr valign="top"> <th width="45%" scope="row"><?php if( $cache_folder_error ) echo "<span style='color: #f00;'>"; _e('Image cache folder <em>(Where images will be cached on your server. MUST be a full path to a folder writeable by the Apache process.):', 'headlinedomain' ); if( $cache_folder_error ) echo "</span>" ?></th> <td><input type="text" name="ImageHeadline_settings[cache_folder]" value="<?php echo stripslashes($ImageHeadline_settings['cache_folder']) ?>" size="70" /></td> </tr> <tr valign="top"> <th width="45%" scope="row"><?php _e('Image cache URL <em>(URL to the same folder as above.)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" name="ImageHeadline_settings[cache_url]" value="<?php echo $ImageHeadline_settings['cache_url'] ?>" size="70" /></td> </tr> <tr valign="top"> <th width="45%" scope="row"><?php _e('Image cache lifetime <em>(time in days that images will remain in cache)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" name="ImageHeadline_settings[image_lifetime]" value="<?php echo $ImageHeadline_settings['image_lifetime'] ?>" size="4" /></td> </tr> </table> </fieldset> <fieldset class="options"> <legend> <?php _e("Font and Colors", 'headlinedomain')?> </legend> <table width="100%" cellspacing="2" cellpadding="5" class="editform"> <tr valign="center"> <th width="45%" scope="row"><?php _e('Font <em>(must be a .ttf file', 'headlinedomain' ); echo $upload_text; _e('.)</em>:', 'headlinedomain' ) ?></th> <?php if( count( $fonts ) > 0 ) { ?> <td><select name="ImageHeadline_settings[font_file]"> <?php for( $x = 0; $x < count( $fonts ); $x++ ) { ?> <option value="<?php echo $fonts[$x]["font_file"];?>"<?php ImageHeadline_check_select('font_file',$ImageHeadline_settings,$fonts[$x]["font_file"]);?>><?php echo $fonts[$x]["font_name"];?></option> <?php } ?> </select></td> <?php } else { ?> <td>You have no fonts installed. They should be installed in the 'wp-content/image-headlines' directory of your WordPress installation or in your WordPress uploads directory. Only TrueType (TTF) fonts are allowed.</td> <?php } ?> </tr> <tr valign="top"> <th width="45%" scope="row"><?php _e('Font size <em>(in points)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" name="ImageHeadline_settings[font_size]" value="<?php echo $ImageHeadline_settings['font_size'] ?>" size="4"></td> </tr> <tr valign="top"> <th width="45%" scope="row"><?php _e('Font color <em>(in HTML format, e.g. #44CCAA)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" name="ImageHeadline_settings[font_color]" value="<?php echo $ImageHeadline_settings['font_color'] ?>" size="8"></td> </tr> <tr valign="top"> <th width="45%" scope="row"><?php _e('Background color <em>(in HTML format, e.g. #44CCAA)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" name="ImageHeadline_settings[background_color]" value="<?php echo $ImageHeadline_settings['background_color'] ?>" size="8"></td> </tr> <tr valign="top"> <th width="45%" scope="row"></th> <td><input name="ImageHeadline_options[]" type="checkbox" id="transparent_background" value="transparent_background" <?php ImageHeadline_check_flag('transparent_background', $ImageHeadline_options); ?> /><label for="transparent_background"><?php _e("Make background color transparent.", 'headlinedomain')?></label></td> </tr> </table> <fieldset class="options"> <legend> <input name="ImageHeadline_options[]" type="checkbox" id="use_background_image" value="use_background_image" <?php ImageHeadline_check_flag('use_background_image', $ImageHeadline_options); ?> /> <label for="use_background_image"><?php _e("Display a background image", 'headlinedomain')?></label> </legend> <table width="100%" cellspacing="2" cellpadding="5" class="editform"> <tr valign="top"> <th width="45%" scope="row"><?php _e('Background image <em>(in PNG format)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" name="ImageHeadline_settings[background_image]" value="<?php echo $ImageHeadline_settings['background_image'] ?>" size="70"></td> </tr> </table> </fieldset> </fieldset> <fieldset class="options"> <legend> <?php _e("Line Spacing", 'headlinedomain')?> </legend> <table width="100%" cellspacing="2" cellpadding="5" class="editform"> <tr valign="top"> <th width="45%" scope="row"><?php _e('Left padding between image edge and text start <em>(in pixels)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" name="ImageHeadline_settings[left_padding]" value="<?php echo $ImageHeadline_settings['left_padding'] ?>" size="4"></td> </tr> </table> <fieldset class="options"> <legend> <input name="ImageHeadline_options[]" type="checkbox" id="split_lines" value="split_lines" <?php ImageHeadline_check_flag('split_lines', $ImageHeadline_options); ?> /> <label for="split_lines"><?php _e("Split long lines", 'headlinedomain')?></label> </legend> <table width="100%" cellspacing="2" cellpadding="5" class="editform"> <tr valign="top"> <th width="45%" scope="row"><?php _e('Maximimum line length before line break <em>(in pixels)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" name="ImageHeadline_settings[max_width]" value="<?php echo $ImageHeadline_settings['max_width'] ?>" size="4" /></td> </tr> <tr valign="top"> <th width="45%" scope="row"><?php _e('Vertical space between lines <em>(in pixels)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" name="ImageHeadline_settings[space_between_lines]" value="<?php echo $ImageHeadline_settings['space_between_lines'] ?>" size="4"></td> </tr> <tr valign="top"> <th width="45%" scope="row"><?php _e('Line indent from left border <em>(in pixels)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" name="ImageHeadline_settings[line_indent]" value="<?php echo $ImageHeadline_settings['line_indent'] ?>" size="4"></td> </tr> </table> </fieldset> </fieldset> <fieldset class="options"> <legend> <input name="ImageHeadline_options[]" type="checkbox" id="shadows" value="shadows" <?php ImageHeadline_check_flag('shadows', $ImageHeadline_options); ?> /> <label for="shadows"><?php _e("Enable shadow behind text", 'headlinedomain')?></label> </legend> <fieldset class="options"> <legend> <input name="ImageHeadline_settings[soft_shadows]" <?php if( ImageHeadline_option_set( 'only_use_imagecreate' )) echo "disabled"?> type="radio" value="1" <?php ImageHeadline_check_radio('soft_shadows', $ImageHeadline_settings, 1); ?> /> <?php if( ImageHeadline_option_set( 'only_use_imagecreate' )) { ?> <label for="ImageHeadline_settings[soft_shadows]"><?php _e("Use soft-shadows <em>(Not available... requires GD version 2.0 or higher.)</em>", 'headlinedomain')?></label> <?php } else { ?> <label for="ImageHeadline_settings[soft_shadows]"><?php _e("Use soft-shadows <em>(computationally expensive)</em>", 'headlinedomain')?></label> <?php } ?> </legend> <table width="100%" cellspacing="2" cellpadding="5" class="editform"> <tr valign="top"> <th width="45%" scope="row"><?php _e('Shadow color <em>(in HTML format, e.g. #44CCAA)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" <?php if( ImageHeadline_option_set( 'only_use_imagecreate' )) echo "disabled"?> name="ImageHeadline_settings[shadow_color]" value="<?php echo $ImageHeadline_settings['shadow_color'] ?>" size="8"></td> </tr> <tr valign="top"> <th width="45%" scope="row"><?php _e('Shadow spread <em>(in pixels (1 - 10). The larger the spread the more diffuse the effect and slower to process)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" <?php if( ImageHeadline_option_set( 'only_use_imagecreate' )) echo "disabled"?> name="ImageHeadline_settings[shadow_spread]" value="<?php echo $ImageHeadline_settings['shadow_spread'] ?>" size="2"></td> </tr> <tr valign="top"> <th width="45%" scope="row"><?php _e('Vertical offset <em>(in pixels)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" <?php if( ImageHeadline_option_set( 'only_use_imagecreate' )) echo "disabled"?> name="ImageHeadline_settings[shadow_vertical_offset]" value="<?php echo $ImageHeadline_settings['shadow_vertical_offset'] ?>" size="2"></td> </tr> <tr valign="top"> <th width="45%" scope="row"><?php _e('Horizontal offset <em>(in pixels)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" <?php if( ImageHeadline_option_set( 'only_use_imagecreate' )) echo "disabled"?> name="ImageHeadline_settings[shadow_horizontal_offset]" value="<?php echo $ImageHeadline_settings['shadow_horizontal_offset'] ?>" size="2"></td> </tr> </table> </fieldset> <fieldset class="options"> <legend> <input name="ImageHeadline_settings[soft_shadows]" type="radio" value="0" <?php ImageHeadline_check_radio('soft_shadows', $ImageHeadline_settings, 0); ?> /> <label for="ImageHeadline_settings[soft_shadows]"><?php _e("Use classic shadows <em>(simple and fast but not as pretty)</em>", 'headlinedomain')?></label> </legend> <table width="100%" cellspacing="2" cellpadding="5" class="editform"> <tr valign="top"> <th width="45%" scope="row"><?php _e('Shadow offset <em>(in pixels)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" name="ImageHeadline_settings[shadow_offset]" value="<?php echo $ImageHeadline_settings['shadow_offset'] ?>" size="2"></td> </tr> <tr valign="top"> <th width="45%" scope="row"><?php _e('First shadow color <em>(in HTML format, e.g. #44CCAA)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" name="ImageHeadline_settings[shadow_first_color]" value="<?php echo $ImageHeadline_settings['shadow_first_color'] ?>" size="8"></td> </tr> <tr valign="top"> <th width="45%" scope="row"><?php _e('Second shadow color <em>(in HTML format, e.g. #44CCAA)</em>:', 'headlinedomain' ) ?></th> <td><input type="text" name="ImageHeadline_settings[shadow_second_color]" value="<?php echo $ImageHeadline_settings['shadow_second_color'] ?>" size="8"></td> </tr> </table> </fieldset> </fieldset> <?php if( ImageHeadline_option_set( 'only_use_imagecreate' ) ) { ?> <input name="ImageHeadline_options[]" type="hidden" id="only_use_imagecreate" value="only_use_imagecreate" /> <?php } ?> <p class="submit"> <input type="submit" name="update_options" value="<?php _e('Update Options') ?>" /> </p> </form> </div> <?php } } else { // Add a filter to the titles so all titles (that have the prepended text) // will be replaced with images. add_filter('the_title', 'imageheadlines', 12); add_action('admin_menu', 'ImageHeadline_add_options_page'); } ?>
cbe1da1d383be4da5fc5715d54e5239b6dfd14a3
[ "PHP" ]
1
PHP
WPPlugins/image-headlines
6e1b83faaa0c18aca6a541373bb3c0dbb9da46f5
23873b785aa71af1704231ee39fd6db5da3ad596
refs/heads/master
<file_sep>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.Date; import java.util.Observable; public class RmiServer extends Observable implements RmiObservableService, Runnable { private static final long serialVersionUID = 1L; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private String response; public RmiServer() { new Thread(this).start(); } @Override public void addObserver(RemoteObserver o) throws RemoteException { WrappedObserver mo = new WrappedObserver(o); addObserver(mo); System.out.println("Added observer :" + mo); } @Override public void run() { while (true) { try { response = br.readLine(); } catch (IOException e) { // ignore } setChanged(); notifyObservers(response); } } public static void main(String[] args) { try { RmiServer obj = new RmiServer(); RmiObservableService stub = (RmiObservableService) UnicastRemoteObject.exportObject(obj, 0); // Bind the remote object ís stub in the registry Registry registry = LocateRegistry.createRegistry(9999); registry.rebind("RmiService", stub); System.err.println("Server ready"); } catch (Exception ex) { ex.printStackTrace(); } } }<file_sep>import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; public class RmiClient extends UnicastRemoteObject implements RemoteObserver { private static final long serialVersionUID = 1L; protected RmiClient() throws RemoteException { super(); } public static void main(String[] args) { try { Registry registry = LocateRegistry.getRegistry(9999); RmiObservableService remoteService = (RmiObservableService) registry.lookup("RmiService"); RmiClient client = new RmiClient(); // Observer remoteService.addObserver(client); // add Observer to Observable } catch (Exception ex) { ex.printStackTrace(); } } @Override public void remoteUpdate(Object observable, Object updateMsg) throws RemoteException { System.out.println("got message :" + updateMsg); } }
5bed334f79adb8569e34439c941bc706a01c53ef
[ "Java" ]
2
Java
smillo/observer-rmi
570f5a038eb609066f67f28653ad287459556e54
6684cd3f3b2582188989f96dd333edfa9441c8eb
refs/heads/master
<file_sep>from docstring_parser import parse import re, os, inspect, importlib # choose package import atomics pkg = atomics # set paths examples_module_path = 'atomics.examples' examples_dir = 'examples/' test_examples_subdir = examples_dir + 'invalid/' doc_examples_subdir = examples_dir + 'valid/' def camel_to_snake(name): return re.sub( '([a-z0-9])([A-Z])', r'\1_\2', re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name), ).lower() def write_setup(f, obj, options): # setup and run problem superclasses = [sc.__name__ for sc in inspect.getmro(obj)] f.write('prob = Problem()\n') if 'Group' in superclasses: f.write('prob.model = ' + obj.__name__ + '(') if len(options) > 0: f.write('\n') for opt in options: f.write(' ' + opt + ',\n') f.write(')\n') elif 'Component' in superclasses: f.write('prob.model = Group()\nprob.model.add_subsystem(') if len(options) > 0: f.write('\n ') f.write('\'example\', ') if len(options) > 0: f.write('\n ') f.write(obj.__name__ + '(') if len(options) > 0: f.write('\n') for opt in options: f.write(' ' + opt + ',\n') f.write('))\n') else: raise TypeError('Example class', obj.__name__, 'is not a Component or Group') f.write('prob.setup(force_alloc_complex=True)\nprob.run_model()') f.write('\n') def get_example_file_name(obj, py_file_path): obj_name_snake_case = camel_to_snake(obj.__name__) prefix = '' example_filename = '' generate_example_script = False if obj_name_snake_case[:len('error_')] == 'error_': prefix = 'error_' generate_example_script = True example_filename = py_file_path.rsplit( '/', 1 )[-1][:-len('.py')] + '_' + obj_name_snake_case[len(prefix):] + '.py' if obj_name_snake_case[:len('example_')] == 'example_': prefix = 'example_' generate_example_script = True example_filename = py_file_path.rsplit( '/', 1 )[-1][:-len('.py')] + '_' + obj_name_snake_case[len(prefix):] + '.py' return generate_example_script, example_filename, prefix def export_examples(): # Python 3.9: use removesuffix package_path = inspect.getfile(pkg)[:-len('__init__.py')] examples_path = package_path + examples_dir test_examples_path = package_path + test_examples_subdir doc_examples_path = package_path + doc_examples_subdir for example in os.listdir(examples_path): suffix = '.py' if example[-len(suffix):] == suffix: py_file_path = (examples_path + example) # gather imports import_statements = [] with open(py_file_path, 'r') as f: import_statements = [] for line in f: l = line.lstrip() if re.match('import', l) or re.match('from', l): import_statements.append(l) # Python 3.9: use removesuffix py_module = importlib.import_module(examples_module_path + '.' + example[:-len(suffix)]) members = inspect.getmembers(py_module) for obj in dict(members).values(): if inspect.isclass(obj): generate_example_script, example_filename, prefix = get_example_file_name( obj, py_file_path) if generate_example_script == True: # collect params docstring = parse(obj.__doc__) var_names = [] options = [] for param in docstring.params: if param.arg_name == 'var': var_names.append(param.description) if param.arg_name == 'option': options.append(param.description) file_path = '' if prefix == 'error_': file_path = test_examples_path + example_filename elif prefix == 'example_': file_path = doc_examples_path + example_filename if file_path != '': print('writing to file', file_path) with open(file_path, 'w') as f: # write import statements f.write('from openmdao.api import Problem\n') for stmt in import_statements: f.write(stmt) f.write('\n\n') # write example class source = re.sub('.*:param.*:.*\n', '', inspect.getsource(obj)) source = re.sub('\n.*"""\n.*"""', '', source) f.write(source) f.write('\n\n') write_setup(f, obj, options) # output values if len(var_names) > 0: f.write('\n') for var in var_names: f.write('print(\'' + var + '\', prob[\'' + var + '\'].shape)\n') f.write('print(prob[\'' + var + '\'])') f.write('\n') f.close() export_examples() <file_sep>Atomics ======= Introduction ------------ Description of ``atomics`` package Example link to OpenMDAO website: `OpenMDAO framework <https://openmdao.org/>`_ Documentation ------------- .. toctree:: :maxdepth: 4 :titlesonly: _src_docs/getting_started.rst <file_sep>Getting Started =============== Make files like this one to write your tutorials! <file_sep> ## Build Docs ```sh make -C docs/ html ``` ## View Generated Docs Open `docs/_build/html/index.html` in your browser. ## What's in this package? - `docs` stores source files and files required by Sphinx and GitHub for generating docs - `_exts` stores extensions for generating docs with extra features like including an n2 diagram - `_build` contains the built docs - `_src_docs` contains docs source files for generating docs - `_static` contains a single file, `custom.css` used to make `jupyter-sphinx` output match the readthedocs theme - `atomics` is where all Python code for the project goes - `.github/workflows/` contains a file that tells GitHub how to build the docs Take a look around inside `docs/index.rst` and `docs/_src_docs/` to get an idea of how to organize your source files. ## Setting up Docs for your Project To set up docs: - Make sure to set `SPHINXPROJ` correctly in `docs/Makefile` and `docs/make.bat` - I'm not sure if you need `docs/requirements.txt`, but leave it in just in case - Use `docs/.embedrc` to use custom directives (may be necesssary only for sphinx_auto_embed, which we no longer use) - Change README on `docs/build-docs.sh` to match project name. - NOTE: `docs/build-docs.sh` works only on Linux. - To test docs, run `make -C docs/ html` from the project root. - Make sure the project name is correct in `docs/conf.py`. - Make sure the author is correct in `docs/conf.py`. - The file `.github/workflows/doc_pages_workflow.yml` is used for GitHub to automatically generate docs whenever someone pushes to the `master` branch - To generate example scripts for use in docs and tests (must be done manually before running Sphinx), use `atomics/utils/generate_example_scripts.py`. - NOTE: You will need to `pip install docstirng_parser` in order to use `generate_example_scripts.py`. `docstring_parser` is not listed as a project dependency in `setup.py`. - NOTE: You will need to make sure that you are importing the correct project within `generate_example_scripts.py`. - NOTE: Follow the examples in `omtools/examples/` to make example classes. `generate_example_scripts.py` will generate the scripts in `valid/` and `invalid/` directories. Use the [Sphinx webpage](https://www.sphinx-doc.org/en/master/) as reference. ## API Docs For the API docs (under `docs/_src_docs/api/`), use [autodoc](https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html). Use `autodoc` to populate `.rst files` in `_src_docs/api/` and add their paths to `docs/index.rst` toctree to include API docs for your classes, functions, etc.
543c8b30b2fd59a07d3e021354f4cf1a70d5de42
[ "Markdown", "Python", "reStructuredText" ]
4
Python
jiy352/doc_test
f0bbc6bafc7f257e6549a3661a82a21d6d90dbc3
6c83700468eb574c086acec78259e9843c050047
refs/heads/master
<repo_name>DJ-Turnschuh/virtual-cash-register<file_sep>/README.md # virtual-cash-register Simple cash register built with HTML/CSS and vanilla JS. Perfect to track your everyday sales of a few products. It uses Local Storage to save your entries. Includes Money In/Out only transactions and a Void Mode. # ez usage Just enter an amount and select a product, then enter the amount given by the customer and select a payment method, finally press enter to register the transaction. Void Mode works exactly the same, just press Void before starting a transaction. # working demo You can view the working demo [HERE](https://luvagu.github.io/virtual-cash-register/) # enjoy! Buy me a beer if you dare [HERE](https://paypal.me/MyPriceRite?locale.x=en_GB) <file_sep>/script.js //---> SELECTORS // side panel const sidebar = document.querySelector('[data-sidebar]') const openBtn = document.querySelector('[data-open]') const closeBtn = document.querySelector('[data-close]') // cash register init form const cashInitForm = document.querySelector('[data-cash-init-form]') const cashInitInput = document.querySelector('[data-cash-init-value]') const submitBtn = document.querySelector('[data-cash-init-submit]') const amendBtn = document.querySelector('[data-cash-init-clear]') const resetRegisterBtn = document.querySelector('[data-register-reset]') // display const displayVoidMode = document.querySelector('[data-display]') const cancelBtn = document.querySelector('[data-cancel]') const restartBtn = document.querySelector('[data-restart]') const prevDisplayText = document.querySelector('[data-prev-operation]') const currDisplayText = document.querySelector('[data-curr-operation]') // keypad buttons const numbers = document.querySelectorAll('[data-number]') const operations = document.querySelectorAll('[data-operation]') const payments = document.querySelectorAll('[data-payment]') const deleteBtn = document.querySelector('[data-delete]') const voidBtn = document.querySelector('[data-void]') const enterBtn = document.querySelector('[data-enter]') // data summary entries const copyBtn = document.querySelector('[data-copy-btn]') const copyAreaClipboard = document.querySelector('[data-area-clipboard]') const sumInitValue = document.querySelector('[data-init-value]') const sumCoffeTotal = document.querySelector('[data-coffe-total]') const sumBeerTotal = document.querySelector('[data-beer-total]') const sumDrinkTotal = document.querySelector('[data-drink-total]') const sumBurgerTotal = document.querySelector('[data-burger-total]') const sumSandwichTotal= document.querySelector('[data-sandwich-total]') const sumMoneyInTotal = document.querySelector('[data-money-in-total]') const sumMoneyOutTotal = document.querySelector('[data-money-out-total]') const sumVoidsTotal = document.querySelector('[data-voids-total]') const sumPaymCashTotal = document.querySelector('[data-payment-cash-total]') const sumPaymCheckTotal = document.querySelector('[data-payment-check-total]') const sumPaymCardTotal = document.querySelector('[data-payment-card-total]') const sumGrandTotal = document.querySelector('[data-grand-total]') // entries html const entriesCount = document.querySelector('[data-entries-count]') const entriesHtml = document.querySelector('[data-entries]') //---> SETUP TODAY'S DATE const date = new Date().toLocaleDateString("en-GB", {year:"numeric", day:"2-digit", month:"2-digit"}) const dateElem = document.querySelector('[data-date]') dateElem.innerText = date //---> LOCALSTORAGE KEYS CONSTANTS const LS_CASH_INIT_VALUE = 'register.cashInitValue' const LS_REGISTER_ENTRIES = 'register.entriesData' const LS_REGISTER_TIMESTAMP = 'register.timestamp' // local storage data let savedEntriesData = JSON.parse(localStorage.getItem(LS_REGISTER_ENTRIES)) || [] let initAmount = localStorage.getItem(LS_CASH_INIT_VALUE) || '' //---> FUNCTIONS // open sidebar function openSidebar() { sidebar.style.width = '250px'; } // close sidebar function closeSidebar() { sidebar.style.width = '0'; } // save entries to localstarage function saveEntriesData() { localStorage.setItem(LS_REGISTER_ENTRIES, JSON.stringify(savedEntriesData)) } // save cash init value to localStorage function saveCashInitValue(e) { e.preventDefault() if (initAmount !== '') { alert('You have already registered the Initial Amount!') resetInput() closeSidebar() return } initAmount = cashInitInput.value localStorage.setItem(LS_CASH_INIT_VALUE, initAmount) localStorage.setItem(LS_REGISTER_TIMESTAMP, Date.now()) resetInput() renderSummaryPane() closeSidebar() } // reset input on form submit function resetInput() { cashInitInput.value = 0 } // check for real data existance function isRealObject(obj) { return obj && obj !== "null" && obj!== "undefined"; } // copy summary text to clipboard function copyToClipboard(elemtext) { const copyText = elemtext.innerText const textarea = document.createElement('textarea') document.body.appendChild(textarea) textarea.value = `REGISTER SUMMARY\n${date}\n\n${copyText}` textarea.select() document.execCommand('copy') document.body.removeChild(textarea) alert('Register Summary copied to clipboard!') } // render entries template function renderTemplate(data) { const date = new Date(data.timestamp) const time = `${date.getHours() < 10 ? '0' + date.getHours().toString() : date.getHours()}:${date.getMinutes() < 10 ? '0' + date.getMinutes().toString() : date.getMinutes()}` entriesHtml.insertAdjacentHTML('afterbegin', ` <div class="entrie__section ${data.class} ${data.voidStatus && 'entrie__voidMode'}"> <p>${data.transactionName} &raquo;&raquo; ${data.transactionValue}</p> <p>${data.tenderName} &raquo;&raquo; ${data.tenderValue}</p> <p>Change &raquo;&raquo; ${data.change}</p> <p>Time &raquo;&raquo; ${time}</p> </div> `) } // rounding accurately to n decimal places function roundToTwoDecimals(n, d) { // where n = number, and d = decimal places return Number(Math.round(n + 'e' + d) + 'e-' + d) } // render summary pane function renderSummaryPane() { const initValue = initAmount === '' ? '0.00' : initAmount sumInitValue.innerText = initValue if (isRealObject(savedEntriesData)) { const coffeTotal = roundToTwoDecimals(savedEntriesData.map(({transactionName: name, transactionValue: value}) => ({name, value})) .filter(e => e.name == 'Coffe') .reduce((a,cv) => a + parseFloat(cv.value), 0), 2) sumCoffeTotal.innerText = coffeTotal != 0 ? coffeTotal : '0.00' const beerTotal = roundToTwoDecimals(savedEntriesData.map(({transactionName: name, transactionValue: value}) => ({name, value})) .filter(e => e.name == 'Beer') .reduce((a,cv) => a + parseFloat(cv.value), 0), 2) sumBeerTotal.innerText = beerTotal != 0 ? beerTotal : '0.00' const drinkTotal = roundToTwoDecimals(savedEntriesData.map(({transactionName: name, transactionValue: value}) => ({name, value})) .filter(e => e.name == 'Drink') .reduce((a,cv) => a + parseFloat(cv.value), 0), 2) sumDrinkTotal.innerText = drinkTotal != 0 ? drinkTotal : '0.00' const burgerTotal = roundToTwoDecimals(savedEntriesData.map(({transactionName: name, transactionValue: value}) => ({name, value})) .filter(e => e.name == 'Burger') .reduce((a,cv) => a + parseFloat(cv.value), 0), 2) sumBurgerTotal.innerText = burgerTotal != 0 ? burgerTotal : '0.00' const sandwichTotal = roundToTwoDecimals(savedEntriesData.map(({transactionName: name, transactionValue: value}) => ({name, value})) .filter(e => e.name == 'Sandwich') .reduce((a,cv) => a + parseFloat(cv.value), 0), 2) sumSandwichTotal.innerText = sandwichTotal != 0 ? sandwichTotal : '0.00' const moneyInTotal = roundToTwoDecimals(savedEntriesData.map(({transactionName: name, transactionValue: value}) => ({name, value})) .filter(e => e.name == 'Money-In') .reduce((a,cv) => a + parseFloat(cv.value), 0), 2) sumMoneyInTotal.innerText = moneyInTotal != 0 ? moneyInTotal : '0.00' const moneyOutTotal = roundToTwoDecimals(savedEntriesData.map(({transactionName: name, transactionValue: value}) => ({name, value})) .filter(e => e.name == 'Money-Out') .reduce((a,cv) => a + parseFloat(cv.value), 0), 2) sumMoneyOutTotal.innerText = moneyOutTotal != 0 ? moneyOutTotal : '0.00' const voidsTotal = roundToTwoDecimals(savedEntriesData.map(({voidAmount}) => ({voidAmount})) .reduce((a,cv) => a + parseFloat(cv.voidAmount), 0), 2) sumVoidsTotal.innerText = voidsTotal != 0 ? voidsTotal : '0.00' const paymCashTotal = roundToTwoDecimals(savedEntriesData.map(({tenderName: name, tenderAmountIn: value}) => ({name, value})) .filter(e => e.name == 'Cash') .reduce((a,cv) => a + parseFloat(cv.value), 0) + parseFloat(initValue), 2) sumPaymCashTotal.innerText = paymCashTotal != 0 ? paymCashTotal : '0.00' const paymCheckTotal = roundToTwoDecimals(savedEntriesData.map(({tenderName: name, tenderAmountIn: value}) => ({name, value})) .filter(e => e.name == 'Check') .reduce((a,cv) => a + parseFloat(cv.value), 0), 2) sumPaymCheckTotal.innerText = paymCheckTotal != 0 ? paymCheckTotal : '0.00' const paymCardTotal = roundToTwoDecimals(savedEntriesData.map(({tenderName: name, tenderAmountIn: value}) => ({name, value})) .filter(e => e.name == 'Card') .reduce((a,cv) => a + parseFloat(cv.value), 0), 2) sumPaymCardTotal.innerText = paymCardTotal != 0 ? paymCardTotal : '0.00' const grandTotal = roundToTwoDecimals(savedEntriesData.map(({transactionValue}) => ({transactionValue})) .reduce((a,cv) => a + parseFloat(cv.transactionValue) , 0) + parseFloat(initValue), 2) sumGrandTotal.innerText = grandTotal != 0 ? grandTotal : '0.00' entriesCount.innerText = savedEntriesData.length } else { sumCoffeTotal.innerText = '0.00' sumBeerTotal.innerText = '0.00' sumDrinkTotal.innerText = '0.00' sumBurgerTotal.innerText = '0.00' sumMoneyInTotal.innerText = '0.00' sumMoneyOutTotal.innerText = '0.00' sumSandwichTotal.innerText = '0.00' sumVoidsTotal.innerText = '0.00' sumPaymCashTotal.innerText = initValue sumPaymCheckTotal.innerText = '0.00' sumPaymCardTotal.innerText = '0.00' sumGrandTotal.innerText = initValue entriesCount.innerText = '0' } } // render entries pane function renderEntriesPane() { if (isRealObject(savedEntriesData)) { // reset entriesHtml before update entriesHtml.innerHTML = '' savedEntriesData.sort((a,b) => a.timestamp > b.timestamp).forEach(e => { const data = { timestamp: e.timestamp, class: e.class, transactionName: e.transactionName, transactionValue: e.transactionValue, tenderName: e.tenderName, tenderValue: e.tenderValue, change: e.change, voidStatus: e.voidStatus } renderTemplate(data) }) } else { // reset entriesHtml anyway entriesHtml.innerHTML = '' } } //---> CASH INIT FORM LISTENERS cashInitInput.addEventListener('input', () => { cashInitInput.value = cashInitInput.value.replace(/[^.\d]/g, '') .replace(/^(\d*\.?)|(\d*)\.?/g, "$1$2") }) submitBtn.addEventListener('click', saveCashInitValue) amendBtn.addEventListener('click', (e) => { e.preventDefault() if (initAmount === '') { alert('Nothing to modify, you must first register the Initial Amount!') closeSidebar() return } alert('The Initial Amount has been eliminated, you can now enter a new value!') localStorage.removeItem(LS_CASH_INIT_VALUE) // localStorage.removeItem(LS_REGISTER_TIMESTAMP) initAmount = '' renderSummaryPane() }) resetRegisterBtn.addEventListener('click', (e) => { e.preventDefault() if (savedEntriesData.length < 1 && initAmount === '') { alert('Nothing to delete!') closeSidebar() return } if (confirm('All data entered will be deleted. Are you sure you want to proceed with this operation?')) { // reset our local variables and localstorage items savedEntriesData = [] initAmount = '' localStorage.removeItem(LS_CASH_INIT_VALUE) localStorage.removeItem(LS_REGISTER_ENTRIES) localStorage.removeItem(LS_REGISTER_TIMESTAMP) // reset entriesHtml renderSummaryPane() renderEntriesPane() closeSidebar() } }) openBtn.addEventListener('click', openSidebar) closeBtn.addEventListener('click', closeSidebar) copyBtn.addEventListener('click', () => { copyToClipboard(copyAreaClipboard) }) //---> REGISTER CLASS class Register { constructor(prevDisplayText, currDisplayText) { this.prevDisplayText = prevDisplayText this.currDisplayText = currDisplayText this.allClear() } allClear() { this.prevDisplayText.removeAttribute('data-before') this.prevDisplayText.innerText = '' this.currDisplayText.removeAttribute('data-before') this.currDisplayText.innerText = '' this.transaction = '' this.payment = '' this.entry = '' this.entryTran = '' this.entryPaym = '' this.tempEntry = '' this.className = '' this.currentEntry = '' this.operation = undefined this.change = '' this.voidMode = false this.voidModeAmount = '' } delete() { this.currentEntry = this.currentEntry.toString().slice(0, -1) } appendNumber(number) { if (number === '.' && this.currentEntry.includes('.')) return this.currentEntry = this.currentEntry.toString() + number.toString() // console.log('currentEntry >>>', this.currentEntry) } enableEnter() { enterBtn.removeAttribute('disabled') this.disableAllButEnter() } disableEnter() { enterBtn.setAttribute('disabled', 'disabled') } disableAllButEnter() { numbers.forEach(e => e.setAttribute('disabled', 'disabled')) operations.forEach(e => e.setAttribute('disabled', 'disabled')) payments.forEach(e => e.setAttribute('disabled', 'disabled')) deleteBtn.setAttribute('disabled', 'disabled') voidBtn.setAttribute('disabled', 'disabled') } enablePayments() { payments.forEach(e => e.removeAttribute('disabled')) } enableAllButEnter() { numbers.forEach(e => e.removeAttribute('disabled')) operations.forEach(e => e.removeAttribute('disabled')) deleteBtn.removeAttribute('disabled') voidBtn.removeAttribute('disabled') } resetBtShowHide() { restartBtn.classList.toggle('hidden') } resetScreen() { this.allClear() this.enableAllButEnter() this.resetBtShowHide() this.removeVoidMode() } cancelBtShowHide() { cancelBtn.classList.toggle('hidden') } cancelOperation() { this.allClear() this.enableAllButEnter() this.cancelBtShowHide() this.removeVoidMode() } removeVoidMode() { displayVoidMode.classList.remove('voidMode') voidBtn.classList.remove('voidBtnOn') } voidTransaction() { if (this.voidMode) { this.voidMode = false this.removeVoidMode() // console.log('void >>>', this.voidMode) } else { this.voidMode = true displayVoidMode.classList.add('voidMode') voidBtn.classList.add('voidBtnOn') // console.log('void >>>', this.voidMode) } } chooseOperation(type, entry, className) { if (this.currentEntry === '') return this.operation = type this.entry = entry if (this.operation === 'tp') { this.transaction = this.voidMode ? `-${this.currentEntry}` : this.currentEntry this.entryTran = entry this.className = className this.voidModeAmount = this.voidMode ? this.currentEntry : 0 this.enablePayments() } else if (this.operation === 'tn') { this.transaction = this.voidMode ? this.currentEntry : `-${this.currentEntry}` this.payment = 0 this.entryTran = entry this.entryPaym = 'Cash' this.tempEntry = 'Cash' this.currentEntry = this.payment this.className = className this.voidModeAmount = this.currentEntry ? this.transaction : 0 this.updateDisplay() this.enableEnter() this.cancelBtShowHide() return } else { this.payment = this.voidMode ? `-${this.currentEntry}` : this.currentEntry this.entryPaym = entry if (parseFloat(this.payment) < parseFloat(this.transaction)) { this.operation = 'tp' this.currentEntry = '' this.payment = '' this.entryPaym = '' alert(`The Payment Method cannot be less than the transaction, try again!`) this.updateDisplay() return } this.enableEnter() this.cancelBtShowHide() } this.currentEntry = '' } entriesData() { const data = { timestamp: Date.now(), class: this.className, transactionName: this.entryTran, transactionValue: this.transaction, tenderName: this.entryPaym, tenderValue: this.payment, tenderAmountIn: this.transaction, voidStatus: this.voidMode, voidAmount: this.voidModeAmount, change: this.change } savedEntriesData.push(data) // console.log('savedEntriesData', savedEntriesData) // only render the current entry object renderTemplate(data) // save data to local storage saveEntriesData() // this renders the whole localStorage object. now it'd done on page reload //renderEntriesPane() } roundAccurately(n, d) { // where n = number, and d = decimal places return Number(Math.round(n + 'e' + d) + 'e-' + d) } compute() { const tran = parseFloat(this.transaction) const paym = parseFloat(this.payment) if (isNaN(tran) || isNaN(paym)) return this.change = this.operation === 'tn' ? this.roundAccurately(Math.abs(tran), 2) : this.roundAccurately((paym - tran), 2) // this.operation = undefined // this.transaction = '' // this.payment = '' // this.currentEntry = '' } formatNumber(number) { const stringNum = number.toString() const intDigits = parseFloat(stringNum.split('.')[0]) const decimalDigits = stringNum.split('.')[1] let intDisplay if (isNaN(intDigits)) { intDisplay = '' } else { intDisplay = intDigits.toLocaleString('en-GB', { maximumFractionDigits: 0 }) } if (decimalDigits != null) { return `${intDisplay}.${decimalDigits}` } else { return intDisplay } } updateDisplay() { this.currDisplayText.innerText = this.formatNumber(this.currentEntry) switch(this.operation) { case 'tp': this.prevDisplayText.innerText = this.formatNumber(this.transaction) this.prevDisplayText.setAttribute('data-before', this.entry) break case 'tn': this.prevDisplayText.innerText = this.formatNumber(this.transaction) this.prevDisplayText.setAttribute('data-before', this.entry) this.currDisplayText.innerText = this.formatNumber(this.payment) this.currDisplayText.setAttribute('data-before', this.tempEntry) break case 'pm': this.prevDisplayText.innerText = this.formatNumber(this.transaction) this.prevDisplayText.setAttribute('data-before', this.entryTran) this.currDisplayText.innerText = this.formatNumber(this.payment) this.currDisplayText.setAttribute('data-before', this.entryPaym) break default: this.prevDisplayText.innerText = '' } } updateDisplayFinal() { this.compute() if (this.change === '') return this.prevDisplayText.innerText = '' this.prevDisplayText.removeAttribute('data-before') this.currDisplayText.innerText = `£ ${this.formatNumber(this.change)}` this.currDisplayText.setAttribute('data-before', 'CHANGE') this.entriesData() this.resetBtShowHide() this.cancelBtShowHide() this.disableEnter() // console.log('operation >>>', this.operation) // console.log('transaction >>>', this.transaction) // console.log('transaction entry >>>', this.entryTran) // console.log('payment >>>', this.payment) // console.log('payment entry >>>', this.entryPaym) // console.log('change >>>', this.change) // console.log('class >>>', this.className) // console.log('void >>>', this.voidMode) } } //---> SETUP REGISTER const register = new Register(prevDisplayText, currDisplayText) //---> REGISTER LISTENERS numbers.forEach(number => { number.addEventListener('click', () => { register.appendNumber(number.innerText) register.updateDisplay() }) }) deleteBtn.addEventListener('click', () => { register.delete() register.updateDisplay() }) operations.forEach(operation => { operation.addEventListener('click', () => { register.chooseOperation(operation.dataset.operation, operation.dataset.entry, operation.dataset.class) register.updateDisplay() }) }) payments.forEach(payment => { payment.addEventListener('click', () => { register.chooseOperation(payment.dataset.payment, payment.dataset.entry, '') register.updateDisplay() }) }) voidBtn.addEventListener('click', () => { register.voidTransaction() }) enterBtn.addEventListener('click', () => { register.updateDisplayFinal() renderSummaryPane() // renderEntriesPane() }) restartBtn.addEventListener('click', () => { register.resetScreen() }) cancelBtn.addEventListener('click', () => { register.cancelOperation() }) //---> ToDo // const numbersKeysAndDot = [48,96,49,97,50,98,51,99,52,100,53,101,54,102,55,103,56,104,57,105,110,190] // const deleteKeys = [8,46] // const escapeKey = 27 // const enterKey = 13 // if (initAmount != 0) { // document.addEventListener('keydown', e => { // console.log(e) // e.preventDefault(); // if (numbersKeysAndDot.indexOf(e.keyCode) >= 0) { // register.appendNumber(e.key) // register.updateDisplay() // } else if (deleteKeys.indexOf(e.keyCode) >= 0) { // register.delete() // register.updateDisplay() // } else if (escapeKey === e.keyCode) { // register.allClear() // } else if (enterKey === e.keyCode) { // register.updateDisplayFinal() // } else { // return false; // } // }) // } //---> LOAD SAVED DATA ON REFRESH if (savedEntriesData.length > 0 || initAmount !== '') { renderSummaryPane() renderEntriesPane() } // Todo : // 1. disable payment methods before a transaction is set Tip: separate them into their own event listenes ***DONE*** // 2. finish implementing the void mode ***DONE*** // 3. add cancel/reset functionality after void is pressed and after payment is set but before enter is pressed ***DONE*** // 4. render the sumary list on the fly and not from local storage during a live session ***DONE*** // 5. enable toggle keboard keystrokes when cash init is set Tip: use isSavedInitValue to toggle the function // 6. prevent register entries if entries from the previous day haven't been reset // 7. convert the app to a PWA ***DONE***
284d01caa35cda7313a3b055de17a7aabb250c97
[ "Markdown", "JavaScript" ]
2
Markdown
DJ-Turnschuh/virtual-cash-register
c3914e02ab1b4acaaf7701d8afd594b2f6f3de3e
1efb4d0e2713a99a78f35f3bd255716a67cd2882
refs/heads/main
<file_sep>import { LightningElement, api, wire } from 'lwc'; import { getRecord, getFieldValue } from 'lightning/uiRecordApi'; import { NavigationMixin } from 'lightning/navigation'; import SIGNATURE_FIELD from '@salesforce/schema/Signature__c'; import NAME_FIELD from '@salesforce/schema/Signature__c.Name'; import PHONE_FIELD from '@salesforce/schema/Signature__c.Phone__c'; import MOBILE_PHONE_FIELD from '@salesforce/schema/Signature__c.Mobile_Phone__c'; import EMAIL_FIELD from '@salesforce/schema/Signature__c.Email__c'; //import calendly from '@salesforce/resourceUrl/calendly'; //import { loadStyle, loadScript } from 'lightning/platformResourceLoader'; // const PROPERTY_FIELDS = [SIGNATURE_FIELD]; const SIGNATURE_FIELDS = [ NAME_FIELD, PHONE_FIELD, MOBILE_PHONE_FIELD, EMAIL_FIELD ]; export default class Signature extends NavigationMixin(LightningElement) { @api recordId; signatureFields = SIGNATURE_FIELDS; @wire(getRecord, { recordId: '$recordId', fields: SIGNATURE_FIELD }) property; get signatureId() { return getFieldValue(this.property.data, SIGNATURE_FIELD); } //loadScript(this, calendly + '/widget.js').then(() => { // Calendly._autoLoadInlineWidgets(); //}); // handleNavigateToRecord() { // this[NavigationMixin.Navigate]({ // type: 'standard__recordPage', // attributes: { // recordId: this.brokerId, // objectApiName: 'Property__c', // actionName: 'view' // } // }); // } }
64d84bfa725c3ae66343aec5160342b08481f51d
[ "JavaScript" ]
1
JavaScript
bmp4070/signature_with_calendly
6827744accfbc281cb668261e3449d62f91630e4
9f7ddface4b2dd8dda1308a436d53b285b6ea09e
refs/heads/master
<repo_name>thoughtstile-thinkful/noteful-api-heroku-server<file_sep>/test/fixtures/folders.fixtures.js 'use strict'; function makeFoldersArray() { return [ { id: 'b0715efe-ffaf-11e8-8eb2-f2801f1b9fd1', name: 'Important' }, { id: 'b07161a6-ffaf-11e8-8eb2-f2801f1b9fd1', name: 'Super' }, { id: 'b07162f0-ffaf-11e8-8eb2-f2801f1b9fd1', name: 'Spangley' } ]; } module.exports = { makeFoldersArray }; <file_sep>/migrations/002.do.create_noteful_folders.sql CREATE TABLE noteful_folders ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), name TEXT NOT NULL ); ALTER TABLE noteful_notes ADD COLUMN folder_id UUID REFERENCES noteful_folders(id) ON DELETE SET NULL;<file_sep>/src/examples/examples-router.js const path = require('path'); const express = require('express'); const xss = require('xss'); const ExamplesService = require('./examples-service'); const examplesRouter = express.Router(); const jsonParser = express.json(); const serializeExample = example => ({ id: example.id, style: example.style, title: xss(example.title), content: xss(example.content), date_published: example.date_published, author: example.author }); examplesRouter .route('/') .get((req, res, next) => { ExamplesService.getAllExamples(req.app.get('db')) .then(examples => { res.json(examples); }) .catch(next); }) .post(jsonParser, (req, res, next) => { const { title, content, style, author } = req.body; const newExample = { title, content, style }; for (const [key, value] of Object.entries(newExample)) { // eslint-disable-next-line eqeqeq if (value == null) { return res.status(400).json({ error: { message: `Missing '${key}' in request body` } }); } } newExample.author = author; ExamplesService.insertExample(req.app.get('db'), newExample) .then(example => { res .status(201) .location(path.posix.join(req.originalUrl, `/${example.id}`)); res.json(serializeExample(example)); }) .catch(next); }); examplesRouter .route('/:example_id') .all((req, res, next) => { ExamplesService.getById(req.app.get('db'), req.params.example_id) .then(example => { if (!example) { return res.status(404).json({ error: { message: "Example doesn't exist" } }); } res.example = example; // save the example for the next middleware next(); // don't forget to call next so the next middleware happens! }) .catch(next); }) .get((req, res, next) => { res.json(serializeExample(res.example)); }) .delete((req, res, next) => { ExamplesService.deleteExample(req.app.get('db'), req.params.example_id) .then(() => { res.status(204).end(); }) .catch(next); }) .patch(jsonParser, (req, res, next) => { const { title, content, style } = req.body; const exampleToUpdate = { title, content, style }; const numberOfValues = Object.values(exampleToUpdate).filter(Boolean) .length; if (numberOfValues === 0) { return res.status(400).json({ error: { message: "Request body must contain either 'title', 'style' or 'content'" } }); } ExamplesService.updateExample( req.app.get('db'), req.params.example_id, exampleToUpdate ) .then(numRowsAffected => { res.status(204).end(); }) .catch(next); }); module.exports = examplesRouter; <file_sep>/migrations/001.do.create_noteful_notes.sql CREATE extension IF NOT EXISTS "uuid-ossp"; CREATE TABLE noteful_notes ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), name TEXT NOT NULL, modified TIMESTAMP NOT NULL DEFAULT NOW(), content TEXT );<file_sep>/migrations/002.undo.create_noteful_folders.sql ALTER TABLE noteful_notes DROP COLUMN folder_id; DROP TABLE IF EXISTS noteful_folders;<file_sep>/test/examples-endpoints.spec.js process.env.TZ = 'UTC'; require('dotenv').config(); const { expect } = require('chai'); const supertest = require('supertest'); const knex = require('knex'); const app = require('../src/app'); const { makeExamplesArray, makeMaliciousExample } = require('./fixtures/examples.fixtures'); const { makeUsersArray } = require('./fixtures/users.fixtures'); describe.skip('Examples Endpoints', function() { let db; before('make knex instance', () => { db = knex({ client: 'pg', connection: process.env.TEST_DATABASE_URL }); app.set('db', db); }); after('disconnect from db', () => db.destroy()); before('clean the table', () => db.raw('TRUNCATE blogful_examples, blogful_users RESTART IDENTITY CASCADE') ); afterEach('cleanup', () => db.raw('TRUNCATE blogful_examples, blogful_users RESTART IDENTITY CASCADE') ); describe(`GET /api/examples`, () => { context(`Given no examples`, () => { it(`responds with 200 and an empty list`, () => { return supertest(app) .get('/api/examples') .expect(200, []); }); }); context('Given there are examples in the database', () => { const testUsers = makeUsersArray(); const testExamples = makeExamplesArray(); beforeEach('insert examples', () => { return db .into('blogful_users') .insert(testUsers) .then(() => { return db.into('blogful_examples').insert(testExamples); }); }); it('responds with 200 and all of the examples', () => { return supertest(app) .get('/api/examples') .expect(200, testExamples); }); }); context(`Given an XSS attack example`, () => { const testUsers = makeUsersArray(); const { maliciousExample, expectedExample } = makeMaliciousExample(); beforeEach('insert malicious example', () => { return db .into('blogful_users') .insert(testUsers) .then(() => { return db.into('blogful_examples').insert([maliciousExample]); }); }); // it('removes XSS attack content', () => { // return supertest(app) // .get(`/api/examples`) // .expect(200) // .expect(res => { // expect(res.body[0].title).to.eql(expectedExample.title); // expect(res.body[0].content).to.eql(expectedExample.content); // }); // }); }); }); describe(`GET /api/examples/:example_id`, () => { context(`Given no examples`, () => { it(`responds with 404`, () => { const exampleId = 123456; return supertest(app) .get(`/api/examples/${exampleId}`) .expect(404, { error: { message: `Example doesn't exist` } }); }); }); context('Given there are examples in the database', () => { const testUsers = makeUsersArray(); const testExamples = makeExamplesArray(); beforeEach('insert examples', () => { return db .into('blogful_users') .insert(testUsers) .then(() => { return db.into('blogful_examples').insert(testExamples); }); }); it('responds with 200 and the specified example', () => { const exampleId = 2; const expectedExample = testExamples[exampleId - 1]; return supertest(app) .get(`/api/examples/${exampleId}`) .expect(200, expectedExample); }); }); context(`Given an XSS attack example`, () => { const testUsers = makeUsersArray(); const { maliciousExample, expectedExample } = makeMaliciousExample(); beforeEach('insert malicious example', () => { return db .into('blogful_users') .insert(testUsers) .then(() => { return db.into('blogful_examples').insert([maliciousExample]); }); }); // it('removes XSS attack content', () => { // return supertest(app) // .get(`/api/examples/${maliciousExample.id}`) // .expect(200) // .expect(res => { // expect(res.body.title).to.eql(expectedExample.title); // expect(res.body.content).to.eql(expectedExample.content); // }); // }); }); }); describe(`POST /api/examples`, () => { const testUsers = makeUsersArray(); beforeEach('insert malicious example', () => { return db.into('blogful_users').insert(testUsers); }); it(`creates an example, responding with 201 and the new example`, () => { const newExample = { title: 'Test new example', style: 'Listicle', content: 'Test new example content...' }; return supertest(app) .post('/api/examples') .send(newExample) .expect(201) .expect(res => { expect(res.body.title).to.eql(newExample.title); expect(res.body.style).to.eql(newExample.style); expect(res.body.content).to.eql(newExample.content); expect(res.body).to.have.property('id'); expect(res.headers.location).to.eql(`/api/examples/${res.body.id}`); const expected = new Intl.DateTimeFormat('en-US').format(new Date()); const actual = new Intl.DateTimeFormat('en-US').format( new Date(res.body.date_published) ); expect(actual).to.eql(expected); }) .then(res => supertest(app) .get(`/api/examples/${res.body.id}`) .expect(res.body) ); }); const requiredFields = ['title', 'style', 'content']; requiredFields.forEach(field => { const newExample = { title: 'Test new example', style: 'Listicle', content: 'Test new example content...' }; it(`responds with 400 and an error message when the '${field}' is missing`, () => { delete newExample[field]; return supertest(app) .post('/api/examples') .send(newExample) .expect(400, { error: { message: `Missing '${field}' in request body` } }); }); }); it('removes XSS attack content from response', () => { const { maliciousExample, expectedExample } = makeMaliciousExample(); return supertest(app) .post(`/api/examples`) .send(maliciousExample) .expect(201) .expect(res => { expect(res.body.title).to.eql(expectedExample.title); expect(res.body.content).to.eql(expectedExample.content); }); }); }); describe(`DELETE /api/examples/:example_id`, () => { context(`Given no examples`, () => { it(`responds with 404`, () => { const exampleId = 123456; return supertest(app) .delete(`/api/examples/${exampleId}`) .expect(404, { error: { message: `Example doesn't exist` } }); }); }); context('Given there are examples in the database', () => { const testUsers = makeUsersArray(); const testExamples = makeExamplesArray(); beforeEach('insert examples', () => { return db .into('blogful_users') .insert(testUsers) .then(() => { return db.into('blogful_examples').insert(testExamples); }); }); it('responds with 204 and removes the example', () => { const idToRemove = 2; const expectedExamples = testExamples.filter( example => example.id !== idToRemove ); return supertest(app) .delete(`/api/examples/${idToRemove}`) .expect(204) .then(res => supertest(app) .get(`/api/examples`) .expect(expectedExamples) ); }); }); }); describe(`PATCH /api/examples/:example_id`, () => { context(`Given no examples`, () => { it(`responds with 404`, () => { const exampleId = 123456; return supertest(app) .delete(`/api/examples/${exampleId}`) .expect(404, { error: { message: `Example doesn't exist` } }); }); }); context('Given there are examples in the database', () => { const testUsers = makeUsersArray(); const testExamples = makeExamplesArray(); beforeEach('insert examples', () => { return db .into('blogful_users') .insert(testUsers) .then(() => { return db.into('blogful_examples').insert(testExamples); }); }); it('responds with 204 and updates the example', () => { const idToUpdate = 2; const updateExample = { title: 'updated example title', style: 'Interview', content: 'updated example content' }; const expectedExample = { ...testExamples[idToUpdate - 1], ...updateExample }; return supertest(app) .patch(`/api/examples/${idToUpdate}`) .send(updateExample) .expect(204) .then(res => supertest(app) .get(`/api/examples/${idToUpdate}`) .expect(expectedExample) ); }); it(`responds with 400 when no required fields supplied`, () => { const idToUpdate = 2; return supertest(app) .patch(`/api/examples/${idToUpdate}`) .send({ irrelevantField: 'foo' }) .expect(400, { error: { message: `Request body must contain either 'title', 'style' or 'content'` } }); }); it(`responds with 204 when updating only a subset of fields`, () => { const idToUpdate = 2; const updateExample = { title: 'updated example title' }; const expectedExample = { ...testExamples[idToUpdate - 1], ...updateExample }; return supertest(app) .patch(`/api/examples/${idToUpdate}`) .send({ ...updateExample, fieldToIgnore: 'should not be in GET response' }) .expect(204) .then(res => supertest(app) .get(`/api/examples/${idToUpdate}`) .expect(expectedExample) ); }); }); }); }); <file_sep>/src/examples/examples-service.js const ExamplesService = { getAllExamples(knex) { return knex.select('*').from('blogful_examples'); }, insertExample(knex, newExample) { return knex .insert(newExample) .into('blogful_examples') .returning('*') .then(rows => { return rows[0]; }); }, getById(knex, id) { return knex .from('blogful_examples') .select('*') .where('id', id) .first(); }, deleteExample(knex, id) { return knex('blogful_examples') .where({ id }) .delete(); }, updateExample(knex, id, newExampleFields) { return knex('blogful_examples') .where({ id }) .update(newExampleFields); } }; module.exports = ExamplesService;
cbb4e0d271d812424944afbcbdf293ff11fa2b5d
[ "JavaScript", "SQL" ]
7
JavaScript
thoughtstile-thinkful/noteful-api-heroku-server
1412ab8b24290760b5855fc618b8c2e60a4af881
45ef891b1134041acb204f4479137c4bf7ed5146
refs/heads/master
<file_sep>//: Playground - noun: a place where people can play import UIKit // Basic class set up class Name { // Properties, init, funcs here } // Let's create a simple Person class class Person { var name: String var age: Int init(name: String, age: Int) { self.name = name self.age = age } func getName() -> String { return "Your name is \(name)" } } // Now we can create an object of Person var person1 = Person(name: "Farhan", age: 21) // We can read the properties like so person1.name person1.age // We can even add functions inside our class, look in the Person class // We can call this function like so person1.getName() // Reference type // classes are reference types, meaning when we create a class we are storing it into memory and simply referncing to that place in memory. // let's visualize it. // Create a new person2 class var person2 = Person(name: "Steve", age: 56) // Create another person3, but make it equal to person 2 var person3 = person2 // Change the age of person3 person3.age = 35 // now if you read both person2 & 3, you'll see there equal to eachother person2.age person3.age // Why is this? // When we store a class we are storing this information in memory and person1 is holding a reference to where that data is. // When we make person3 equal to person2, we simply look at that same reference place for that data. // Person3 is NOT a copy of person2. It IS person2. <file_sep># Basic Examples of how to work with classes in Swift. For more detailed explainations checkout my article on <a href="https://medium.com/@farhansyed/classes-in-swift-for-newbies-529145228ba">Medium</a>.
3d5e489094147c190cb3b6f9d4bb2b0bc13c45d0
[ "Swift", "Markdown" ]
2
Swift
darkprgrmmr/basicsClassesInSwift
e54d97e35be2e755f6694cf8f2c364d2747fdf52
fb6d89b2bd227d66c10b5d716afff75addcabe19
refs/heads/master
<file_sep><?php Route::group(['namespace' => 'Api'], function ($router) { $router->post('/login', 'AuthController@login')->name('auth.login'); Route::group(['middleware' => 'auth:api'], function ($router) { $router->post('/logout', 'AuthController@logout')->name('auth.logout'); $router->match(['PUT', 'PATCH'], '/auth/user', 'UserController@update')->name('auth.update'); }); $router->get('/stops', 'StopController@index')->name('stop.index'); $router->get('/random-location', 'GeneratorController@location')->name('random.location'); }); <file_sep><?php namespace Tests\Unit; use Tests\TestCase; use Modules\Transportation\Calculator; class CalculatorTest extends TestCase { public function testGetDistance() { $firstPoint = [ 'latitude' => '32.9697', 'longitude' => '-98.53506', ]; $secondPoint = [ 'latitude' => '29.46786', 'longitude' => '14.000', ]; $result = (new Calculator)->getDistance($firstPoint, $secondPoint)->toKilometer(); $this->assertTrue("10,085" === $result); } } <file_sep><?php namespace Tests\Unit; use Tests\TestCase; use Modules\Base\Models\User; use Illuminate\Http\Request; class AuthenticationManagerTest extends TestCase { public function testLogin() { $manager = app('authentication.manager'); $request = (new Request)->merge([ // 'client_id' => 2, // 'client_secret' => '<KEY>', 'email' => '<EMAIL>', 'password' => '<PASSWORD>', // 'grant_type' => 'password' ]); $manager->login($request); } } <file_sep><?php namespace Tests\Unit; use Tests\TestCase; use Modules\Transportation\Transportation; use Modules\Transportation\Exceptions\MissingLocationException; class MissingLocationExceptionsTest extends TestCase { public function testMissingLocationException() { $this->expectException(MissingLocationException::class); $bus = app('bus'); $bus2 = app('bus'); $locator = Transportation::make()->to($bus)->from($bus2)->calculate(); } } <file_sep><?php namespace Modules\Base\Http\Controllers; class BaseController extends Controller { /** * Base view for front side * * @return void */ public function index() { return view('base'); } } <file_sep><?php namespace Modules\Authentication; use DateInterval; use Illuminate\Contracts\Validation\Factory as ValidationFactory; use Laravel\Passport\Bridge\PersonalAccessGrant; use Laravel\Passport\Http\Controllers\PersonalAccessTokenController; use Laravel\Passport\TokenRepository; use League\OAuth2\Server\AuthorizationServer; class PassportManager { public function __construct() { $oauth2 = app()->make(AuthorizationServer::class); $oauth2->enableGrantType( new PersonalAccessGrant, new DateInterval('P1W') ); } /** * Generate a personal token. * * @param [type] $request * @param [type] $user * * @return void */ public function personalToken($request, $user = null) { $request ->setUserResolver(function () use ($user) { return $user; }) ->merge([ 'name' => sprintf('Personal Token for [%s]', $request->email), 'scope' => $request->scope ?? [], ]); $controller = new PersonalAccessTokenController( resolve(TokenRepository::class), resolve(ValidationFactory::class) ); return $controller->store($request); } } <file_sep><?php namespace Modules\Transportation\Contracts; interface LocatorInterface { /** * Undocumented function * * @param [type] $latitude * * @return void */ public function setLatitude($latitude); /** * Undocumented function * * @param [type] $longitude * * @return void */ public function setLongitude($longitude); /** * Undocumented function * * @return void */ public function getLatitude(); /** * Undocumented function * * @return void */ public function getLongitude(); } <file_sep>[![Build Status](https://travis-ci.com/napoleon101392/acme.svg?branch=master)](https://travis-ci.com/napoleon101392/acme) # To start with the backend ```bash composer install php artisan migrate --seed php artisan passport:install ``` If you get an error for some reason and it regards to Application Key, try to regenerate your local token ```bash php artisan key:generate ``` # To start with the frontend ```bash cd ./@frontend yarn install yarn build yarn start ``` <file_sep>const API_HOST = 'http://localhost:8001'; export const searchNearbyStops = async ({ latitude, longitude }) => { const res = await fetch(`${API_HOST}/api/stops?latitude=${latitude}&longitude=${longitude}`, { headers: { Accept: 'application/json', } }); return await res.json(); // return [ // { // name: 'Bus A', // lat: '1.330913', // lng: '103.876913', // }, // { // name: 'Bus B', // lat: '1.330915', // lng: '103.876915', // }, // { // name: 'Bus C', // lat: '1.330921', // lng: '103.876921', // }, // { // name: 'Bus D', // lat: '1.330925', // lng: '103.876925', // }, // ]; } export const getRandomLatLng = async () => { const res = await fetch(`${API_HOST}/api/random-location`, { headers: { Accept: 'application/json', } }); return (await res.json()).content; } export const loginAttempt = async (email, password) => { // const res = await fetch.post('https://api.github.com/repos/zeit/next.js', { ... }); // return await res.json(); // @TODO: call api using fetch // @TODO: store the access token inside local storage return true; } export const isLoggedIn = () => { // if (global.window) { // const token = localStorage.getItem('access_token'); // // if (!token) { // console.log('No access_token found'); // // return false; // } // } return true; } <file_sep><?php namespace Modules\Transportation\Exceptions; use Exception; class MissingLocationException extends Exception { public function __construct($message = 'Geo location missing') { parent::__construct($message); } } <file_sep><?php namespace Modules\Transportation; use Modules\Transportation\Support\Converter; final class Calculator { const PER_MILE = 1.1515; protected $data; /** * Undocumented function * * @param [type] $to * @param [type] $from * * @return void */ public function getDistance(array $to, array $from) { $lat1 = $to['latitude']; $lon1 = $to['longitude']; $lat2 = $from['latitude']; $lon2 = $from['longitude']; $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $this->data = $miles = $dist * 60 * self::PER_MILE; return $this; } /** * Undocumented function * * @return void */ public function toKilometer() { return (new Converter)->toKilometer($this->data); } } <file_sep><?php namespace Modules\Authentication; use Carbon\Carbon; use Illuminate\Http\Request; class AuthenticationManager { /** * Logs the user in * * @param Request $request * * @return void */ public function login($request) { $user = app('repository.user') ->login($request->email, $request->password); $return = app('authentication.passport')->personalToken($request, $user); return [ 'access_token' => $return->accessToken, 'created_at' => Carbon::parse($return->token->created_at)->setTimezone(config('app.timezone')), 'expires_at' => Carbon::parse($return->token->expires_at)->setTimezone(config('app.timezone')), ]; } } <file_sep><?php namespace Modules\Authentication\Repositories; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Cache; class UserRepository { /** * Login User * * @param [type] $email * @param [type] $password * * @return void */ public function login($email, $password) { $cache = 'login-' . $email; if (Cache::has($cache)) { $user = Cache::get($cache); } else { $user = app('model.user')->newQuery()->where('email', $email)->first(); } if (Hash::check($password, $user->password)) { Cache::forever($cache, $user); return $user; } throw new \Exception('User not found'); } /** * Update authenticated User information * * @return void */ public function update($request) { return request()->user()->fill($request); } } <file_sep><?php namespace Tests\Unit; use Tests\TestCase; use Modules\Transportation\Transportation; use Illuminate\Foundation\Testing\DatabaseMigrations; class BusStopTest extends TestCase { use DatabaseMigrations; public function testGetDistanceOfBusToStop() { $bus = resolve('bus') ->setLatitude('32.9697') ->setLongitude('-98.53506'); $stop = resolve('stop') ->setLatitude('29.46786') ->setLongitude('14.000'); $result = Transportation::make()->to($bus)->from($stop)->calculate(); $this->assertTrue("10,085" === $result); } } <file_sep><?php namespace Modules\Base\Http\Controllers\Api; use Modules\Base\Http\Response; use Modules\Base\Http\Controllers\Controller; class GeneratorController extends Controller { /** * To generate random stop location * * @return void */ public function location() { try { $stop = app('repository.stop')->pickRandom(); $data = [ 'latitude' => $stop->latitude, 'longitude' => $stop->longitude ]; return Response::make()->success($data); } catch (\Exception $e) { return Response::make()->error($e->getMessage()); } } } <file_sep><?php namespace Modules\Locator; use Modules\Transportation\Contracts\LocatorInterface; use Modules\Transportation\Exceptions\MissingLocationException; class BusLocator implements LocatorInterface { /** * Undocumented function * * @param [type] $latitude * * @return void */ public function setLatitude($latitude) { $this->latitude = $latitude; return $this; } /** * Undocumented function * * @param [type] $longitude * * @return void */ public function setLongitude($longitude) { $this->longitude = $longitude; return $this; } /** * Undocumented function * * @return void */ public function getLatitude() { if (!isset($this->latitude)) { throw new MissingLocationException; } return $this->latitude; } /** * Undocumented function * * @return void */ public function getLongitude() { if (!isset($this->longitude)) { throw new MissingLocationException; } return $this->longitude; } } <file_sep><?php namespace Modules\Locator\Repositories; class BusRepository { /** * Display all bus stops * * @return void */ public function all() { $cache = 'bus-repository-all'; if (Cache::has($cache)) { return Cache::get($cache); } $record = app('model.bus')->all(); Cache::forever($cache, $record); return $record; } /** * Create a bus * * @param [type] $request * * @return void */ public function create($request) { $cache = 'bus-repository-all'; if (Cache::has($cache)) { return Cache::get($cache); } $create = app('model.bus')->create([ 'latitude' => $request->latitude, 'longitude' => $request->longitude, ]); Cache::forever($cache, $create); return $record; } /** * update a bus * * @param [type] $bus * @param [type] $request * * @return void */ public function update($bus, $request) { $cache = 'bus-repository-all'; if (Cache::has($cache)) { return Cache::get($cache); } $update = app('user.bus')->find($bus)->fill($request); Cache::forever($cache, $update); return $record; } } <file_sep><?php namespace Modules\Transportation\Support; use Illuminate\Support\Collection; class Converter { const KILOMETER = 1.609344; /** * Undocumented function * * @param [type] $data * * @return void */ public function toKilometer($data) { return number_format(round($data * self::KILOMETER)); } } <file_sep><?php use Faker\Generator as Faker; $factory->define(get_class(app('model.stop')), function (Faker $faker) { // @TODO: populate this data to have some value // or by calling api return [ 'name' => $faker->name, 'latitude' => '29.46786', 'longitude' => '14.000', ]; }); <file_sep><?php namespace Modules\Base\Http\Controllers\Api; use Illuminate\Http\Request; use Modules\Base\Http\Controllers\Controller; use Modules\Base\Http\Response; class StopController extends Controller { /** * Displays all bus stops * * @return void */ public function index(Request $request) { try { $stops = app('repository.stop')->get($request); return Response::make()->default($stops); } catch (\Exception $e) { return Response::make()->error($e->getMessage()); } } } <file_sep><?php namespace Modules\Base; use Illuminate\Foundation\Application as BaseApp; class Application extends BaseApp { /** * @inheritDoc */ protected $namespace = 'Base\\'; /** * @inheritDoc */ public function path($path = '') { return $this->basePath . DIRECTORY_SEPARATOR . 'Base' . DIRECTORY_SEPARATOR . 'app' . ($path ? DIRECTORY_SEPARATOR . $path : $path); } } <file_sep><?php namespace Tests\Feature; use Tests\TestCase; class ExampleFeatureTest extends TestCase { /** @test */ public function test_sample_feature() { $this->assertTrue(true); } } <file_sep><?php namespace Modules\Locator\Repositories; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; use Modules\Transportation\Transportation; class StopRepository { const NEAREST_STOP = "1.00"; /** * Display all bus stops * * @return void */ public function all() { $cache = 'stop-repository-all'; if (Cache::has($cache)) { return Cache::get($cache); } $record = app('model.stop')->all(); Cache::forever($cache, $record); return $record; } /** * Random record * * @return void */ public function pickRandom() { return app('model.stop')->get()->random(); } /** * Display nearest Bus stop of the authenticated user * * @return void */ public function get(Request $request) { $userLocator = app('user'); $stopLocator = app('stop'); $records = app('model.stop')->get() ->map(function ($record) use ($userLocator, $stopLocator, $request) { $user = $userLocator ->setLatitude($request->latitude) ->setLongitude($request->longitude); $stop = $stopLocator ->setLatitude($record->latitude) ->setLongitude($record->longitude); $record->distance = Transportation::make() ->to($user) ->from($stop) ->calculate(); return $record; }) ->filter(function ($record, $index) use ($request) { if ($record->distance <= self::NEAREST_STOP) { return true; } return false; }) ->take(10); return $records; } } <file_sep><?php namespace Tests\Unit; use Tests\TestCase; use Modules\Transportation\Transportation; use Modules\Transportation\Contracts\LocatorInterface; class TransportationTest extends TestCase { public function setUp(): void { parent::setUp(); $this->assertTrue(resolve('bus') instanceof LocatorInterface); } public function testGetDistance() { $bus = resolve('bus') ->setLatitude('32.9697') ->setLongitude('-98.53506'); $bus2 = resolve('bus') ->setLatitude('29.46786') ->setLongitude('14.000'); $locator = Transportation::make()->to($bus)->from($bus2)->calculate(); $this->assertTrue("10,085" === $locator); } } <file_sep><?php namespace Modules\Base\Http; class Response { public static function make() { return new static(); } public function default($data, $status = 200) { return response()->json($data, $status); } public function success($data, $status = 200) { return response()->json([ 'success' => true, 'content' => $data ], $status); } public function message($message = 'ok', $status = 200) { return response()->json([ 'success' => true, 'message' => $message, ], $status); } public function error($message = 'Something went wrong', $status = 500) { return response()->json([ 'success' => false, 'message' => $message ], $status); } public function __construct() { } } <file_sep><?php namespace Modules\Base\Http\Controllers\Api; use Illuminate\Http\Request; use Modules\Base\Http\Response; use Modules\Base\Http\Controllers\Controller; class UserController extends Controller { /** * Undocumented function * * @param Request $request * * @return void */ public function update(Request $request) { try { $user = app('repository.user')->update($request); return Response::make()->default($stops); } catch (\Exception $e) { return Response::make()->error($e->getMessage()); } } } <file_sep><?php use Faker\Generator as Faker; $factory->define(get_class(app('model.bus')), function () { // @TODO: populate this data to have some value // or by calling api return [ 'latitude' => '32.9697', 'longitude' => '-98.53506', ]; }); <file_sep><?php namespace Modules\Base\Http\Controllers\Api; use Illuminate\Http\Request; use Modules\Base\Http\Response; use Base\Http\Requests\LoginRequest; use Illuminate\Support\Facades\Auth; use Modules\Base\Http\Controllers\Controller; use Modules\Authentication\AuthenticationManager; class AuthController extends Controller { /** * Logs the user in * * @param Request $request * @param AuthenticationManager $auth * * @return void */ public function login(LoginRequest $request, AuthenticationManager $auth) { try { $response = $auth->login($request); return Response::make()->default($response); } catch (\Exception $e) { return Response::make()->error($e->getMessage()); } } /** * Logout user * * @return void */ public function logout() { try { if (auth()->check()) { request()->user()->token()->revoke(); } return Response::make()->message('Logged out'); } catch (\Exception $e) { return response()->json([ 'success' => false, 'message' => $e->getMessage() ], 500); } } } <file_sep><?php return [ 'bindings' => [ /** * Repositories */ 'repository.user' => Modules\Authentication\Repositories\UserRepository::class, 'repository.bus' => Modules\Locator\Repositories\BusRepository::class, 'repository.stop' => Modules\Locator\Repositories\StopRepository::class, /** * Models */ 'model.user' => Modules\Base\Models\User::class, 'model.bus' => Modules\Base\Models\Bus::class, 'model.stop' => Modules\Base\Models\Stop::class, /** * Core Modules */ 'bus' => Modules\Locator\BusLocator::class, 'stop' => Modules\Locator\StopLocator::class, 'user' => Modules\Locator\UserLocator::class, 'authentication.manager' => Modules\Authentication\AuthenticationManager::class, 'authentication.passport' => Modules\Authentication\PassportManager::class, ], ]; <file_sep><?php namespace Modules\Base\Providers; use Illuminate\Support\Facades\Schema; use Illuminate\Support\ServiceProvider; /** * Things @TODO: * - Add publishable config * - Add publishable migration */ class AppServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { foreach (config('modules.base.bindings') as $key => $binding) { $this->app->bind($key, $binding); } } /** * Bootstrap any application services. * * @return void */ public function boot() { Schema::defaultStringLength(191); } } <file_sep><?php Route::get('/', 'BaseController@index'); <file_sep>import React from 'react' import Head from 'next/head' import Error from 'next/error' import Nav from '../components/nav' import { isLoggedIn, getRandomLatLng, searchNearbyStops } from '../components/api'; class Search extends React.Component { constructor(props) { super(props); this.state = { nearbyStops: [], latitude: null, longitude: null, }; this.formSubmit = this.formSubmit.bind(this); } inputChange = (e) => { this.setState((state, props) => ({ [e.target.name]: e.target.value, })); } formSubmit = async (e) => { e.preventDefault(); const rand = await getRandomLatLng(); const resolveNearbyStops = await searchNearbyStops(rand); const nearbyStops = Object.keys(resolveNearbyStops).map((key, idx) => { const record = resolveNearbyStops[key]; return { name: record.name, latitude: record.latitude, longitude: record.longitude, } }); this.setState(() => ({ ...rand, nearbyStops, })); }; render = () => { return ( <div> <Head> <title>Search Page</title> <link rel="icon" href="/favicon.ico" /> </Head> <Nav /> { !this.props.authenticated ? ( <Error statusCode="401" /> ) : ( <div className="hero"> <div className="row"> <div className="card"> <h5>Random Box</h5> <form method="GET" onSubmit={this.formSubmit}> <label>Latitude</label> <input name="latitude" type="text" defaultValue={this.state.latitude} onChange={this.inputChange} /> <label>Longitude</label> <input name="longitude" type="text" defaultValue={this.state.longitude} onChange={this.inputChange} /> <button type="submit">Generate Random</button> </form> </div> <div className="card"> <h5>Lists of Nearby</h5> <ul> {this.state.nearbyStops.map((el, key) => ( <li key={key}> {el.name} -> {el.latitude}, {el.longitude} </li> ))} </ul> </div> </div> </div> ) } <style jsx>{` .hero { width: 100%; color: #333; } .title { margin: 0; width: 100%; padding-top: 80px; line-height: 1.15; font-size: 48px; } .title, .description { text-align: center; } .row { max-width: 880px; margin: 80px auto 40px; display: flex; flex-direction: row; justify-content: space-around; } .card { padding: 18px 18px 24px; width: 220px; text-align: left; text-decoration: none; color: #434343; border: 1px solid #9b9b9b; } .card:hover { border-color: #067df7; } .card h3 { margin: 0; color: #067df7; font-size: 18px; } .card p { margin: 0; padding: 12px 0 0; font-size: 13px; color: #333; } `}</style> </div> ) } } Search.getInitialProps = async () => { return { authenticated: isLoggedIn(), } } export default Search; <file_sep><?php namespace Modules\Base\Models; use Laravel\Passport\HasApiTokens; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use HasApiTokens, Notifiable; protected $fillable = [ 'latitude', 'longitude' ]; } <file_sep><?php Artisan::command('stop:seed', function () { $json = json_decode(file_get_contents('https://raw.githubusercontent.com/cheeaun/busrouter-sg/master/data/bus-stops.json'), true); collect($json)->map(function ($stop, $index) use (&$data) { $data[] = [ 'name' => $stop['name'], 'latitude' => $lat = explode(',', $stop['coords'])[0], 'longitude' => $lat = explode(',', $stop['coords'])[1], 'created_at' => now() ]; }); \DB::transaction(function () use ($data) { \DB::table('stops')->insert($data); }); }); <file_sep><?php use Illuminate\Database\Seeder; class BusRouterSgTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $json = file_get_contents('https://raw.githubusercontent.com/cheeaun/busrouter-sg/master/data/bus-stops.json'); $arr = json_decode($json, true); foreach ($arr as $busNumber => $info) { $ex = explode(',', $info['coords']); app('model.stop')->create([ 'name' => $info['name'], 'latitude' => $ex[0], 'longitude' => $ex[1], ]); } } } <file_sep><?php namespace Modules\Transportation; use Modules\Transportation\Contracts\LocatorInterface; final class Transportation { /** * Undocumented function * * @param LocatorInterface $location * * @return void */ public function to(LocatorInterface $location) { $this->to = $this->setDistance($location); return $this; } /** * Undocumented function * * @param LocatorInterface $location * * @return void */ public function from(LocatorInterface $location) { $this->from = $this->setDistance($location); return $this; } /** * Undocumented function * * @param [type] $location * * @return void */ protected function setDistance($location) { if (is_callable($location)) { return call_user_func($location); } return [ 'latitude' => $location->getLatitude(), 'longitude' => $location->getLongitude(), ]; } /** * Undocumented function * * @return void */ public function calculate() { return (new Calculator)->getDistance($this->to, $this->from)->toKilometer(); } /** * Should be able to create a self instance thru static call. * * This is similarly for Laravel devs. * * @return self */ public static function make() { return new static(); } }
6e452375445da0f88275486ac86dc1dddeb8c573
[ "Markdown", "JavaScript", "PHP" ]
36
PHP
napoleon101392/acme
d16524fbc14c70e47e912346afc5bba779827ada
182720396393db1f734f15384b6ce3b6f9eabe17
refs/heads/master
<file_sep>package itstep; public class TestMe { public static void main(String[] args) { } }
c8346e7216749caaacd59c00c4609415c736aba7
[ "Java" ]
1
Java
sharlan88/itstep
47bd1da4ec301f7cf7ba93a2241900c61da7aa61
1305fa2ab0c15f3aa419be20e8eb01b244b1bbe9
refs/heads/master
<file_sep>- Branchement avec l'API (Webservices) pour récupérer le JSON - Enregistrement des données via HTML5 Storage - Rechargement des données JSON au besoin (déclenché par utilisateur ?) - Interface via UI Binder (XML) plutot qu'en dur dans les classes Java - Utilisation d'une Google Map à partir des données JSON localisées. <file_sep>package com.van.tri.client; import java.util.List; import com.google.gwt.core.client.JsArray; import com.google.gwt.json.client.JSONArray; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONParser; import com.google.gwt.json.client.JSONValue; import com.van.tri.model.GarbageDO; public class ModuleServiceDechets implements IModuleService { private final static String jsondata="{ \"garbages\" : [{ \"col_0\" : \"\", \"col_1\" : \"acides\", \"col_2\" : \"scu_toxiquedivers\", \"col_3\" : \"cat_ddm\", \"col_4\" : \"\", \"col_5\" : \"\", \"col_6\" : \"\", \"col_7\" : \"\" }, { \"col_0\" : \"\", \"col_1\" : \"aérosols\", \"col_2\" : \"scu_toxiquedivers\", \"col_3\" : \"cat_ddm\", \"col_4\" : \"\", \"col_5\" : \"\", \"col_6\" : \"\", \"col_7\" : \"\" }, { \"col_0\" : \"\", \"col_1\" : \"agenda\", \"col_2\" : \"cu_papierscartons\", \"col_3\" : \"cat_papiercarton\", \"col_4\" : \"\", \"col_5\" : \"\", \"col_6\" : \"\", \"col_7\" : \"\" }, { \"col_0\" : \"\", \"col_1\" : \"Ampoule classique\", \"col_2\" : \"cu_divers\", \"col_3\" : \"cat_omr\", \"col_4\" : \"\", \"col_5\" : \"\", \"col_6\" : \"\", \"col_7\" : \"ampoule_petit.png\" }]}"; private final static String jsondata2="[{\"code\" : \"AC1\", \"name\" : \"<NAME>\", \"description\" : \"TitiTataToto\", \"picture\" : \"ampoule_petit.png\" },{\"code\" : \"AC1\", \"name\" : \"<NAME>\", \"description\" : \"TitiTataToto\", \"picture\" : \"ampoule_petit.png\" },{\"code\" : \"AC1\", \"name\" : \"<NAME>\", \"description\" : \"TitiTataToto\", \"picture\" : \"ampoule_petit.png\" },{\"code\" : \"AC1\", \"name\" : \"<NAME>\", \"description\" : \"TitiTataToto\", \"picture\" : \"ampoule_petit.png\" }]"; /* @return Recharge les données JSON Déchets (Appel Webservice) * @see com.romeo.demo1.client.ModuleService#reloadData() */ @Override public boolean reloadData() throws Exception { // TODO Auto-generated method stub return false; } /* @return Retourne les données JSON Déchets * @see com.romeo.demo1.client.ModuleService#getData() */ @Override public String getData() throws Exception { return null; } public JsArray<GarbageDO> fetchListGarbage() { JsArray<GarbageDO> arrayGarbage = asArrayOfStockData(ModuleServiceDechets.jsondata2); return arrayGarbage; } private final native JsArray<GarbageDO> asArrayOfStockData(String json) /*-{ return eval(json); }-*/; public int testJson() { JSONValue jsonvalue=JSONParser.parseStrict(this.jsondata); JSONObject jsonobj=jsonvalue.isObject(); JSONValue dechets=jsonobj.get("garbages"); JSONArray listedechets=dechets.isArray(); int size=listedechets.size(); /* for (int j=0; j<=pricesArray.size()-1; j++) { JSONObject priceObj = pricesArray.get(j).isObject(); double price = priceObj.get("price").isNumber().doubleValue(); if (j!=pricesArray.size()-1) { priceSb.append("-"); } } */ return size; } } <file_sep>package com.van.tri.client; import com.google.gwt.core.client.JsArray; import com.van.tri.model.GarbageDO; public interface IModuleService { boolean reloadData() throws Exception; String getData() throws Exception; JsArray<GarbageDO> fetchListGarbage(); } <file_sep>/** * */ package com.van.tri.model; import com.google.gwt.core.client.JavaScriptObject; /** * @author van * */ public class GarbageDO extends JavaScriptObject { // Overlay types always have protected, zero argument constructors. protected GarbageDO() { } // private String id; // // private String code; // // private String description; // // private String picture; // // private String name; // JSNI methods to get stock data. public final native String getId() /*-{ return this.id; }-*/; public final native String getCode() /*-{ return this.code; }-*/; public final native String getDescription() /*-{ return this.description; }-*/; public final native String getPicture() /*-{ return this.picture; }-*/; public final native String getName() /*-{ return this.name; }-*/; }
6c00f87fe7f5bf265e7b34ccacb6cbb86142fccc
[ "Java", "Text" ]
4
Text
vivreanantes/opendata
4dcb64981f3c03acece69c8e7888552ba23ad409
a9e5cb0c1ef38481d0005f30a5d1737ff058ba6f
refs/heads/main
<repo_name>vithuren27/python-tictactoe-game<file_sep>/tictactoe.py import tkinter as tk class TICTACTOE(tk.Tk): def __init__(self): super().__init__() self.title("Tic Tac Toe") self.btns = [] self.turn = True self.count = 0 self.resizable(width=False, height=False) self.Board() def Board(self): for i in range(0, 3): row = [] for j in range(0, 3): row.append(tk.Button(self, width=10, height=3, font="Calibre 35 bold", command=lambda x=i, y=j: self.Turn_Taken(x, y))) row[j].grid(row=i, column=j) self.btns.append(row) tk.Button(self, text="New Game", width=10, height=1, font="Calibre 15 bold", bg='black', fg='white', activebackground='blue3', activeforeground='white', command=self.NEWGAME).grid(row=3, column=1) def Turn_Taken(self, x, y): self.count += 1 if self.turn: char = 'X' self.btns[x][y].config(text='X', bg='black', state="disabled") else: char = 'O' self.btns[x][y].config(text='O', bg='white', state="disabled") self.Check_Results(char) self.turn = not self.turn def NEWGAME(self): for widget in self.winfo_children(): widget.destroy() self.btns = [] self.turn = True self.count = 0 self.Board() def Check_Results(self, char): # Horizontal Direction if(((self.btns[0][0]["text"] == char) and (self.btns[0][1]["text"] == char) and (self.btns[0][2]["text"] == char)) or ((self.btns[1][0]["text"] == char) and (self.btns[1][1]["text"] == char) and (self.btns[1][2]["text"] == char)) or ((self.btns[2][0]["text"] == char) and (self.btns[2][1]["text"] == char) and (self.btns[2][2]["text"] == char)) or # Vertical Direction ((self.btns[0][0]["text"] == char) and (self.btns[1][0]["text"] == char) and (self.btns[2][0]["text"] == char)) or ((self.btns[0][1]["text"] == char) and (self.btns[1][1]["text"] == char) and (self.btns[2][1]["text"] == char)) or ((self.btns[0][2]["text"] == char) and (self.btns[1][2]["text"] == char) and (self.btns[2][2]["text"] == char)) or # Diagonal Direction ((self.btns[0][0]["text"] == char) and (self.btns[1][1]["text"] == char) and (self.btns[2][2]["text"] == char)) or ((self.btns[0][2]["text"] == char) and (self.btns[1][1]["text"] == char) and (self.btns[2][0]["text"] == char))): self.Result(char) elif self.count == 9: self.Result("Draw") def Result(self, char): top =tk.Toplevel(self) if char == "Draw": top.title("OOPS!") topText = tk.Label(top, text=f"It is a Draw!", font="Calibre 30 bold", fg='blue') else: top.title("Congratulations!") topText = tk.Label(top, text=f"{char} is the Winner!", font="Calibre 30 bold", fg="blue") topButton = tk.Button(top, text="New Game", bg='black', fg='white', activebackground='blue3', activeforeground='white', command=self.NEWGAME) topText.grid(row=0, column=0, padx=10, pady=10) topButton.grid(row=1, column=0) TICTACTOE().mainloop()<file_sep>/README.md # Python - Tic Tac Toe Game This program will create a Tkinter package based Tic Tac Toe game. The first player to make a turn will be X and the second player will be O. When initially opening the application the user interface for the game will be as follows: ![image](https://user-images.githubusercontent.com/66092888/124392511-fa3d8000-dcc3-11eb-8ed0-c45d974fd1b0.png) The first selection will set the player with symbol X to the selected tile. Subsequently player with symbol O will select their respective tile. The game will proceed until either X wins, O wins or there is a draw. If any of the conditions are met such as X wins, O wins or Draw the application will generate a message reiterating the same and the users will be able to select click the New Game button to start a new game. ![image](https://user-images.githubusercontent.com/66092888/124392548-41c40c00-dcc4-11eb-8066-aa9d2058c34b.png)
cf17e5e99bb66d536f80b883903970c0fc2a5ed0
[ "Markdown", "Python" ]
2
Python
vithuren27/python-tictactoe-game
a21a582029d6b7f8421ba81690c63a64647c84c3
3d92c165ea31e864f790b99b6153e4800f49651a
refs/heads/master
<repo_name>CharlesRngrd/ConvertisseurSalaireJavascriptNatif<file_sep>/mentions-legales.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Mon salaire en intérim | Mentions légales</title> <link rel="icon" href="img/favicon.ico" /> <link href="https://fonts.googleapis.com/css?family=Dosis:500" rel="stylesheet"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="css/styles.css"/> </head> <body> <div class="col-sm-12 red"> <noscript class="red"> Pour naviguer sur ce site, vous devez activer JavaScript.<br/> Si vous êtes sur Internet Explorer, merci de cliquer sur "Autoriser le contenu bloqué" en bas de la page.<br/> Besoin d'aide : <a href="http://www.enable-javascript.com/fr/" titre="No Javascript" target="_blank" id="cliquez">cliquez ici !</a> </noscript> </div> <div class="blanc" id="titre"> <div class="row container-fluid"> <div class="col-sm-12 blanc"> <h1>Je calcule mon salaire en intérim</h1> </div> </div> <div class="row container-fluid blanc"> <div class="col-sm-4 offset-sm-2 col-lg-3 offset-lg-3 blanc center"> <a class="menu" href="index.html">Simuler son salaire</a> </div> <div class="col-sm-4 col-lg-3 blanc center"> <a class="menu" href="comprendre-salaire.html">Comprendre son salaire</a> </div> </div> </div> <div id="corp"> <div class="row container-fluid"> <div class="col-md-10 offset-md-1 col-lg-8 offset-lg-2 blanc bloc"> <div class="row container-fluid"> <div class="col-sm-10 offset-sm-1 blanc"> <h2 class="xtall">Mentions Légales<br/><br/></h2> <p class="tall">Propriétaire et éditeur du site :<br/></p> <p class="grey-text"> Prénom Nom<br/> Adresse<br/> Téléphone<br/> Email<br/> <br/> </p> <p class="tall">Directeur de la publication :<br/></p> <p class="grey-text"> Prénom Nom<br/> <br/> </p> <p class="tall">Hébergeur :<br/></p> <p class="grey-text"> Hébergeur<br/> SIRENT<br/> Adresse<br/> <br/> </p> </div> </div> </div> </div> <div class="row container-fluid"> <div class="col-12 footer"> <a class="grey" href="mentions-legales.html">- Mentions Légales -</a> </div> </div> </div> </body> <file_sep>/js/calcul.js function ready() { // Correction du style en fonction du navigateur if (-1 != navigator.userAgent.indexOf("Safari") && -1 == navigator.userAgent.indexOf("Chrome")) { document.getElementById("baseHebdo").style["-webkit-appearance"] = "none", document.getElementById("baseHebdo").style.paddingRight = "3px", document.getElementById("baseHebdo").style.paddingLeft = "2px", document.getElementById("marjorationHeuresSupp").style["-webkit-appearance"] = "none", document.getElementById("marjorationHeuresSupp").style.paddingRight = "3px", document.getElementById("marjorationHeuresSupp").style.paddingLeft = "2px" }; // Activation des popups pour comprendre le salaire $(".popoverData").popover(); $(".popoverOption").popover({ trigger: "hover" }) } function smic() { // Modification de la valeur du taux horaire et calcul du salaire document.getElementById("tauxHoraire").value = 9.76; convertFunction(); } function convertFunction() { // Réception des inputs utilisateur tauxHoraire = document.getElementById("tauxHoraire").value; baseHebdo = document.getElementById("baseHebdo").value; nombreHeuresHebdo = document.getElementById("nombreHeuresHebdo").value; marjorationHeuresSupp = document.getElementById("marjorationHeuresSupp").value; isTickets = document.getElementById("isTickets"); tickets = document.getElementById("tickets").value; isTreiziemeMois = document.getElementById("isTreiziemeMois"); arePrimes = document.getElementById("arePrimes"); // Réception des inputs liés aux primes for (var e = 1; 3 >= e; e++) { isMonthly[e] = document.getElementById("isMonthly" + e); isDayly[e] = document.getElementById("isDayly" + e); prime[e] = document.getElementById("prime" + e).value; }; // Remplacement du séparateur virgule par un point tauxHoraire = tauxHoraire.replace(",", "."); nombreHeuresHebdo = nombreHeuresHebdo.replace(",", "."); tickets = tickets.replace(",", "."); // Remplacement du séparateur virgule par un point pour les primes for (var e = 1; 3 >= e; e++) { prime[e] = prime[e].replace(",", "."); } // Remplacement des valeurs nulles par zéro if (1 == isNaN(tauxHoraire)) { tauxHoraire = 0 } if (1 == isNaN(nombreHeuresHebdo)) { nombreHeuresHebdo = 0 } if (1 == isNaN(tickets)) { tickets = 0 } // Remplacement des valeurs nulles par zéro pour les primes for (var e = 1; 3 >= e; e++) { if (1 == isNaN(prime[e])) { prime[e] = 0 } } // Gestion de l'affichage des inputs de majoration des heures supplémentaires // si l'utilisateur saisie plus de 35 heures hebdo if (nombreHeuresHebdo > 35) { $("#collapseHeuresSupp").collapse("show") } else { $("#collapseHeuresSupp").collapse("hide") } // Calcul du revenu de base (heures supplémentaires inclues sans majoration) var revenuBase = Math.round( tauxHoraire * constNombreHeureMois * (1 - constTauxCharges) * (nombreHeuresHebdo / 35) ) // Calcul du revenu lié à la majoration des heures supplémentaires var revenuMajoration = Math.round( (nombreHeuresHebdo - baseHebdo) * nbSemainesMois * tauxHoraire * (1 - constTauxCharges) * (marjorationHeuresSupp / 100) ); // Si le nombre d'heures par semaine est plus grand que le seuil de déclanchement // des heures supplémentaires alors on applique la majoration. Dans le cas contraire, // il n'y a pas de majoration if (nombreHeuresHebdo > baseHebdo) { salaireBase = revenuBase + revenuMajoration; salaireBaseAvecPrime = revenuBase + revenuMajoration } else { salaireBase = revenuBase; salaireBaseAvecPrime = revenuBase } // Gestion de l'affichage de montant des tickets restaurant. S'il y a des tickets // restaurant alors on retire la part du salarié if (isTickets.checked) { $("#collapseTickets").collapse("show"); salaireBaseAvecPrime -= Math.round(tickets * constNombreHeureMois / 7 * .5) } // S'il n'y a pas de ticket restaurant, on réinitialise le montant else { $("#collapseTickets").collapse("hide"); document.getElementById("tickets").value = "0" } // Gestion de l'affichage des primes. S'il y a des primes, on ajoute le montant // Attention, les primes n'influent pas sur les IFM et CP ! if (arePrimes.checked) { $("#collapsePrimes").collapse("show"); // Vérification du type de primes (mensuelle ou journaliaire) for (var e = 1; 3 >= e; e++) { if (isMonthly[e].checked) { salaireBaseAvecPrime += Math.round(prime[e] * nbJoursMois * (1 - constTauxCharges)) } else { salaireBaseAvecPrime += Math.round(prime[e] * (1 - constTauxCharges)) } } } // S'il n'y a pas de prime, on réinitialise le montant et le type else { $("#collapsePrimes").collapse("hide"); for (var e = 1; 3 >= e; e++) { document.getElementById("prime" + e).value = "0"; isMonthly[e].checked = 0; isDayly[e].checked = 0; } } // Affichage du 13e mois if (isTreiziemeMois.checked) { treiziemeMois = Math.round(revenuBase / 12); document.getElementById("treiziemeMois").innerHTML = treiziemeMois } else { treiziemeMois = 0 document.getElementById("treiziemeMois").innerHTML = treiziemeMois } // Affichage du salaire de base document.getElementById("salaireBase").innerHTML = salaireBaseAvecPrime; // Affichage des IFM (les primes n'ont pas d'influence sur ce montant) var ifm = Math.round((salaireBase + treiziemeMois) / 10); document.getElementById("IFM").innerHTML = ifm; // Affichage des CP (les primes n'ont pas d'influence sur ce montant) var cp = Math.round((salaireBase + treiziemeMois + ifm) / 10); document.getElementById("CP").innerHTML = cp; var salaireNetTotal = salaireBaseAvecPrime + treiziemeMois + ifm + cp; document.getElementById("salaireNetTotal").innerHTML = salaireNetTotal } // Valeurs par défaut var tauxHoraire = 0, baseHebdo = 0, nombreHeuresHebdo = 0, marjorationHeuresSupp = 0, salaireBase = 0, salaireBaseAvecPrime = 0, isTreiziemeMois = 0, treiziemeMois = 0, isTickets = 0, tickets = 0, arePrimes = 0, prime = new Array, isMonthly = new Array, isDayly = new Array; // Constantes var constNombreHeureMois = 151.67, nbSemainesMois = constNombreHeureMois / 35, nbJoursMois = constNombreHeureMois / 7, constTauxCharges = .23; <file_sep>/README.md <p align="center"> <img src="https://github.com/CharlesRngrd/ConvertisseurSalaireJavascriptNatif/blob/master/img/image.png"> </p> ## Convertisseur de salaire pour l'intérim ## Ce site permet de réaliser des simulations de salaire dans le cadre de l'intérim. Il est constitué uniquement d'un front end. ## Types de rémunérations ## - Salaire de base - IFM : Indemnités de Fin de Mission, correspond à 10% du salaire de base hors primes - CP : Congés Payés, correspond à 10% du salaire de base hors primes et 10% des IFM ## Détails techniques ## - La fonction convertFunction() permet de calculer les éléments de rémunération en récupérant la valeur de chaque input - Des eventListeners dans chaque input invoquent cette fonction à chaque changement provenant de l'utilisateur - Le point et la virgule sont interprétés comme séparateur de décimales - Les valeurs nulles sont remplacées par 0 - Certains inputs apparaissent uniquement lorsque les options sont égales à "Oui"
88e786364ada54b2d416a5589a4044490e0695e9
[ "JavaScript", "HTML", "Markdown" ]
3
HTML
CharlesRngrd/ConvertisseurSalaireJavascriptNatif
985d1602ce316930bc5305c0e377fd52e08188cb
945a8591b89c2c56e4b29a8d8c05880e4d66a3a0
refs/heads/master
<repo_name>tanyhb1/YSC3232-SE-HW2<file_sep>/Main.java package Lab_2_Final; import java.io.IOException; import org.xml.sax.SAXException; public class Main { public static void main(String[] args) throws SAXException, IOException { //insert 6 test questions of 3 different types. MCQ mcq1 = new MCQ("5+5 = ?", "2", "D", "1", "5", "-3", "10"); MCQ mcq2 = new MCQ("10-5 = ?", "2", "B", "2", "5", "10", "7"); SAQ saq1 = new SAQ("What is the best major?", "4", "MCS"); SAQ saq2 = new SAQ("What is the name of my school?", "4", "Yale-NUS"); LAQ laq1 = new LAQ("Did the chicken or the egg come first? Explain.", "0", "Blah blah"); LAQ laq2 = new LAQ("How did this examination go for you?", "0", "Blah blah blah"); //add the test questions to the exam. Exam ExamDemo = new Exam("Exam 1"); ExamDemo.addMCQ(mcq1); ExamDemo.addMCQ(mcq2); ExamDemo.addShortAns(saq1); ExamDemo.addShortAns(saq2); ExamDemo.addLongAns(laq1); ExamDemo.addLongAns(laq2); // Printing and saving demo exam as XML file, and checking that when we read it, it is the same. System.out.println(ExamDemo.toXML()); ExamDemo.saveXMLFile("Exam.xml"); Exam ExamDemo2 = Exam.readXMLFile("Exam.xml"); System.out.println(ExamDemo2.toXML()); ExamDemo2.saveXMLFile("Exam2.xml"); // run the exam. ExamDemo.implementExam(); } } <file_sep>/Exam.java package Lab_2_Final; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; //exam takes in Name, a list of MCQs, a list of SAQs, and a list of LAQs. public class Exam { String Name; List <MCQ> MCQs; List <SAQ> SAQs; List <LAQ> LAQs; Exam(String name){ this.Name = name; this.MCQs = new ArrayList<>(); this.SAQs = new ArrayList<>(); this.LAQs = new ArrayList<>(); } Exam(){ this.Name = "TBC"; this.MCQs = new ArrayList<>(); this.SAQs = new ArrayList<>(); this.LAQs = new ArrayList<>(); } //self-explanatory. void addMCQ (MCQ q){ this.MCQs.add(q); } void addShortAns (SAQ q){ this.SAQs.add(q); } void addLongAns (LAQ q){ this.LAQs.add(q); } //for our exam, we enforce that MCQs come first, then SAQ come second, then LAQ come last. This is like the Singapore style exams. public String toXML (){ String xmlMCQ = ""; for (MCQ q: MCQs){ xmlMCQ+= q.toXML(); } String xmlShortAns = "" ; for (SAQ q: SAQs){ xmlShortAns+= q.toXML(); } String xmlLongAns = "" ; for (LAQ q: LAQs){ xmlLongAns+= q.toXML(); } String xmlExam = "<Exam name='" + this.Name.replace("'", "") + "'>\n" + xmlMCQ + xmlShortAns + xmlLongAns + "</Exam>\n"; return xmlExam; } void saveXMLFile(String filename) { String str = this.toXML(); try { Files.write(Paths.get(filename), str.getBytes()); } catch (IOException ex) { Logger.getLogger(Exam.class.getName()).log(Level.SEVERE, null, ex); } } public static Exam readXMLFile(String filename) throws SAXException, IOException { Exam readExam = new Exam(); File fXmlFile = new File(filename); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; try { dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); // Combines the new lines in the XML file Element examE = doc.getDocumentElement(); String TheExamName = examE.getAttribute("name"); readExam= new Exam(TheExamName); // read each element with the MCQ tag, and within those elements, we iterate through their fields, creating a new MCQ NodeList mcqElements = examE.getElementsByTagName("MCQ"); for (int i = 0; i < mcqElements.getLength(); i++){ Node bNode = mcqElements.item(i); if (bNode.getNodeType() == Node.ELEMENT_NODE){ Element mcqE = (Element) bNode; //USUALLY cannot cast superclass to a subclass, the other way is ok. String mcqDetails = mcqE.getAttribute("question"); String mcqAnswer = mcqE.getElementsByTagName("Answer").item(0).getTextContent(); String mcqMarks = mcqE.getElementsByTagName("Marks").item(0).getTextContent(); String mcqOption1 = mcqE.getElementsByTagName("OptionA").item(0).getTextContent(); String mcqOption2 = mcqE.getElementsByTagName("OptionB").item(0).getTextContent(); String mcqOption3 = mcqE.getElementsByTagName("OptionC").item(0).getTextContent(); String mcqOption4 = mcqE.getElementsByTagName("OptionD").item(0).getTextContent(); MCQ Q = new MCQ (mcqDetails, mcqMarks, mcqAnswer, mcqOption1, mcqOption2, mcqOption3, mcqOption4); readExam.addMCQ(Q); } } // read each element with the ShortAns tag, and then iterate through their fields, creating a new SAQ NodeList shortansElements = examE.getElementsByTagName("ShortAns"); for (int i = 0; i < shortansElements.getLength(); i++){ Node bNode = shortansElements.item(i); if (bNode.getNodeType() == Node.ELEMENT_NODE){ Element shortAnsE = (Element) bNode; //USUALLY cannot cast superclass to a subclass, the other way is ok. String shortAnsDetails = shortAnsE.getAttribute("question"); String shortAnsAnswer = shortAnsE.getElementsByTagName("Answer").item(0).getTextContent(); String shortAnsMarks = shortAnsE.getElementsByTagName("Marks").item(0).getTextContent(); SAQ Q = new SAQ(shortAnsDetails , shortAnsMarks , shortAnsAnswer); readExam.addShortAns(Q); } } // read each element with the LongAns tag, and iterate through their fields, creating a new LAQ. NodeList longAnsElements = examE.getElementsByTagName("LongAns"); for (int i = 0; i < longAnsElements.getLength(); i++){ Node bNode = longAnsElements.item(i); if (bNode.getNodeType() == Node.ELEMENT_NODE){ Element longAnsE = (Element) bNode; //USUALLY cannot cast superclass to a subclass, the other way is ok. String longAnsDetails = longAnsE.getAttribute("question"); String longAnsAnswer = longAnsE.getElementsByTagName("Answer").item(0).getTextContent(); String longAnsMarks = longAnsE.getElementsByTagName("Marks").item(0).getTextContent(); LAQ Q = new LAQ(longAnsDetails, longAnsMarks, longAnsAnswer); readExam.addLongAns(Q); } } // return the new exam with all the stored questions. return readExam; } catch (ParserConfigurationException ex) { Logger.getLogger(Exam.class.getName()).log(Level.SEVERE, null, ex); } return readExam; } // initialize two variables to keep track of total possible marks, and the marks scored by the user. // then, using the methods in the subclasses of Question, we ask the question and retrieve the answer from the user. // we mandate that LAQ have 0 marks, since it is difficult to machine-check answers for ambiguous long answer questions. void implementExam (){ int totalMarks = 0; int totalPossibleMarks = 0; for (MCQ q : MCQs){ q.askMCQ(); q.printMcqOptions(); totalMarks += q.markAnswer(); totalPossibleMarks += q.getMarks(); } for (SAQ q : SAQs){ q.askShortAnsQns(); totalMarks += q.markAnswer(); totalPossibleMarks += q.getMarks(); } for (LAQ q : LAQs){ q.askLongAnsQns(); q.storeAnswer(); totalPossibleMarks += q.getMarks(); } System.out.println("The exam is over."); System.out.println("Calculating your score (exclusive of long answer questions)..."); System.out.println("Congratulations! You have scored " + totalMarks + " out of " + Integer.toString(totalPossibleMarks) +" marks."); } }
d2c551adbe8837e6b1728b3f184b0fc35668a441
[ "Java" ]
2
Java
tanyhb1/YSC3232-SE-HW2
297090b046571a6857b058d46822812e36cc7ca7
4ee6285951504183f139e6192b0cf4dfa2294d57
refs/heads/main
<repo_name>lio-elalouf/CSE201-td3-1-handin<file_sep>/td3.cpp #include <iostream> #include "td3.hpp" #include "support.hpp" #include <stdlib.h> #include <math.h> // sin, cos #include <assert.h> #include <limits> // + inf double using namespace std; using namespace support; double* extend_array(double* array, int length, int new_size) { double* new_array; new_array = new double[new_size]; //new_array[new_size] = {}; / better do the if for (int i=0 ; i< new_size ; i++) { if (i< length) { new_array[i] = array[i]; } else { new_array[i] = 0; } } delete array; return new_array; } double* shrink_array(double* array, int length, int new_size) { double* new_array; new_array = new double[new_size]; for (int i=0 ; i< new_size ; i++) { new_array[i] = array[i]; } delete array; return new_array; } double* append_to_array(double element, double* array, int &current_size, int &max_size) { if (current_size == max_size) { array = extend_array(array, current_size, max_size+5); max_size += 5; } array[current_size] = element; // set the value of the last element current_size += 1; return array; } double* remove_from_array(double* array, int &current_size, int &max_size) { if (current_size > 0) { current_size -= 1; if (max_size - current_size >= 5) { // distance (total nb of used elements, array maximum size) array = shrink_array(array, current_size, max_size-5); max_size -= 5;} } return array; // return it anyway } bool simulate_projectile(const double magnitude, const double angle, const double simulation_interval, double *targets, int &tot_targets, int *obstacles, int tot_obstacles, double* &telemetry, int &telemetry_current_size, int &telemetry_max_size) { bool hit_target, hit_obstacle; double v0_x, v0_y, x, y, t; double PI = 3.14159265; double g = 9.8; v0_x = magnitude * cos(angle * PI / 180); v0_y = magnitude * sin(angle * PI / 180); t = 0; x = 0; y = 0; // add the first coordinates telemetry = append_to_array(t,telemetry, telemetry_current_size, telemetry_max_size); telemetry = append_to_array(x,telemetry, telemetry_current_size, telemetry_max_size); telemetry = append_to_array(y,telemetry, telemetry_current_size, telemetry_max_size); hit_target = false; hit_obstacle = false; while (y >= 0 && (! hit_target) && (! hit_obstacle)) { double * target_coordinates = find_collision(x, y, targets, tot_targets); if (target_coordinates != NULL) { remove_target(targets, tot_targets, target_coordinates); hit_target = true; } else if (find_collision(x, y, obstacles, tot_obstacles) != NULL) { hit_obstacle = true; } else { t = t + simulation_interval; y = v0_y * t - 0.5 * g * t * t; x = v0_x * t; if (y >= 0) { // can not be under the ground telemetry = append_to_array(t,telemetry, telemetry_current_size, telemetry_max_size); telemetry = append_to_array(x,telemetry, telemetry_current_size, telemetry_max_size); telemetry = append_to_array(y,telemetry, telemetry_current_size, telemetry_max_size); } } } return hit_target; } void merge_telemetry(double **telemetries, int tot_telemetries, int *telemetries_sizes, double* &global_telemetry, int &global_telemetry_current_size, int &global_telemetry_max_size) { // Multiple telemetries are stored in "telemetries" (pointer to a pointer to doubles) // telemetries : liste des telemetries // tot_telemetries : nombre de projectile // telemetries_sizes : taille de chacune des telemetries // global_telemetry : listes once merged // global_telemetry_current_size: total nb of elements stored in global_telemetry // global_telemetry_max_size: total amount of elements that have been allocated global_telemetry_max_size = 0; global_telemetry_current_size = 0; global_telemetry = new double[global_telemetry_max_size]; if (tot_telemetries == 0) { return; } double plus_inf = std::numeric_limits<double>::infinity(); int depasser = 0; double** telemetries_ptr; telemetries_ptr = new double*[tot_telemetries]; for (int i = 0; i < tot_telemetries; i++) { telemetries_ptr[i] = telemetries[i]; if (telemetries_sizes[i] == 0) { telemetries_ptr[i] = &plus_inf; depasser+= 1;} } while(depasser < tot_telemetries) { double values[tot_telemetries]; double min_value = *telemetries_ptr[0]; int where_min_value = 0; for (int i = 0; i < tot_telemetries; i++) { values[i] = *telemetries_ptr[i]; if (values[i] < min_value) { min_value = values[i]; where_min_value = i;}} // copie de 3 valeur de telemetry global_telemetry = append_to_array(*(telemetries_ptr[where_min_value]), global_telemetry,global_telemetry_current_size, global_telemetry_max_size); global_telemetry = append_to_array(*(telemetries_ptr[where_min_value]+1), global_telemetry,global_telemetry_current_size, global_telemetry_max_size); global_telemetry = append_to_array(*(telemetries_ptr[where_min_value]+2), global_telemetry,global_telemetry_current_size, global_telemetry_max_size); // avancer le pointeur correspondant à where_min_value (telemetries_ptr[where_min_value]) += 3; // si jamais le ptr dépasse la fin, le pointer vers plus_inf double* end = telemetries[where_min_value] + telemetries_sizes[where_min_value]; if (telemetries_ptr[where_min_value] >= end ){ telemetries_ptr[where_min_value] = &plus_inf; depasser+= 1;} } delete[] telemetries_ptr; } <file_sep>/README.md # CSE201-td3-1-handin This is the TD3, and I'm learning how to use GIT :)
ad30505894bbc4ce141777825e733c56490b1d83
[ "Markdown", "C++" ]
2
C++
lio-elalouf/CSE201-td3-1-handin
1bb805bc1dc7940234a8f39972a11fc935ee41b8
674de1a7ff422fe69666cf55af75dd04c5251ce9
refs/heads/master
<repo_name>njclapp/PowderCheck<file_sep>/setup.py #!/usr/bin/env python2.7 from setuptools import setup setup( name='PowderCheck', version="1.0.0", author='<NAME>', install_requires=[ "bs4", "requests", ], ) <file_sep>/smtp.py import smtplib from email.MIMEText import MIMEText msg = ('Varget is in stock!') msg_from = '' # who the message is 'from' # msg_subject = '' # message subject -- if i ever want to email this alert msg_to = ['', ''] # phone to text -- figure out how to text multiple users later msg_text = "Varget is on sale!" # alert message, will never change -- variable is needed for headers/formatting headers = ['From: {}'.format(msg_from), 'To: {}'.format(msg_to), 'Content-Type: text/html' ] msg_body = '\r\n'.join(headers) + '\r\n\r\n' + msg_text session = smtplib.SMTP('smtp.gmail.com', 587) session.ehlo() session.starttls() session.login('', '') #'username', '<PASSWORD>' note: password in plaintext is very dangerous session.sendmail(msg_from, msg_to, msg_body) session.quit() <file_sep>/powdercheck.py #!/usr/bin/env python # This program is used to check primarily for Hodgdon H110 and Hodgdon Varget gunpowder from # http://www.powdervalleyinc.com # Version 1.0 # Project started on 12/22/15 # First version finished 12/23/15 - No support for email or text # Version 1.1 # Added support for text through <EMAIL> -- finished 12/28/15 # TODO: text to multiple people, figure out why text shows a period at the end # Version 1.2 # Added support for multiple people(brackets around msg_to) -- finished 12/29/15 # Period at the end of texts seems to be normal # Link for grab - http://www.powdervalleyinc.com/hodgdon.shtml #Libraries for email/text import smtplib from email.MIMEText import MIMEText #Libraries for parsing data from bs4 import BeautifulSoup import requests import re # For support, consult http://www.scottcking.com/?p=146 # The headers and msg_body section is scottcking's code def email(): msg_from = '' # who the message is 'from' # msg_subject = '' # message subject -- if i ever want to email this alert msg_to = ['', '', ''] # phone to text/email msg_text = '''Varget is in stock!<br><br>Go to http://powdervalleyinc.com now to order.''' # alert message, will never change -- variable is needed for headers/formatting # If intent is SMS/text, remove/comment the header subject line # If intent is e-mail, add/uncomment the header subject line headers = ['From: {}'.format(msg_from), #'Subject: {}'.format(msg_subject), 'To: {}'.format(msg_to), 'MIME-Version: 1.0', 'Content-Type: text/html'] msg_body = '\r\n'.join(headers) + '\r\n\r\n' + msg_text session = smtplib.SMTP('smtp.gmail.com', 587) session.ehlo() session.starttls() session.login('', '') #'username','password' note: password in plaintext is very dangerous session.sendmail(msg_from, msg_to, msg_body) session.quit() def main(): #imports HTML and adds it to soup r = requests.get('http://www.powdervalleyinc.com/hodgdon.shtml') soup = BeautifulSoup(r.content, "html.parser") powder = [] stock = [] # Finds Varget, strips HTML tags for i in soup('td',text=re.compile('VARGET')): powder.append(i.text) stock.append(i.next_sibling.next.text) # For a second powder... # for i in soup('td',text=re.compile('H110 -')): # powder.append(i.text) # stock.append(i.next_sibling.next.text) i=0 count = 0 # Iterates list and prints what is in stock while i < len(powder): if (stock[i] == 'Yes'): print powder[i] + ' >In Stock<' # Adds count if powder is in stock. Used for email() count += 1 else: print powder[i] + ' >Out of Stock<' i+=1 # If stock is found, email is called # if count >= 1: # email() if __name__ == '__main__': main()
300c153893dd16562140ff76ffb4ab0509479674
[ "Python" ]
3
Python
njclapp/PowderCheck
556935997cd011699feab194a2b9457c16db03b5
a0cceb883c18ea67d8dda956a7d7e60e32881521
refs/heads/main
<file_sep>import "./explorePage.css" const ExplorePage = () => { return ( <div className="explore-page"> <div className="header"> <i className="fa fa-search icon"></i> <input type="text" className="search-input" placeholder="Search Twitter" /> <button type="button"><i className="material-icons">&#xe8b8;</i></button> </div> <div className="explore-page-content"> <div> <div id="image"></div> <div id="imageInfo"> <p>COVID-19 LIVE</p> <p>Updates on Covid-19 in Nigeria</p> </div> </div> <div> <h4>Trends for you</h4> <div className="current-trend"> <p>Technology Trending</p> <strong>iPhone 13</strong> <p>7,254k Tweets</p> </div> <div className="current-trend"> <p>Trending in Nigeria</p> <strong>WhatsApp</strong> <p>10.8k Tweets</p> </div> <div className="current-trend"> <p>Trending in Nigeria</p> <strong>Weird MC</strong> <p>12k Tweets</p> </div> <div className="current-trend"> <p>Hip hop Trending</p> <strong>Lil Wayne</strong> <p>4,664 Tweets</p> </div> <div className="current-trend"> <p>Sports Trending</p> <strong>Hazard</strong> <p>17.4k Tweets</p> </div> </div> <div> <h4>Computer Programming</h4> <div className="tweet-content-item"> <img src="https://images.pexels.com/photos/6735182/pexels-photo-6735182.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" className="home-page-photo" alt="user-profile" /> <div> <div className="tweet-person"> <strong><NAME></strong> <button><i className="material-icons">&#xe5d3;</i></button> </div> <p> As developers, one of the most used body part is our eyes due to staring at screens. </p> <div className="tweet-info"> <button><i className="fa fa-comment-o"></i>5.1k</button> <button><i className="fa fa-retweet"></i>2.1k</button> <button><i className="fa fa-heart-o"></i>3.1k</button> <button><i className="fa fa-upload"></i></button> </div> </div> </div> <div className="tweet-content-item"> <img src="https://images.pexels.com/photos/2083188/pexels-photo-2083188.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" className="home-page-photo" alt="user-profile" /> <div> <div className="tweet-person"> <strong><NAME></strong> <button><i className="material-icons">&#xe5d3;</i></button> </div> <p> Interviewer: What makes you think you are qualified for this job? Developer: I know 2 things, how to open my editor and how to search google </p> <div className="tweet-info"> <button><i className="fa fa-comment-o"></i>5.1k</button> <button><i className="fa fa-retweet"></i>2.1k</button> <button><i className="fa fa-heart-o"></i>3.1k</button> <button><i className="fa fa-upload"></i></button> </div> </div> </div> <div className="tweet-content-item"> <img src="https://images.pexels.com/photos/3853513/pexels-photo-3853513.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" className="home-page-photo" alt="user-profile" /> <div> <div className="tweet-person"> <strong><NAME></strong> <button><i className="material-icons">&#xe5d3;</i></button> </div> <p> Bad Habits you should break as a developer! </p> <div className="tweet-info"> <button><i className="fa fa-comment-o"></i>5.1k</button> <button><i className="fa fa-retweet"></i>2.1k</button> <button><i className="fa fa-heart-o"></i>3.1k</button> <button><i className="fa fa-upload"></i></button> </div> </div> </div> </div> </div> </div> ) } export default ExplorePage <file_sep>export { TrendingPane } from './trendingPane' export { HomePage } from './homePage' export { LeftNav } from './leftNav' export { ProfilePage } from './profilePage' export { ExplorePage } from './explorePage' export { NotificationPage } from './notificationPage' export { BookmarkPage } from './bookmarkPage' export { ListsPage } from './listsPage' export { MessagePage } from './messagePage' export { CommentPage } from './commentPage' export { SettingsPage } from './settingsPage' <file_sep>import { useHistory } from "react-router-dom" import { CONSTANTS } from './constants' const Tweets = ({ tweetData, setCommentModal, setTweetDropdown, setSelectedTweet, bio }) => { const history = useHistory() const openTweetDropdown = (event, tweetItem) => { event.stopPropagation() const top = event.clientY setTweetDropdown({isActive: true, position: (top + 'px')}) setSelectedTweet(tweetItem) } const openCommentModal = (event, tweetItem) => { event.stopPropagation() setCommentModal(true) setSelectedTweet(tweetItem) } return ( tweetData && tweetData.map(tweetItem => ( <div onClick={() => {history.push("/comment"); setSelectedTweet(tweetItem) }} key={tweetItem.id} className="tweet-item" > <div className="tweet-content-item"> <img onClick={event => { event.stopPropagation(); history.push("/profile") }} src={bio?.profilePhoto || CONSTANTS.PHOTOURL} className="home-page-photo" alt="user-profile" /> <div> <div className="tweet-person"> <strong onClick={event => { event.stopPropagation(); history.push("/profile") }} > {bio?.name || CONSTANTS.NAME} </strong> <button type="button" title="More" onClick={event => openTweetDropdown(event, tweetItem)} > <i className="material-icons">&#xe5d3;</i> </button> </div> <p>{tweetItem.tweetText}</p> <div className="tweet-info"> <button type="button" onClick={event => openCommentModal(event, tweetItem)} > <i className="fa fa-comment-o"></i> 5.1k </button> <button type="button"><i className="fa fa-retweet"></i>2.1k</button> <button type="button"><i className="fa fa-heart-o"></i>3.1k</button> <button type="button"><i className="fa fa-upload"></i></button> </div> </div> </div> </div> )) ) } export default Tweets <file_sep>import { useState } from "react" import Tweets from "../common/Tweets" import CommentModal from "../commentPage/CommentModal" import TweetDropdown from "../common/TweetDropdown" import DeleteModal from "../common/DeleteModal" import { inputEventHandler, addTweetData } from "../common/helper" import EditTweetModal from "../common/EditTweetModal" import { CONSTANTS } from '../common/constants' import MobileLeftNav from "../leftNav/MobileLeftNav" import EditProfileModal from '../profilePage/EditProfileModal' import './homePage.css' const HomePage = ({ tweetData, commentModal, editTweetModal, setEditTweetModal, setCommentModal, tweetDropdown, setTweetDropdown, deleteModalIsVisible, setDeleteModalIsVisible, selectedTweet, setSelectedTweet, bioData }) => { const [editModalDisplay, setEditModal] = useState(false) const [mobileLeftNav, setMobileLeftNav] = useState(false) const bio = bioData[0] return ( <div className="home-page"> <div className="header"> <button onClick={() => setMobileLeftNav(true)} className="fa fa-align-justify"></button> <span>Home</span> </div> <div className="home-page-content"> <div id="tweetContainer"> <img src={bio?.profilePhoto || CONSTANTS.PHOTOURL} className="home-page-photo" alt="user-profile" /> <div> <div> <textarea onKeyUp={(event) => bio ? inputEventHandler(event, '#tweetHomeBox', '#tweetHomeButton') : setEditModal(true) } id="tweetHomeBox" className="input-box" placeholder="What's happening?" > </textarea> <strong>Everyone can reply</strong> </div> <div className="tweet-options"> <div> <input type="file" id="addPhoto" /> <label htmlFor="addPhoto"> <span><i className="fa fa-file-picture-o" id="photoIcon"></i></span> </label> <span><i className="fa fa-git-square"></i></span> <span><i className="fa fa-bar-chart"></i></span> <span><i className="fa fa-smile-o"></i></span> <span><i className="fa fa-calendar-plus-o"></i></span> </div> <button onClick={() => addTweetData('#tweetHomeBox')} type="button" id="tweetHomeButton" className="tweet-button" > Tweet </button> </div> </div> </div> <div> <Tweets tweetData={tweetData} setSelectedTweet={setSelectedTweet} setCommentModal={setCommentModal} setTweetDropdown={setTweetDropdown} bio={bio} /> </div> </div> {commentModal && <CommentModal setCommentModal={setCommentModal} bio={bio} selectedTweet={selectedTweet} /> } {tweetDropdown.isActive && <TweetDropdown tweetDropdown={tweetDropdown} setTweetDropdown={setTweetDropdown} setDeleteModalIsVisible={setDeleteModalIsVisible} setEditTweetModal={setEditTweetModal} /> } {deleteModalIsVisible && <DeleteModal selectedTweet={selectedTweet} setDeleteModalIsVisible={setDeleteModalIsVisible} /> } {editTweetModal && <EditTweetModal tweetData={tweetData} tweetDropdown={tweetDropdown} setEditTweetModal={setEditTweetModal} selectedTweet={selectedTweet} bio={bio} /> } {editModalDisplay && <EditProfileModal setEditModal={setEditModal} bio={bio} /> } { mobileLeftNav && <MobileLeftNav setMobileLeftNav={setMobileLeftNav} bio={bio} /> } </div> ) } export default HomePage <file_sep>import { useHistory } from 'react-router' import './listsPage.css' const ListsPage = () => { const history = useHistory() return ( <div className="lists-page"> <div className="header"> <button onClick={() => history.goBack()} type="button" > <i className="material-icons">&#xe5c4;</i> </button> <div> <span>Lists</span> <small>@Marvel1167481</small> </div> </div> <div className="lists-page-content"> <div className="list"> <h4>Pinned Lists</h4> <p>Nothing to see here yet - pin your favorite Lists to access them quickly</p> </div> <div> <h4>Discover new Lists</h4> <div className="new-list-item"> <img src="https://pbs.twimg.com/media/EXZ2mJCUEAEbJb3?format=png&name=small" alt="user-profile"/> <div> <p>Celebrities</p> <p><strong>kingbookah</strong>_@kingbookah</p> </div> <button type="button">Follow</button> </div> <div className="new-list-item"> <img src="https://pbs.twimg.com/media/EXZ2mJCUEAEbJb3?format=png&name=small" alt="user-profile"/> <div> <p>LEMTOL ORGANIC ANTISEPTIC</p> <p><strong>LEMTOL ORGANIC ANTISEPTIC </strong>@ lemtola</p> </div> <button type="button">Follow</button> </div> </div> <div className="list"> <h4>Your Lists</h4> <p>You haven't created or followed any Lists. When you do, they'll show up here.</p> </div> </div> </div> ) } export default ListsPage <file_sep>import database from '../../dataBase' import { CONSTANTS } from '../common/constants' const CommentModal = ({ setCommentModal, bio, selectedTweet }) => { const addComment = async () => { const commentText = document.querySelector('#commentTextBox').value const commentObject = { commentText, parentId: selectedTweet.id } await database.commentData.add(commentObject) setCommentModal(false) } const inputEventHandler = event => { const inputValue = document.querySelector('#commentTextBox').value if (inputValue.trim().length >= 1) { document.querySelector('#commentButton').classList.add('enable') const keyCode = event.which || event.keyCode if (keyCode === 13 && event.shiftKey) { addComment() } } else { document.querySelector('#commentButton').classList.remove('enable') } } return ( <> <div className="overlay" onClick={() => setCommentModal(false)}></div> <div className="comment-modal"> <div className="tweet-modal-header"> <button type="button" onClick={() => setCommentModal(false)}> <i className="material-icons">&#xe5cd;</i> </button> </div> <div className="comment-content"> <img src={bio?.profilePhoto || CONSTANTS.PHOTOURL} className="home-page-photo" alt="user-profile" /> <div> <span className="user-profile-name">{bio?.name || CONSTANTS.NAME}</span> <p>{selectedTweet.tweetText}</p> </div> </div> <div className="comment-input"> <img src={bio?.profilePhoto || CONSTANTS.PHOTOURL} className="home-page-photo" alt="user-profile" /> <textarea onKeyUp={inputEventHandler} className="input-box" id="commentTextBox" placeholder="Tweet your reply" > </textarea> </div> <div className="tweet-options"> <div> <span><i className="fa fa-file-picture-o"></i></span> <span><i className="fa fa-git-square"></i></span> <span><i className="fa fa-bar-chart"></i></span> <span><i className="fa fa-smile-o"></i></span> <span><i className="fa fa-calendar-plus-o"></i></span> </div> <button onClick={addComment} id="commentButton" className="tweet-button">Reply</button> </div> </div> </> ) } export default CommentModal <file_sep>const contactList = [ { id: 'tyui', name: '<NAME>', photoUrl: 'https://images.pexels.com/photos/2703463/pexels-photo-2703463.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' }, { id: 'bjhf', name: '<NAME>', photoUrl: 'https://images.pexels.com/photos/2700116/pexels-photo-2700116.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' }, { id: 'kjfn', name: '<NAME>', photoUrl: 'https://images.pexels.com/photos/5649341/pexels-photo-5649341.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' }, { id: 'yhji', name: '<NAME>', photoUrl: 'https://images.pexels.com/photos/4401285/pexels-photo-4401285.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' }, { id: 'kjue', name: '<NAME>', photoUrl: 'https://images.pexels.com/photos/2703463/pexels-photo-2703463.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' } ] export default contactList <file_sep>import { useLiveQuery } from 'dexie-react-hooks' import { useState } from 'react' import { BrowserRouter, Route, Switch } from 'react-router-dom' import database from './dataBase' import { TrendingPane, HomePage, LeftNav, ProfilePage, ExplorePage, NotificationPage, BookmarkPage, ListsPage, MessagePage, CommentPage, SettingsPage } from './components' import './index.css' const App = () => { const storedTheme = localStorage.getItem('storedTheme') const storedTextColor = localStorage.getItem('storedTextColor') const [theme, setTheme] = useState(storedTheme || 'default') const [textColor, setTextColor] = useState(storedTextColor || 'blue') const [activePage, setActivePage] = useState('') const [editTweetModal, setEditTweetModal] = useState(false) const [tweetDropdown, setTweetDropdown] = useState({isActive: false}) const [deleteModalIsVisible, setDeleteModalIsVisible] = useState(false) const [commentModal, setCommentModal] = useState(false) const [selectedTweet, setSelectedTweet] = useState({}) const [selectedContact, setSelectedContact] = useState() const bioData = useLiveQuery(() => database.bio.toArray(), []) const tweetData = useLiveQuery(() => database.tweetData.toArray(), []) const commentData = useLiveQuery(() => database.commentData.toArray(), []) const messageData = useLiveQuery(() => database.messageData.toArray(), []) if (!bioData) return null if (!tweetData) return null if (!commentData) return null if (!messageData) return null return ( <BrowserRouter> <div className={`app-layer ${theme} ${textColor}`}> <LeftNav theme={theme} setTheme={setTheme} textColor={textColor} setTextColor={setTextColor} setActivePage={setActivePage} activePage={activePage} bioData={bioData} /> <Switch> <Route path="/" component={() => ( <HomePage tweetData={tweetData} commentModal={commentModal} setCommentModal={setCommentModal} tweetDropdown={tweetDropdown} setTweetDropdown={setTweetDropdown} deleteModalIsVisible={deleteModalIsVisible} setDeleteModalIsVisible={setDeleteModalIsVisible} editTweetModal={editTweetModal} setEditTweetModal={setEditTweetModal} selectedTweet={selectedTweet} setSelectedTweet={setSelectedTweet} bioData={bioData} /> )} exact /> <Route path="/comment" component={() => ( <CommentPage bioData={bioData} selectedTweet={selectedTweet} commentData={commentData} /> )} /> <Route path="/profile" component={() => ( <ProfilePage tweetData={tweetData} commentModal={commentModal} setCommentModal={setCommentModal} tweetDropdown={tweetDropdown} setTweetDropdown={setTweetDropdown} deleteModalIsVisible={deleteModalIsVisible} setDeleteModalIsVisible={setDeleteModalIsVisible} editTweetModal={editTweetModal} setEditTweetModal={setEditTweetModal} selectedTweet={selectedTweet} setSelectedTweet={setSelectedTweet} bioData={bioData} /> )} /> <Route path="/explore" component={ExplorePage}/> <Route path="/notification" component={NotificationPage}/> <Route path="/bookmark" component={BookmarkPage}/> <Route path="/list" component={ListsPage}/> </Switch> <Switch> <Route path="/messages" component={() => ( <MessagePage messageData={messageData} selectedContact={selectedContact} setSelectedContact={setSelectedContact} /> )} /> <Route path="/settings" component={() => ( <SettingsPage theme={theme} setTheme={setTheme} textColor={textColor} setTextColor={setTextColor} /> )} /> <TrendingPane /> </Switch> </div> </BrowserRouter> ) } export default App <file_sep>import { useState } from "react" import { useHistory } from "react-router-dom" import Tweets from '../common/Tweets' import CommentModal from "../commentPage/CommentModal" import DeleteModal from "../common/DeleteModal" import TweetDropdown from "../common/TweetDropdown" import EditTweetModal from "../common/EditTweetModal" import { CONSTANTS } from '../common/constants' import EditProfileModal from './EditProfileModal' import './profilePage.css' const ProfilePage = ({ tweetData, commentModal, editTweetModal, setEditTweetModal, selectedTweet, setCommentModal, tweetDropdown, setTweetDropdown, deleteModalIsVisible, setDeleteModalIsVisible, setSelectedTweet, bioData }) => { const { goBack } = useHistory() const [editModalDisplay, setEditModal] = useState(false) const bio = bioData[0] return ( <div className="profile-page"> <div className="header"> <button onClick={() => goBack()} type="button" > <i className="material-icons">&#xe5c4;</i> </button> <div> <span>{bio?.name || CONSTANTS.NAME}</span> <small>4 Tweets</small> </div> </div> <div className="page-content"> <img src={bio?.headerPhoto || CONSTANTS.PHOTOURL} className="photo" alt=""/> <div className="user-bio-container"> <div> <div className="profile-photo"> <img src={bio?.profilePhoto || CONSTANTS.PHOTOURL} alt=""/> </div> <div className="user-bio"> <strong>{bio?.name || CONSTANTS.NAME}</strong> <p>{bio?.aboutUser}</p> <span><i className="material-icons">&#xe55f;</i>{bio?.location}</span> <span><i className="fa fa-birthday-cake"></i>{bio?.birthDate}</span> <span><i className="fa fa-calendar"></i>Joined January 2021</span> <div> <span><strong>48 </strong>Following</span> <span><strong>8 </strong>Followers</span> </div> </div> </div> <button onClick={() => setEditModal(true)} type="button"> Edit profile </button> </div> <div className="options-button"> <button>Tweets</button> <button>Tweets & replies</button> <button>Media</button> <button>Likes</button> </div> <div id="tweetOutput"> <Tweets tweetData={tweetData} bio={bio} setSelectedTweet={setSelectedTweet} setCommentModal={setCommentModal} setTweetDropdown={setTweetDropdown} /> </div> </div> { editModalDisplay && <EditProfileModal setEditModal={setEditModal} bio={bio} /> } {commentModal && <CommentModal setCommentModal={setCommentModal} selectedTweet={selectedTweet} bio={bio} /> } {tweetDropdown.isActive && <TweetDropdown tweetDropdown={tweetDropdown} setTweetDropdown={setTweetDropdown} setDeleteModalIsVisible={setDeleteModalIsVisible} setEditTweetModal={setEditTweetModal} /> } {deleteModalIsVisible && <DeleteModal selectedTweet={selectedTweet} setDeleteModalIsVisible={setDeleteModalIsVisible} /> } {editTweetModal && <EditTweetModal tweetData={tweetData} tweetDropdown={tweetDropdown} setEditTweetModal={setEditTweetModal} selectedTweet={selectedTweet} bio={bio} /> } </div> ) } export default ProfilePage <file_sep>import { displaySettingsPage } from '../common/helper' const ResourceSection = () => { return ( <div className="resource-section"> <div className="section header"> <button type="button" onClick={displaySettingsPage} className="previous-button"> <i className="material-icons">&#xe5c4;</i> </button> <span>Additional resources</span> </div> <div className="section-content"> <div> <span>Check out other places for helpful information to learn more about Twitter products and services. </span> </div> <div> <h3>Release notes</h3> </div> <section className="more-options"> <button type="button" className="button"> <p>Release notes</p> <i className="material-icons">&#xe315;</i> </button> </section> <section className="more-options"> <div> <h3>Legal</h3> </div> <button type="button" className="button"> <p>Ads info</p> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p>Cookie policy</p> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p>Privacy policy</p> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p>Terms of Service</p> <i className="material-icons">&#xe315;</i> </button> </section> <section className="more-options"> <div> <h3>Miscellaneous</h3> </div> <button type="button" className="button"> <p>About</p> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p>Advertising</p> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p>Blog</p> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p>Brand Resources</p> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p>Careers</p> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p>Developers</p> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p>Help Center</p> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p>Marketing</p> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p>Status</p> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p>Twitter for Business</p> <i className="material-icons">&#xe315;</i> </button> </section> </div> </div> ) } export default ResourceSection <file_sep>import { useState } from 'react' import database from '../../dataBase' import Message from './Message' const InitialChatSection = () => { return ( <div className="initial-message-section"> <strong>You don’t have a message selected</strong> <p>Choose one from your existing messages, or start a new one.</p> <button type="button" className="message-button">New message</button> </div> ) } const ChatSection = ({ messageData, selectedContact }) => { const [chatDropdown, setChatDropdown] = useState({isActive: false}) const [deleteModal, setDeleteModal] = useState(false) const [selectedMessageId, setSelectedMessageId] = useState('') const addMessageData = async () => { const text = document.querySelector('#messageBox').value const messageId = 'id' + Date.parse(new Date()).toString() const chatTime = new Date().toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true }) const messageObject = { messageId, text, chatTime, selectedContact } await database.messageData.add(messageObject) } const inputEventHandler = event => { const inputValue = document.querySelector('#messageBox').value if (inputValue.trim().length >= 1) { document.querySelector('.send-button').classList.add('allow') if (event.which === 13) { addMessageData() } } else { document.querySelector('.send-button').classList.remove('allow') } } const deleteMessage = async () => { await database.messageData.delete(selectedMessageId) setDeleteModal(false) } const displayContactSection = () => { document.querySelector('.current-message-section').style.display = 'none' document.querySelector('#contactSection').style.display = 'block' document.querySelector('.left-nav-content').style.display = 'flex' } return ( <> {!selectedContact && <InitialChatSection />} {selectedContact && ( <div className="message-section"> <div className="section-header"> <button type="button" onClick={displayContactSection} className="previous-button"> <i className="material-icons">&#xe5c4;</i> </button> <img src={selectedContact?.photoUrl} className="home-page-photo" alt="user-profile" /> <strong>{selectedContact?.name}</strong> <span className="material-icons">&#xe88f;</span> </div> <div id="sectionContent"> <div className="message-container"> <Message messageData={messageData} selectedContact={selectedContact} setChatDropdown={setChatDropdown} setSelectedMessageId={setSelectedMessageId} /> </div> <form> <span className="fa fa-file-picture-o"></span> <span className="fa fa-git-square"></span> <textarea onKeyUp={(event) => inputEventHandler(event)} id="messageBox" placeholder="Start a new message" autoFocus > </textarea> <span className="fa fa-smile-o smiley-icon"></span> <button onClick={() => addMessageData()} className="material-icons send-button"> &#xe163; </button> </form> </div> </div> )} {chatDropdown.isActive && ( <div> <div className="overlay" style={{backgroundColor: "transparent"}} onClick={() => setChatDropdown(false)} > </div> <div className="chat-dropdown" style={{top: chatDropdown.top}}> <button onClick={() => { setDeleteModal(true); setChatDropdown(false) }} > <i className="fa fa-trash-o"></i> Delete for you </button> <button type="button"> <i className="fa fa-edit"></i> Copy message </button> </div> </div> )} {deleteModal && ( <> <div onClick={() => setDeleteModal(false)} className="overlay"></div> <div className="delete-modal"> <h3>Delete Tweet?</h3> <p>This message will be deleted for you. Other people in the conversation will still be able to see it. </p> <button onClick={() => setDeleteModal(false)} className="cancel-button"> Cancel </button> <button onClick={deleteMessage} className="confirm-button"> Delete </button> </div> </> )} </> ) } export { InitialChatSection, ChatSection } <file_sep>import Dexie from 'dexie' const database = new Dexie('Twitter') database.version(1).stores( { bio: '++id,name,aboutUser,location,website,birthDate,profilePhoto,headerPhoto', tweetData: '++id,tweetText', commentData: '++id,commentText,parentId', messageData: 'messageId,text,chatTime,selectedContact' } ) export default database <file_sep>import "./notificationPage.css" const NotificationPage = () => { return ( <div className="notification-page"> <div id="header"> <div> <span>Notifications</span> <button type="button"><i className="material-icons">&#xe8b8;</i></button> </div> <div id="pageNavButtons"> <button type="button" className="current">All</button> <button type="button">Mentions</button> </div> </div> <div className="notification-page-content"> <div> <i className="fa fa-bell symbol"></i> <div> <img src="https://images.pexels.com/photos/1725399/pexels-photo-1725399.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="user-profile"/> <p>New Tweet notifications for <strong><NAME></strong></p> </div> </div> <div> <i className="fa fa-user-o symbol"></i> <div> <img src="https://images.pexels.com/photos/6924280/pexels-photo-6924280.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="user-profile"/> <p><strong><NAME></strong> followed you</p> </div> </div> <div> <i className="fa fa-heart heart-icon"></i> <div> <img src="https://images.pexels.com/photos/1725399/pexels-photo-1725399.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="user-profile"/> <p><strong><NAME></strong> liked your Tweet</p> <p>Ten ways to know a junior developer</p> </div> </div> <div> <i className="fa fa-star"></i> <div> <img src="https://images.pexels.com/photos/6338278/pexels-photo-6338278.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="user-profile"/> <p>Recommended For You</p> <p>I'm fired</p> </div> </div> <div> <i className="fa fa-heart heart-icon"></i> <div> <img src="https://images.pexels.com/photos/1983917/pexels-photo-1983917.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="user-profile"/> <p><strong><NAME></strong> liked tour Tweet</p> <p>hey</p> </div> </div> <div> <i className="fa fa-bell symbol"></i> <div> <img src="https://images.pexels.com/photos/1725399/pexels-photo-1725399.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="user-profile"/> <p>New Tweet notifications for <strong>Ebenezer Don</strong></p> </div> </div> <div> <i className="fa fa-user-o symbol"></i> <div> <img src="https://images.pexels.com/photos/6924280/pexels-photo-6924280.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="user-profile"/> <p><strong><NAME></strong> followed you</p> </div> </div> <div> <i className="fa fa-star"></i> <div> <img src="https://images.pexels.com/photos/6338278/pexels-photo-6338278.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="user-profile"/> <p>Recommended For You</p> <p>I'm fired</p> </div> </div> </div> </div> ) } export default NotificationPage <file_sep>export { default as BookmarkPage } from './BookmarkPage' <file_sep>const Message = ({ messageData, selectedContact, setChatDropdown, setSelectedMessageId }) => { const filteredData = messageData.filter(item => item.selectedContact.id === selectedContact.id) const openMessageOptions = (selector) => { document.querySelector(`#${selector}`).style.visibility = 'visible' } const closeMessageOptions = (selector) => { document.querySelector(`#${selector}`).style.visibility = 'hidden' } const openTweetDropdown = (event, id) => { const top = event.clientY setChatDropdown({isActive: true, top: (top + 'px')}) setSelectedMessageId(id) } return ( filteredData.map(messageItem => ( <div key={messageItem.messageId} onMouseOver={() => openMessageOptions(messageItem.messageId) } onMouseOut= {() => closeMessageOptions(messageItem.messageId)} className="message-item" > <div> <div className="message-content"> <div id={messageItem.messageId} className="message-options"> <p className="fa">&#xf08a;</p> <p onClick={(event) => openTweetDropdown(event, messageItem.messageId)} className="material-icons" > &#xe5d3; </p> </div> <p className="message">{messageItem.text}</p> </div> <p className="message-time">Today at {messageItem.chatTime}✔</p> </div> </div> )) ) } export default Message <file_sep>import database from '../../dataBase' const DeleteModal = ({ setDeleteModalIsVisible, selectedTweet }) => { const deleteTweet = async id => { await database.tweetData.delete(id) setDeleteModalIsVisible(false) } return ( <> <div onClick={() => setDeleteModalIsVisible(false)} className="overlay"></div> <div className="delete-modal"> <h3>Delete Tweet?</h3> <p>This can't be undone and it will be removed from your timeline.</p> <button onClick={() => setDeleteModalIsVisible(false)} className="cancel-button"> Cancel </button> <button onClick={() => deleteTweet(selectedTweet.id)} className="confirm-button"> Delete </button> </div> </> ) } export default DeleteModal <file_sep>import { displaySettingsPage } from '../common/helper' const AccountSection = () => { return ( <div className="account-section"> <div className="section header"> <button type="button" onClick={displaySettingsPage} className="previous-button"> <i className="material-icons">&#xe5c4;</i> </button> <span>Your Account</span> </div> <div className="section-content"> <div> <span>See information about your account, download an archive of your data, or learn about your account deactivation options </span> </div> <button type="button" className="button"> <p className="fa fa-user-o "></p> <div> <p>Account information</p> <span>See your information like your phone number and email address.</span> </div> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p className="material-icons">&#xe0da;</p> <div> <p>Change your password</p> <span>Change your password at any time.</span> </div> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p className="fa">&#xf019;</p> <div> <p>Download an archive of your data</p> <span>Get insights inot the type of information stored for your account</span> </div> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p className="material-icons">&#xe7fc;</p> <div> <p>TweetDeck's Team</p> <span>Invite anyone to Tweet from this account using TweetDeck's Teams.</span> </div> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p className="fa fa-heart-o"></p> <div> <p>Deactivate your account</p> <span>Find out how you can deactivate your account</span> </div> <i className="material-icons">&#xe315;</i> </button> </div> </div> ) } export default AccountSection <file_sep>import { useHistory } from 'react-router-dom' import { useState } from "react" import CommentModal from './CommentModal' import Comments from "./Comments" import { CONSTANTS } from '../common/constants' import './commentPage.css' const CommentPage = ({ bioData, selectedTweet, commentData }) => { const [commentModalDisplay, setCommentModal] = useState(false) const { goBack } = useHistory() const bio = bioData[0] return ( <div id={selectedTweet.id} className="comment-page"> <div className="header"> <button onClick={() => goBack()}><i className="material-icons">&#xe5c4;</i></button> <span>Tweet</span> </div> <div className="tweet-content"> <div> <img src={bio?.profilePhoto || CONSTANTS.PHOTOURL} className="home-page-photo" alt="user-profile" /> <strong className="user-profile-name">{bio?.name || CONSTANTS.NAME}</strong> <button><i className="material-icons">&#xe5d3;</i></button> </div> <div> <p className="tweet-text">{selectedTweet.tweetText}</p> <p id="time">2:51pm. Feb 15, 2021. Twitter Web App</p> </div> <div className="tweet-interaction"> <span><strong>42 </strong>Retweets</span> <span><strong>12 </strong>Quote Tweets</span> <span><strong>675 </strong>Likes</span> </div> <div className="user-tweet-options"> <button title="Reply" onClick={() => setCommentModal(true)} > <i className="fa fa-comment-o"></i> </button> <button><i className="fa fa-retweet"></i></button> <button><i className="fa fa-heart-o"></i></button> <button><i className="fa fa-upload"></i></button> </div> </div> <div id="commentOutput"> <Comments commentData={commentData} bio={bio} selectedTweet={selectedTweet} /> </div> {commentModalDisplay && <CommentModal setCommentModal={setCommentModal} bio={bio} selectedTweet={selectedTweet} /> } </div> ) } export default CommentPage <file_sep>import { useState } from "react" import './trendingPane.css' const TrendingPane = () => { const [modalActive, setModalActive] = useState(false) const trendModal = ( <> <div onClick={() => setModalActive(false)} className="overlay"></div> <div className="trend-modal"> <button type="button" onClick={() => setModalActive(false)}> <i className="material-icons">&#xe5cd;</i> </button> <h4>Trends</h4> <div className="set-trend"> <p>Location</p> <div> <div className="checkbox-container"> <span>Show content in this location</span> <label id="container"> <input type="checkbox" /> <span id="checkmark"></span> </label> </div> <small>When this is on, you'll see what's happening around you right now.</small> </div> </div> <div className="set-trend"> <p>Personalization</p> <div> <div className="checkbox-container"> <span>Trends for you</span> <label id="container"> <input type="checkbox" /> <span id="checkmark"></span> </label> </div> <small>You can personalize trends based on your location and who you follow</small> </div> </div> </div> </> ) return ( <div className="trending-pane"> <i className="fa fa-search"></i> <input type="text" className="search-input" placeholder="Search Twitter" /> <div className="trending-tweets"> <h4>Trends</h4> <button type="button" onClick={() => setModalActive(true)}><i className="material-icons">&#xe8b8;</i></button> <div className="current-trend"> <p>Trending in Nigeria</p> <strong>Erica</strong> <p>Trending with: Laycon, #BBNaijaLockdown</p> <p>128k Tweets</p> </div> <div className="current-trend"> <p>Trending in Nigeria</p> <strong>Rema</strong> <p>Trending with: Laycon, #BBNaijaLockdown</p> <p>28.1k Tweets</p> </div> <div className="current-trend"> <p>Trending in Nigeria</p> <strong>#bobrisky</strong> <p>12.5k Tweets</p> </div> <div className="current-trend"> <p>Trending in Nigeria</p> <strong>Tosin</strong> <p>Trending with: Laycon, #BBNaijaLockdown</p> <p>2,833 Tweets</p> </div> <div className="current-trend"> <p>Trending in Nigeria</p> <strong>#FreeSomto</strong> <p>Trending with: Laycon, #BBNaijaLockdown</p> <p>2,282 Tweets</p> </div> <div className="current-trend"> <p>Trending in Nigeria</p> <strong>Erica</strong> <p>Trending with: Laycon, #BBNaijaLockdown</p> <p>128k Tweets</p> </div> <div className="current-trend"> <p>Trending in Nigeria</p> <strong>Erica</strong> <p>Trending with: Laycon, #BBNaijaLockdown</p> <p>128k Tweets</p> </div> </div> { modalActive && trendModal } </div> ) } export default TrendingPane <file_sep>export { default as ListsPage } from './ListsPage' <file_sep>import { displaySettingsPage } from '../common/helper' const SecuritySection = () => { return ( <div className="security-section"> <div className="section header"> <button type="button" onClick={displaySettingsPage} className="previous-button"> <i className="material-icons">&#xe5c4;</i> </button> <span>Security and account access</span> </div> <div className="section-content"> <div> <span>Manage your account’s security and keep track of your account’s usage including apps that you have connected to your account. </span> </div> <button type="button" className="button"> <p className="material-icons">&#xe899;</p> <div> <p>Security</p> <span>Manage your account's security</span> </div> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p className="material-icons">&#xe14d;</p> <div> <p>Apps and sessions</p> <span>See information about when you logged into your account and the apps you connected to your account. </span> </div> <i className="material-icons">&#xe315;</i> </button> </div> </div> ) } export default SecuritySection <file_sep>import { Link } from 'react-router-dom' const DropDownModal = ({ setDropDownDisplay, setDisplayModal }) => { return ( <> <div className="overlay" style={{backgroundColor: "#110d0d0a"}} onClick={() => setDropDownDisplay(false)} > </div> <div className="dropdown-content"> <button className="dropdown-button"> <i className="material-icons">&#xe8e1;</i> Topics </button> <button className="dropdown-button"> <i className="fa fa-bolt"></i> Moments </button> <button className="dropdown-button"> <i className="fa fa-external-link-square"></i> Twitter Ads </button> <button className="dropdown-button"> <i className="fa fa-bar-chart"></i> Analytics </button> <Link to='./settings' className="dropdown-button" onClick={() => setDropDownDisplay(false)} > <i className="material-icons">&#xe8b8;</i> Settings and privacy </Link> <button className="dropdown-button"> <i className="fa fa-question-circle-o"></i> Help Center </button> <button className="dropdown-button" onClick={() => {setDisplayModal(true); setDropDownDisplay(false)}} > <i className="material-icons">&#xe3ae;</i> Display </button> </div> </> ) } export default DropDownModal <file_sep>import { useState } from 'react' import { useHistory } from "react-router-dom" import AccessiblitySection from './AccessiblitySection' import AccountSection from './AccountSection' import DisplaySection from './DisplaySection.js' import NotificationSection from './NotificationSection' import PrivacySection from './PrivacySection' import ResourceSection from './ResourceSection.js' import SecuritySection from './SecuritySection' import './settingsPage.css' const SettingsPage = ({ theme, setTheme, textColor, setTextColor }) => { const [currentSection, setCurrentSection] = useState(localStorage.getItem('storedSection') || 'account') const switchCurrentSection = name => { if (window.innerWidth <= 768) { document.querySelector('#settingsPage').style.display = 'none' document.querySelector('#currentSection').style.display = 'block' } setCurrentSection(name) localStorage.setItem('storedSection', name) } const { goBack } = useHistory() return ( <div className="settings-page"> <div id="settingsPage"> <div className="headline"> <button type="button" onClick={() => goBack()} className="previous-button"> <i className="material-icons">&#xe5c4;</i> </button> <span>Settings</span> </div> <div className="settings page-core"> <button onClick={() => switchCurrentSection('account')} type="button" className={currentSection === 'account' ? 'current-section' : ''} > <span>Your account</span> <i className="material-icons">&#xe315;</i> </button> <button onClick={() => switchCurrentSection('security')} type="button" className={currentSection === 'security' ? 'current-section' : ''} > <span>Security and account access</span> <i className="material-icons">&#xe315;</i> </button> <button onClick={() => switchCurrentSection('privacy')} type="button" className={currentSection === 'privacy' ? 'current-section' : ''} > <span>Privacy and safety</span> <i className="material-icons">&#xe315;</i> </button> <button onClick={() => switchCurrentSection('notification')} type="button" className={currentSection === 'notification' ? 'current-section' : ''} > <span>Notifications</span> <i className="material-icons">&#xe315;</i> </button> <button onClick={() => switchCurrentSection('accessibility')} type="button" className={currentSection === 'accessibility' ? 'current-section' : ''} > <span>Accessibility, display, and languages</span> <i className="material-icons">&#xe315;</i> </button> <button onClick={() => switchCurrentSection('resource')} type="button" className={currentSection === 'resource' ? 'current-section' : ''} > <span>Additional resources</span> <i className="material-icons">&#xe315;</i> </button> </div> </div> <div id="currentSection"> {currentSection === 'account' && <AccountSection />} {currentSection === 'security' && <SecuritySection />} {currentSection === 'notification' && <NotificationSection />} {currentSection === 'accessibility' && <AccessiblitySection switchCurrentSection={switchCurrentSection} /> } {currentSection === 'privacy' && <PrivacySection />} {currentSection === 'resource' && <ResourceSection />} {currentSection === 'display' && <DisplaySection theme={theme} setTheme={setTheme} textColor={textColor} setTextColor={setTextColor} switchCurrentSection={switchCurrentSection} /> } </div> </div> ) } export default SettingsPage <file_sep>import { displaySettingsPage } from '../common/helper' const NotificationSection = () => { return ( <div className="notification-section"> <div className="section header"> <button type="button" onClick={displaySettingsPage} className="previous-button"> <i className="material-icons">&#xe5c4;</i> </button> <span>Notifications</span> </div> <div className="section-content"> <div> <span>Select the kinds of notifications you get about your activities, interests, and recommendations. </span> </div> <button type="button" className="button"> <p className="material-icons">&#xe152;</p> <div> <p>Filters</p> <span>Choose the notification you'd like to see — and those you don't.</span> </div> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p className="material-icons">&#xe0dd;</p> <div> <p>Preferences</p> <span>Select your preferences by notification type.</span> </div> <i className="material-icons">&#xe315;</i> </button> </div> </div> ) } export default NotificationSection <file_sep>import './messagePage.css' import { ContactSection } from "./ContactSection" import { ChatSection } from './ChatSection' const MessagePage = ({ messageData, selectedContact, setSelectedContact }) => { return ( <div className="message-page"> <div id="contactSection"> <div className="headline"> <span>Messages</span> <button type="button"><i className="fa fa-envelope-o"></i></button> </div> <div className="message-contact-page"> <ContactSection selectedContact={selectedContact} setSelectedContact={setSelectedContact} /> </div> </div> <div className="current-message-section"> <ChatSection messageData={messageData} selectedContact={selectedContact} /> </div> </div> ) } export default MessagePage <file_sep>import { displaySettingsPage } from '../common/helper' const AccessiblitySection = ({ switchCurrentSection }) => { return ( <div className="accessibility-section"> <div className="section header"> <button type="button" onClick={displaySettingsPage} className="previous-button"> <i className="material-icons">&#xe5c4;</i> </button> <span>Accessibility, display and languages</span> </div> <div className="section-content"> <div> <span>Manage how Twitter content is displayed to you.</span> </div> <button type="button" className="button"> <p className="material-icons">&#xe8f5;</p> <div> <p>Accessibility</p> <span>Manage aspects of your Twitter experience such as limiting color contrast and motion. </span> </div> <i className="material-icons">&#xe315;</i> </button> <button onClick={() => switchCurrentSection('display')} type="button" className="button" > <p className="material-icons">&#xe3ae;</p> <div> <p>Display</p> <span>Manage your font size, color and background. These settings affect all the Twitter accounts on this browser. </span> </div> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p className="material-icons">&#xe894;</p> <div> <p>Languages</p> <span>Manage which languages are used to personalize your Twitter experience.</span> </div> <i className="material-icons">&#xe315;</i> </button> <button type="button" className="button"> <p className="material-icons">&#xe24b;</p> <div> <p>Data usage</p> <span>Limit how Twitter uses some of your network data. These settings affect all the Twitter accounts on this browser. </span> </div> <i className="material-icons">&#xe315;</i> </button> </div> </div> ) } export default AccessiblitySection <file_sep>export { default as ProfilePage } from "./ProfilePage" <file_sep>import contactList from './contactList' const ContactSection = ({ selectedContact, setSelectedContact }) => { const switchCurrentSection = contact => { if (window.innerWidth <= 768) { document.querySelector('#contactSection').style.display = 'none' document.querySelector('.left-nav-content').style.display = 'none' document.querySelector('.current-message-section').style.display = 'block' } setSelectedContact(contact) } return ( <div className="contact-section"> <div id="searchInputContainer"> <i className="fa fa-search"></i> <input type="text" className="search-input" placeholder="Search for people and groups" /> </div> <div> {contactList.map(contact => ( <div key={contact.id} id={selectedContact === contact.id ? 'current' : ''} className="contact-list" onClick={() => switchCurrentSection(contact)} > <img src={contact.photoUrl} className="home-page-photo" alt="user-profile" /> <div> <div className="tweet-person"> <strong>{contact.name}</strong> </div> </div> </div> )) } </div> </div> ) } export { ContactSection } <file_sep>import database from '../../dataBase' import { CONSTANTS } from './constants' const EditTweetModal = ({ setEditTweetModal, selectedTweet, bio }) => { const editTweetData = async id => { const newTweetInput = document.querySelector('#editTweetBox').value await database.tweetData.update(id, {tweetText: newTweetInput}) setEditTweetModal(false) } const inputEventHandler = event => { const inputValue = document.querySelector('#editTweetBox').value if (inputValue.trim().length >= 1) { document.querySelector('#editTweetButton').classList.add('enable') const keyCode = event.which || event.keyCode if (keyCode === 13 && event.shiftKey) { editTweetData(selectedTweet.id) } } else { document.querySelector('#editTweetButton').classList.remove('enable') } } return ( <> <div onClick={() => setEditTweetModal(false)} className="overlay"></div> <div className="edit-tweet-modal"> <div className="tweet-modal-header"> <button onClick={() => setEditTweetModal(false)} type="button"> <i className="material-icons">&#xe5cd;</i> </button> </div> <div id="tweetContainer"> <img src={bio?.profilePhoto || CONSTANTS.PHOTOURL} className="home-page-photo" alt="user-profile" /> <div> <div> <textarea id="editTweetBox" className="input-box" onKeyUp={inputEventHandler} defaultValue={selectedTweet.tweetText} placeholder="Enter new tweet here..." > </textarea> </div> <div className="tweet-options"> <div> <input type="file" id="addPhoto" /> <label htmlFor="addPhoto"> <span><i className="fa fa-file-picture-o" id="photoIcon"></i></span> </label> <span><i className="fa fa-git-square"></i></span> <span><i className="fa fa-bar-chart"></i></span> <span><i className="fa fa-smile-o"></i></span> <span><i className="fa fa-calendar-plus-o"></i></span> </div> <button onClick={() => editTweetData(selectedTweet.id)} type="button" id="editTweetButton"className="enable tweet-button" > Save </button> </div> </div> </div> </div> </> ) } export default EditTweetModal <file_sep>import database from '../../dataBase' const changeTheme = (theme, setTheme ) => { setTheme(theme) localStorage.setItem('storedTheme', theme) } const changeTextColor = (textColor, setTextColor) => { setTextColor(textColor) localStorage.setItem('storedTextColor', textColor) } const addTweetData = async (selector, setTweetModalDisplay) => { const tweetText = document.querySelector(selector).value await database.tweetData.add({tweetText}) document.querySelector(selector).value = '' setTweetModalDisplay && setTweetModalDisplay(false) } const inputEventHandler = (event, inputSelector, buttonSelector, setTweetModalDisplay ) => { const inputValue = document.querySelector(inputSelector).value if (inputValue.trim().length >= 1) { document.querySelector(buttonSelector).classList.add('enable') const keyCode = event.which || event.keyCode if (keyCode === 13 && event.shiftKey) { addTweetData(inputSelector, setTweetModalDisplay) } } else { document.querySelector(buttonSelector).classList.remove('enable') } } const displaySettingsPage = () => { document.querySelector('#settingsPage').style.display = 'block' document.querySelector('#currentSection').style.display = 'none' } export { inputEventHandler, addTweetData, changeTheme, changeTextColor, displaySettingsPage } <file_sep>export { default as CommentPage } from './CommentPage' <file_sep>export { default as ExplorePage } from "./ExplorePage" <file_sep>import { useState } from "react" import { Link, useHistory } from 'react-router-dom' import { CONSTANTS } from '../common/constants' import DisplayModal from './DisplayModal' import DropDownModal from './DropDownModal' import EditProfileModal from '../profilePage/EditProfileModal' import TweetModal from './TweetModal' import './leftNav.css' const LeftNav = ({ theme, setTheme, textColor, setTextColor, tweetData, setTweetData, setActivePage, bioData }) => { const [tweetModalDisplay, setTweetModalDisplay] = useState(false) const [dropDownDisplay, setDropDownDisplay] = useState(false) const [displayModal, setDisplayModal] = useState(false) const [editModalDisplay, setEditModal] = useState(false) const { location } = useHistory() const { pathname } = location const bio = bioData[0] return ( <div className="left-nav"> <div className="left-nav-content"> <span id="logo"><i className="fa">&#xf099;</i></span> <Link to="/" className="nav-button" id={pathname === '/' ? 'active' : ''} onClick={() => setActivePage('/')} > <i className="glyphicon glyphicon-home"></i> <span>Home</span> </Link> <Link to="/explore" className="nav-button" id={pathname === '/explore' ? 'active' : ''} onClick={() => setActivePage('/explore')} > <i className="fa fa-hashtag"></i> <span>Explore</span> </Link> <Link to="/notification" className="nav-button" id={pathname === '/notification' ? 'active' : ''} onClick={() => setActivePage('/notification')} > <i className="fa fa-bell-o"></i> <span>Notifications</span> </Link> <Link to="/messages" className="nav-button" id={pathname === '/messages' ? 'active' : ''} onClick={() => setActivePage('/messages')} > <i className="fa fa-envelope-o"></i> <span>Messages</span> </Link> <Link to="/bookmark" className="nav-button" id={pathname === '/bookmark' ? 'active' : ''} onClick={() => setActivePage('/bookmark')} > <i className="fa fa-bookmark-o"></i> <span>Bookmarks</span> </Link> <Link to="/list" className="nav-button" id={pathname === '/list' ? 'active' : ''} onClick={() => setActivePage('/list')} > <i className="fa fa-list-alt"></i> <span>Lists</span> </Link> <Link to="/profile" className="nav-button" id={pathname === '/profile' ? 'active' : ''} onClick={() => setActivePage('/profile')} > <i className="fa fa-user-o"></i> <span>Profile</span> </Link> <button type="button" className="nav-button" onClick={() => setDropDownDisplay(true)}> <i className="fa fa-caret-down"></i> <span>More</span> </button> <button className="tweet-modal-button" onClick={() => { bio ? setTweetModalDisplay(true) : setEditModal(true) }} > <i className="material-icons">&#xe0cb;</i> </button> <button type="button" id="tweetModalButton" onClick={() => { bio ? setTweetModalDisplay(true) : setEditModal(true) }} > Tweet </button> <div className="user-info"> <img src={bio?.profilePhoto || CONSTANTS.PHOTOURL} className="left-nav-photo" alt="user-profile" /> <span>{bio?.name || CONSTANTS.NAME}</span> </div> </div> { tweetModalDisplay && <TweetModal setTweetModalDisplay={setTweetModalDisplay} tweetData={tweetData} setTweetData={setTweetData} bio={bio} /> } { dropDownDisplay && <DropDownModal setDropDownDisplay={setDropDownDisplay} setDisplayModal={setDisplayModal} /> } { displayModal && <DisplayModal setDisplayModal={setDisplayModal} theme={theme} setTheme={setTheme} textColor={textColor} setTextColor={setTextColor} /> } { editModalDisplay && <EditProfileModal setEditModal={setEditModal} bio={bio} /> } </div> ) } export default LeftNav <file_sep>export { default as NotificationPage } from './NotificationPage' <file_sep>export { default as MessagePage } from './MessagePage'
b28a31e1ebdb84b36bb337b6522c2afe0e75d0e9
[ "JavaScript" ]
35
JavaScript
marveldev/twitter-react-app
96558aec88a455a3c8383eb7fd0ad838cae4b98d
22b6499ff37e93c94756c6c241b13d3100962f9a
refs/heads/master
<file_sep>Date.prototype.addDays = function(days) { var dat = new Date(this.valueOf()); dat.setDate(dat.getDate() + days); return dat; }; Date.prototype.addMinutes = function(minutes) { return new Date(this.getTime() + (minutes * 60000)); }; var MetronomeParser = function(now) { this.now = (typeof(now) === "string") ? new Date(now) : new Date(); this.parse = function(text) { var convertToDayOfWeek = function(dayAbbr) { switch (dayAbbr.trim().toUpperCase()) { case "SU": return 0; case "M": return 1; case "T": return 2; case "W": return 3; case "R": return 4; case "F": return 5; case "SA": return 6; default: throw "'" + dayAbbr + "' is not a recognized Day Of Week abbreviation"; } }; var formatMMDDYYYY = function(date) { return (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear(); }; var padWithLeadingZeros = function(num, size) { var s = num+""; while (s.length < size) s = "0" + s; return s; }; var m = null; // Time given as a range with an optional day identifier. Uses TODAY if date not given // Ex: 9-915 or M 900-1000 m = text.match(/^(SU|Su|su|SA|Sa|sa|[M|m|T|t|W|d|R|r|F|f]){0,1} ?([0-9]{1,4}[A|a|AM|am|P|p|PM|pm]{0,1})-([0-9]{1,4}[A|a|AM|am|P|p|PM|pm]{0,1})$/); if (m) { var dayOfWeek = m[1]; var startTime = this.getTimeComponents(m[2]); var endTime = this.getTimeComponents(m[3]); var targetDate = (dayOfWeek == null) ? this.now : this.now.addDays(convertToDayOfWeek(dayOfWeek) - this.now.getDay()); return new TimeEntry({ date: formatMMDDYYYY(targetDate), startHour: startTime.hour, startMin: startTime.minutes, endHour: endTime.hour, endMin: endTime.minutes }); } // Time given as a duration only. Use NOW as the ending time, then work backwards. // Ex: 90m or 1.5h m = text.match(/^([0-9]+(\.[0-9]+){0,1}) ?([m|M|h|H|hr|Hr|HR])$/); if (m) { var number = parseFloat(m[1]); var durationType = m[3]; var minutes = null; switch (durationType.toUpperCase()) { case "M": minutes = number; break; case "H": case "HR": minutes = number * 60; break; default: throw "Duration type '" + durationType + "' is not recognized"; } var endTime = this.now; var startTime = endTime.addMinutes(minutes * -1); return new TimeEntry({ date: formatMMDDYYYY(startTime), startHour: startTime.getHours(), startMin: padWithLeadingZeros(startTime.getMinutes(), 2), endHour: endTime.getHours(), endMin: padWithLeadingZeros(endTime.getMinutes(), 2) }); } throw "Could not parse: " + text; }; this.getTimeComponents = function(s) { var m = null; var isPM = function(s) { return (s != null) && (s.indexOf("p") >= 0 || s.indexOf("P") >= 0); }; // If we have a 1 or 2 digit number like "1" or "11", with optional am/pm designation, // assume it's the hour and minutes weren't specified if (m = s.match(/^([0-9]{1,2})(A|a|AM|am|P|p|PM|pm){0,1}$/)) { var isPM = isPM(m[2]); var hour = isPM ? parseInt(m[1]) + 12 : parseInt(m[1]); return { hour: hour.toString(), minutes: "00" }; } // If we have 3 or 4 digits then assume its a 1 or 2 digit hour and 2 digit minutes. // "105" makes more sense as 1:05 than 10:5. if (m = s.match(/^([0-9]{3,4})(A|a|AM|am|P|p|PM|pm){0,1}$/)) { var hour = (m[1].length == 3) ? m[1].substr(0, 1) : m[1].substr(0, 2); var minutes = (m[1].length == 3) ? m[1].substr(1) : m[1].substr(2); var isPM = isPM(m[2]); if (isPM) hour = parseInt(hour) + 12; return { hour: hour.toString(), minutes: minutes }; } throw "Could not parse time components from: " + s; } } var TimeEntry = function(hash) { this.date = hash.date || getDate(); this.startHour = hash.startHour; this.startMin = hash.startMin; this.endHour = hash.endHour; this.endMin = hash.endMin; this.description = hash.description; this.ticketNum = hash.ticketNum || ""; }
b50a967d724b3457425e9ff79a8437dec520892a
[ "JavaScript" ]
1
JavaScript
spetryjohnson/TimeEntry.js
4146795205685ebe01003d01f96612c0c0cd633e
212f77f05cee160a6556ffb1604d610d9a142b84
refs/heads/master
<file_sep>package com.example.bohdan.retr; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** Created by bohdan on 16.03.2018. */ public class TankOnline { @SerializedName("vehicle_armor_fedd") @Expose private Integer vehicleArmorFedd; @SerializedName("image") @Expose private String image; @SerializedName("max_health") @Expose private Integer maxHealth; @SerializedName("name") @Expose private String name; public Integer getVehicleArmorFedd() { return vehicleArmorFedd; } public void setVehicleArmorFedd(Integer vehicleArmorFedd) { this.vehicleArmorFedd = vehicleArmorFedd; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public Integer getMaxHealth() { return maxHealth; } public void setMaxHealth(Integer maxHealth) { this.maxHealth = maxHealth; } /*public String getName() { return name; } public void setName(String name) { this.name = name; }*/ }
c62a60471ace31ee964f3d228ccce464482267d5
[ "Java" ]
1
Java
BohdanLiush/retr
60198054e9117253bbd81fc10efa17fee8cbc6db
fd4e978f90cc70bcd5bab742e117546cb90f83e3
refs/heads/master
<repo_name>aftertheboop/pd-category-auto-emailer<file_sep>/README.md # pd-category-auto-emailer Wordpress plugin to automatically email a notification to an address upon publishing an article in a category. ## Installation Clone or copy the pd-category-auto-emailer folder into your /wp-content/plugins directory ## Usage Configure the plugin in "Auto Emailer". Use the following shortcodes to insert WP content into the HTML template: $$BLOGNAME$$ - will be substituted with the blog's name $$PERMALINK$$ - will be substituted with a link to the article $$POSTTITLE$$ - will be substituted with the blog post title <file_sep>/pd-admin-options.php <?php /** * PD Category Auto Emailer Admin Class * * Handles all interactions with the admin section of the plugin */ class PD_Category_Auto_Emailer_Admin { public function __construct() { } /** * Init Menu Item * * Assigns the menu item */ public function init_menu_item() { add_menu_page( 'Category Auto Emailer Settings', 'Auto-Emailer', 'manage_options', 'pd_category_auto_emailer_plugin', array($this, 'pd_auto_emailer_admin_init') ); } /** * PD Auto Emailer Admin Init * * Checks permissions and renders the admin section */ public function pd_auto_emailer_admin_init() { if ( !current_user_can( 'manage_options' ) ) { wp_die( __( 'You do not have sufficient permissions to access this page.' ) ); } // Save options if(isset($_POST['option_page'])) { $this->admin_save_options(); } // Display form $this->admin_menu_html(); } /** * Admin Save Options * * Saves the POSTed options */ private function admin_save_options() { $this->set_pd_from_name(); $this->set_pd_from_email(); $this->set_pd_bcc(); $this->set_pd_body_content(); } /** * Set PD From Name * * Sets the FROMn NAME field * @return void */ private function set_pd_from_name() { $option_name = 'pd_from_name' ; $new_value = filter_input(INPUT_POST, 'pd-auto-from-name', FILTER_SANITIZE_STRING) ; if ( get_option( $option_name ) !== false ) { // The option already exists, so we just update it. update_option( $option_name, $new_value ); } else { // The option hasn't been added yet. We'll add it with $autoload set to 'no'. $deprecated = null; $autoload = 'no'; add_option( $option_name, $new_value, $deprecated, $autoload ); } } /** * Set PD From Email * * Sets the FROM EMAIL field * @return void */ private function set_pd_from_email() { $option_name = 'pd_from_email' ; $new_value = filter_input(INPUT_POST, 'pd-auto-from', FILTER_SANITIZE_STRING) ; if ( get_option( $option_name ) !== false ) { update_option( $option_name, $new_value ); } else { $deprecated = null; $autoload = 'no'; add_option( $option_name, $new_value, $deprecated, $autoload ); } } /** * Set PD Bcc * * Sets the email addresses to BCC * @return void */ private function set_pd_bcc() { $option_name = 'pd_bcc' ; $new_value = filter_input(INPUT_POST, 'pd-auto-bcc', FILTER_SANITIZE_STRING) ; if ( get_option( $option_name ) !== false ) { update_option( $option_name, $new_value ); } else { $deprecated = null; $autoload = 'no'; add_option( $option_name, $new_value, $deprecated, $autoload ); } } /** * Set PD Body Content * * Sets the HTML body content for the emailer * @return void */ private function set_pd_body_content() { $option_name = 'pd_body_content' ; $new_value = filter_input(INPUT_POST, 'pd-auto-body') ; if ( get_option( $option_name ) !== false ) { update_option( $option_name, $new_value ); } else { $deprecated = null; $autoload = 'no'; add_option( $option_name, $new_value, $deprecated, $autoload ); } } /** * Admin Menu HTML * * Renders the admin HTML form * @return void */ private function admin_menu_html() { $html = '<div class="wrap">'; $html .= '<h1>Category Auto Emailer Settings</h1>'; $html .= '<p class="description">Configure settings for your category auto-emailer. These settings are universal across all categories.</p>'; $html .= '<form id="pd-auto-emailer" method="post">'; echo $html; settings_fields( 'pd-auto-emailer-settings' ); do_settings_sections( 'pd-auto-emailer-settings' ); /*$html .= '<input type="hidden" name="option_page" value="general">'; $html .= '<input type="hidden" name="action" value="update">'; $html .= wp_nonce_field('pd-category-auto-emailer-save_options', '_wpnonce', true, false);*/ $html = '<table class="form-table">'; $html .= '<tr>'; $html .= '<th><label for="pd-auto-from-name">From Name</label></th>'; $html .= '<td><input name="pd-auto-from-name" type="text" id="pd-auto-from-name" class="regular-text" value="' . $this->get_pd_from_name() . '" /><p class="description">The displayed From Name on the notifications</p></td>'; $html .= '</tr>'; $html .= '<tr>'; $html .= '<th><label for="pd-auto-from">From Address</label></th>'; $html .= '<td><input name="pd-auto-from" type="email" id="pd-auto-from" class="regular-text" value="' . $this->get_pd_email() . '" /><p class="description">The displayed From and Reply-To email address on the notification</p></td>'; $html .= '</tr>'; $html .= '<tr>'; $html .= '<th><label for="pd-auto-bcc">Bcc Address(es):</label></th>'; $html .= '<td><input name="pd-auto-bcc" type="text" id="pd-auto-bcc" class="regular-text" value="' . $this->get_pd_bcc() . '" /><p class="description">Comma-separated list of any additional addresses you would like to add to any notification</p></td>'; $html .= '</tr>'; $html .= '<tr>'; $html .= '<th><label for="pd-auto-body">HTML Emailer Body</label></th>'; $html .= '<td>'; $html .= $this->body_content_field(); //$html .= '<textarea name="pd-auto-body" id="pd-auto-body" class="regular-text" style="width: 100%" rows="20"></textarea>'; $html .= '<p class="description">The following aliases will be substituted with content:<br/>$$BLOGNAME$$, $$PERMALINK$$, $$POSTTITLE$$<br/>Use them to substitute dynamic content in your email</p>'; $html .= '</td>'; $html .= '</tr>'; $html .= '<tr>'; $html .= '<td></td><td>' . get_submit_button('Save Options', 'primary large', 'pd_save_options') . '</td>'; $html .= '</tr>'; $html .= '</table>'; $html .= '</form>'; $html .= '</div>'; echo $html; } /** * Get PD From Name * * Gets the FROM NAME for the email * @return String */ public function get_pd_from_name() { $from_name = get_option('pd_from_name', get_bloginfo('name')); return $from_name; } /** * Get PD Email * * Gets the FROM EMAIL for the mail * @return String */ public function get_pd_email() { $from_email = get_option('pd_from_email', get_option('admin_email')); return $from_email; } /** * Get PD Bcc * * Gets the BCC field for the headers. Blank if nothing * @return String */ public function get_pd_bcc() { $bcc_emails = get_option('pd_bcc', ''); return $bcc_emails; } /** * Get PD Body Content * * Gets the emailer body copy * @return String */ public function get_pd_body_content() { $body_content = get_option('pd_body_content', $this->default_body_content()); return $body_content; } /** * Default Body Content * * Gets a default string of body copy in the event that nothing is assigned * @return String */ private function default_body_content() { $html = 'Hi there, A new article relevant to you has been posted on $$BLOGNAME$$. Click the link to read: <b><a href="$$PERMALINK$$" title="$$POSTTITLE$$">$$POSTTITLE$$</a></b> <b>We welcome daily news for placement</b> and we invite you to send us any events as they happen. Kind regards, The <b>$$BLOGNAME$$</b> Team'; return $html; } /** * Body Content Field * * Generates the WYSIWYG interface for adding the HTML content for the email * @return String */ private function body_content_field() { ob_start(); wp_editor($this->get_pd_body_content(), 'pd-auto-body', array( 'wpautop' => false, 'textarea_name' => 'pd-auto-body', 'media_buttons' => false )); $ret = ob_get_contents(); ob_end_clean(); return $ret; } }<file_sep>/pd-category-auto-emailer.php <?php /** * @package PD Category Auto Emailer */ /* Plugin Name: PD Category Auto Emailer Description: Sends an automated email to an email address set per category upon publishing a post for the first time Version: 1.1 Author: <NAME> Author URI: http://pitchdark.co.za License: Private Text Domain: pd-category-auto-emailer */ // Include Admin class include_once('pd-admin-options.php'); // Admin integration add_action('admin_menu', 'pd_category_auto_emailer_admin'); // Run main plugin activity on post status change add_action( 'transition_post_status', 'pd_category_auto_emailer_init', 10, 3 ); /** * PD Category Auto Emailer Admin * * Init the Admin section * @return void */ function pd_category_auto_emailer_admin() { // Create class $pd_category_auto_emailer_admin = new PD_Category_Auto_Emailer_Admin(); // Init $pd_category_auto_emailer_admin->init_menu_item(); } /** * PD Category Auto Emailer Init * * Run the main automation for the plugin * * @param String $new_status * @param String $old_status * @param WP Post Object $post * @return WP_Error|boolean */ function pd_category_auto_emailer_init($new_status, $old_status, $post) { // New class instances $Auto_admin = new PD_Category_Auto_Emailer_Admin(); $Auto_emailer = new PD_Category_Auto_Emailer($post->ID, $post, $Auto_admin); $Auto_emailer->_log('Prepare auto mailer'); // Log the beginning of the action $Auto_emailer->_log($old_status . ' ' . $new_status . ' ' . json_encode($post)); // Log status change // Only continue if the status changes to publish if ( ( $old_status === 'draft' || $old_status === 'auto-draft' || $old_status === 'pending' ) && $new_status === 'publish' ) { // Emailer can be sent if($Auto_emailer->can_send()) { $Auto_emailer->_log('Can Send'); // Prepare the emailer if($Auto_emailer->pre_email()) { // Check that there are email addresses available if(empty($Auto_emailer->get_emails()) || strlen($Auto_emailer->get_emails(true)) == 0) { $Auto_emailer->_log('Cannot send email. No addresses'); return false; } else { // Send email $sent = wp_mail($Auto_admin->get_pd_email(), '[' . get_bloginfo('name') . '] New Article', $Auto_emailer->get_message(), $Auto_emailer->get_headers()); // Send debug logging $Auto_emailer->_log(json_encode($sent)); $Auto_emailer->_log($Auto_emailer->get_message()); $Auto_emailer->_log('Email Sent!'); } } } else { // Automation failed for whatever reason. Throw a WP Error $Auto_emailer->_log('Failed'); return new WP_Error('pd_auto_emailer_failed', __( 'Article Auto-emailer could not be sent', 'pd-category-auto-emailer')); } } } /** * PD Category Auto Emailer * * Emails a comma-separated list of recipients when an article is published to a * specific category */ class PD_Category_Auto_Emailer { /** * Constructor * * @param Int $post_ID * @param WP Post Object $post * @param PD_Category_Auto_Emailer_Admin $admin */ public function __construct($post_ID, $post, $admin) { // Assign variables $this->post_id = $post_ID; $this->post = $post; $this->admin = $admin; $this->emails = array(); $this->template = ''; // debugging / logging $this->debug = true; } /** * Log * * Custom logging function to output to a local activity log * @param String $message * @return boolean */ public function _log($message) { // Only log if debug is set to false if($this->debug == false) { return false; } $log = fopen(plugin_dir_path( __FILE__ ) . 'errorlog.txt', "a") or die('Could not open log file'); fwrite($log, '[' . date('Y-m-d H:i:s') . '] - ' . $message . "\r\n"); fclose($log); } /** * Get Headers * * Returns properly formatted email headers for content and Bcc * @return string */ public function get_headers() { $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; $headers .= "Bcc: " . $this->get_emails(true) . ',' . $this->admin->get_pd_bcc(); return $headers; } /** * Get Message * * Returns the message body * @return string */ public function get_message() { return $this->template; } /** * Get Emails * * Returns a list of all email addresses to send to * @param bool $string * @return array|string */ public function get_emails($string = false) { if(!$string) { return $this->emails; } else { return implode(', ', $this->emails); } } /** * Can Send * * Checks whether the plugin can proceeed to process and send the notification * @return boolean */ public function can_send() { $sent_status = $this->_get_sent_status(); $post_status = $this->post->post_status; // Email must be unsent and post must be published if($sent_status == 0 && $post_status == 'publish') { $this->_log('Can send email'); return true; } else { $this->_log('Cannot send email: Sent Status: ' . $sent_status . ' Post Status: ' . $post_status); return false; } } /** * Pre Email * * Prepares the content, addresses, sent flag and authority to send the auto * email * @return boolean */ public function pre_email() { // Get all addresses to end to try { $this->emails = $this->_get_category_email_addresses(); // Set email template $this->template = $this->_prepare_template(); $this->_log('Emails: ' . json_encode($this->emails)); $this->_log('Template fetched'); return true; } catch (Exception $e) { return false; } } /** * Get Sent Status * * Gets the value of the email sent flag * @return int */ private function _get_sent_status() { $status = get_post_meta($this->post_id, 'pd_cat_email_sent', true); if(strlen($status) > 0) { return $status; } else { return 0; } } /** * Prepare Template * * Prepares the Email template by substituting the relevant information on * the document. * @return String */ private function _prepare_template() { // HTML is hard baked into the plugin due to server shenanigans $html = $this->get_html(); // Replace blog name $html = str_replace('$$BLOGNAME$$', get_bloginfo('name'), $html); // Replace article permalink $html = str_replace('$$PERMALINK$$', get_the_permalink($this->post_id), $html); // Replace article title $html = str_replace('$$POSTTITLE$$', get_the_title($this->post_id), $html); return $html; } /** * Get Category Email Addresses * * Get the contents of all `pd_cat_email` fields of the article's associated * categories. Returns an array of field values. * @return Array */ private function _get_category_email_addresses() { $categories = wp_get_post_categories($this->post_id); $emails = array(); foreach($categories as $category) { // Get the contents of the pd_cat_email meta field $pd_cat_email = get_term_meta($category, 'pd_cat_email', true); // Only add the content if it has a non-zero length. // Validation is handled on the initial category POST if(strlen($pd_cat_email) > 0) { $emails_arr = explode(",", $pd_cat_email); // Merge everything together $emails = array_merge($emails, $emails_arr); } } return $emails; } private function get_html() { return '<!doctype html> <html> <head> <meta name="viewport" content="width=device-width"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>New Notification From $$BLOGNAME$$</title> <style> /* ------------------------------------- INLINED WITH htmlemail.io/inline ------------------------------------- */ /* ------------------------------------- RESPONSIVE AND MOBILE FRIENDLY STYLES ------------------------------------- */ @media only screen and (max-width: 620px) { table[class=body] h1 { font-size: 28px !important; margin-bottom: 10px !important; } table[class=body] p, table[class=body] ul, table[class=body] ol, table[class=body] td, table[class=body] span, table[class=body] a { font-size: 16px !important; } table[class=body] .wrapper, table[class=body] .article { padding: 10px !important; } table[class=body] .content { padding: 0 !important; } table[class=body] .container { padding: 0 !important; width: 100% !important; } table[class=body] .main { border-left-width: 0 !important; border-radius: 0 !important; border-right-width: 0 !important; } table[class=body] .btn table { width: 100% !important; } table[class=body] .btn a { width: 100% !important; } table[class=body] .img-responsive { height: auto !important; max-width: 100% !important; width: auto !important; } } /* ------------------------------------- PRESERVE THESE STYLES IN THE HEAD ------------------------------------- */ @media all { .ExternalClass { width: 100%; } .ExternalClass, .ExternalClass p, .ExternalClass span, .ExternalClass font, .ExternalClass td, .ExternalClass div { line-height: 100%; } .apple-link a { color: inherit !important; font-family: inherit !important; font-size: inherit !important; font-weight: inherit !important; line-height: inherit !important; text-decoration: none !important; } .btn-primary table td:hover { background-color: #34495e !important; } .btn-primary a:hover { background-color: #34495e !important; border-color: #34495e !important; } } </style> </head> <body class="" style="background-color: #f6f6f6; font-family: sans-serif; -webkit-font-smoothing: antialiased; font-size: 14px; line-height: 1.4; margin: 0; padding: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;"> <table border="0" cellpadding="0" cellspacing="0" class="body" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; background-color: #f6f6f6;"> <tr> <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">&nbsp;</td> <td class="container" style="font-family: sans-serif; font-size: 14px; vertical-align: top; display: block; Margin: 0 auto; max-width: 580px; padding: 10px; width: 580px;"> <div class="content" style="box-sizing: border-box; display: block; Margin: 0 auto; max-width: 580px; padding: 10px;"> <!-- START CENTERED WHITE CONTAINER --> <span class="preheader" style="color: transparent; display: none; height: 0; max-height: 0; max-width: 0; opacity: 0; overflow: hidden; mso-hide: all; visibility: hidden; width: 0;">New Notification from $$BLOGNAME$$</span> <table class="main" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; background: #ffffff; border-radius: 3px;"> <!-- START MAIN CONTENT AREA --> <tr> <td class="wrapper" style="font-family: sans-serif; font-size: 14px; vertical-align: top; box-sizing: border-box; padding: 20px;"> <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;"> <tr> <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;"> '. $this->format_message() .' </td> </tr> </table> </td> </tr> <!-- END MAIN CONTENT AREA --> </table> <!-- START FOOTER --> <div class="footer" style="clear: both; Margin-top: 10px; text-align: center; width: 100%;"> <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;"> <tr> <td class="content-block" style="font-family: sans-serif; vertical-align: top; padding-bottom: 10px; padding-top: 10px; font-size: 12px; color: #999999; text-align: center;"> <span class="apple-link" style="color: #999999; font-size: 12px; text-align: center;">This email was automatically generated by $$BLOGNAME$$ on ' . date('j F Y H:i') . '</span> <br>Please reply to this email if you no longer wish to receive these notifications. </td> </tr> </table> </div> <!-- END FOOTER --> <!-- END CENTERED WHITE CONTAINER --> </div> </td> <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">&nbsp;</td> </tr> </table> </body> </html>'; } /** * Format Message * * Gets the user generated HTML and formats it for the mailer * @return String */ private function format_message() { $body = $this->admin->get_pd_body_content(); $body_arr = explode("\n", $body); foreach($body_arr as $k => $b) { if(strlen($b) > 1) { $body_arr[$k] = '<p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">' . $b . '</p>'; } else { $body_arr[$k] = '<p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">&nbsp;</p>'; } } return implode("\n", $body_arr); } } /* Category Auto-Email Fields ----------------------------------------------- */ add_action('category_add_form_fields', 'pd_taxonomy_add_new_meta_field', 10, 1); add_action('category_edit_form_fields', 'pd_taxonomy_edit_meta_field', 10, 1); /** * PD Taxonomy Add New Meta Field * * Renders meta fields on the category overview page */ function pd_taxonomy_add_new_meta_field() { ?> <div class="form-field"> <label for="pd_cat_email"><?php _e('Category Auto Email', 'pd'); ?></label> <input type="text" name="pd_cat_email" id="pd_cat_email"> <p class="description"><?php _e('Enter the email address of a person to receive an email every time a post is made to this category. You can enter multiple addresses separated by a comma', 'pd'); ?></p> </div> <?php } /** * PD Taxonomy Edit Meta Field * * Renders meta field on the Edit Category page * @param WP Term Object $term */ function pd_taxonomy_edit_meta_field($term) { //getting term ID $term_id = $term->term_id; // retrieve the existing value(s) for this meta field. $pd_cat_email = get_term_meta($term_id, 'pd_cat_email', true); ?> <tr class="form-field"> <th scope="row" valign="top"><label for="pd_cat_email"><?php _e('Category Auto Email', 'pd'); ?></label></th> <td> <input type="text" name="pd_cat_email" id="pd_cat_email" value="<?php echo esc_attr($pd_cat_email) ? esc_attr($pd_cat_email) : ''; ?>"> <p class="description"><?php _e('Enter the email address of a person to receive an email every time a post is made to this category. You can enter multiple addresses separated by a comma', 'pd'); ?></p> </td> </tr> <?php } add_action('edited_category', 'pd_save_taxonomy_custom_meta', 10, 1); add_action('create_category', 'pd_save_taxonomy_custom_meta', 10, 1); /** * PD Save Taxonomy Customer Meta * * Saves the field to the term meta tables * @param Int $term_id */ function pd_save_taxonomy_custom_meta($term_id) { $pd_cat_email = filter_input(INPUT_POST, 'pd_cat_email'); update_term_meta($term_id, 'pd_cat_email', $pd_cat_email); } /* End Custom Category Field ------------------------------------------------ */
941808799c5875749289867aa51dcf5a782ffc93
[ "Markdown", "PHP" ]
3
Markdown
aftertheboop/pd-category-auto-emailer
8bc9feb43678751d38e672d7adf51a5fd4d8d6ca
bf822f4d4b333757f33eebda69b19ee08c696e3c
refs/heads/master
<file_sep>/** * User Bin Crash You are on a cargo plane full of commercial goods when the * pilot announces that the plane is short on fuel. Unless cargo is ejected from * the plane, you will run out of fuel and crash. The pilot provides you with * the number of pounds of weight that must be ejected from the plane. * Fortunately, the manifest of the plane is both completely accurate, * digitized, and you are a programmer of some repute. Unfortunately, your boss * is going to be extremely unhappy, and wants you to exactly minimize the * losses to the absolute minimum possible without crashing the plane. The * manifest does not contain the exact quantities of every type of good, because * you have so many on board. You may assume that you will not run out of any * good in the course of saving the plane. You also realize this kind of program * could be handy to others who find themselves in similar situations. * * Write a program that takes a single argument on the command line. This * argument must be a file name, which contains the input data. The program * should output to standard out the minimum losses your boss will incur from * your ejection of goods (see below). Your program will be tested against * several manifests of several crashing planes; each with different data. * * Additionally, your program must be fast, and give the correct answer. * * Input specifications The input file will start with an integer number * indicating the minimum number of pounds of weight that must be ejected from * the plane to prevent a crash, followed by a new line. Each additional line in * the file represents a commercial SKU (stock keeping unit) along with its cost * (in dollars) and weight (in pounds). The format of these lines is: <SKU * label> <weight in pounds> <cost in dollars> SKUs are represented as a * combination of letters (upper and lower case) and numbers. Both costs and * weights are integers. Each piece of data in a line is separated by white * space. Lines are separated by a single new line character. You are guaranteed * your program will run against well formed input files. * * Example input file: * 1250 * LJS93K 1300 10500 * J38ZZ9 700 4750 * HJ394L 200 3250 * O1IE82 75 10250 * * Output specifications Your boss is not interested in exactly what you ejected * to save the plane, he/she is currently only interested in how much it will * cost the company. Your program must find the set of goods that will prevent * the plane from crashing, and minimize company losses. It should print out the * total value of goods lost as a plain integer, followed by a newline. Do not * insert commas or dollar signs. * * Example output (newline after integer): * 9500 * **/<file_sep>package com.points.backpack; import java.util.List; public class CargoCalculator { private CargoCombo cargoCandidate; private Manifest manifest; private List<Cargo> cargoAboardPlane; private CargoCombo currentCombo; private CargoCalculator() {} public CargoCalculator(Manifest manifest) { this.manifest = manifest; } public CargoCombo calculateCargoToDrop() { if (manifest == null ) { return null; } cargoAboardPlane = manifest.getCargoAboardPlane(); if (cargoAboardPlane == null || cargoAboardPlane.size() < 1 ) { return null; } currentCombo = new CargoCombo(cargoAboardPlane.get(0)); return recursiveCalcuate(); } private CargoCombo recursiveCalcuate() { if (currentCombo.getCargo().isEmpty() ) { return cargoCandidate; } if (cargoCandidate != null && currentCombo.getTotalCost() > cargoCandidate.getTotalCost() ) { popAndAddNext(true); recursiveCalcuate(); } if (currentCombo.getTotalWeight() > manifest.getWeightToLose() ) { if (cargoCandidate == null ) { cargoCandidate = new CargoCombo(currentCombo.getCargo()); } if (currentCombo.getTotalCost() < cargoCandidate.getTotalCost() ) { cargoCandidate = new CargoCombo(currentCombo.getCargo()); } popAndAddNext(true); recursiveCalcuate(); } popAndAddNext(false); recursiveCalcuate(); return cargoCandidate; } private void popAndAddNext(boolean doPop) { if (currentCombo == null || currentCombo.getCargo() == null || currentCombo.getCargo().isEmpty() ) { return; } int nextCargoIndex; if (doPop ) { Cargo lastItem = currentCombo.removeLastCargoItem(); nextCargoIndex = cargoAboardPlane.indexOf(lastItem) + 1; } else { List<Cargo> cargoList = currentCombo.getCargo(); Cargo lastItem = cargoList.get(cargoList.size() - 1); nextCargoIndex = cargoAboardPlane.indexOf(lastItem); } if (nextCargoIndex < cargoAboardPlane.size() ) { currentCombo.addToCargoCombo(cargoAboardPlane.get(nextCargoIndex)); } else { popAndAddNext(true); } } public static void main(String[] args) { if (args.length < 1 || args.length > 1 ) { System.out.println("Invalid number of arguments provided. Please provide the manifest file location"); System.exit(1); } Manifest manifest = Manifest.readManifestFile(args[0]); if (manifest == null ) { System.out.println("Invalid manifest"); System.exit(1); } CargoCalculator calculator = new CargoCalculator(manifest); CargoCombo answer = calculator.calculateCargoToDrop(); if (answer == null ) { System.out.println("Answer could not be calculated"); System.exit(1); } int cost = answer.getTotalCost(); System.out.printf("%d\n",cost); System.exit(0); } } <file_sep>package com.points.backpack; public class Cargo { private String sku; private int weight; private int cost; private Cargo() {} public Cargo(String sku, int weight, int cost ) { this.sku = sku; this.weight = weight; this.cost = cost; if (sku == null || sku.isEmpty() ) { this.sku = "CARGO"; } if (weight <= 0 ) { this.weight = 1; } if (cost <= 0 ) { this.cost = 1; } } public String getSku() { return sku; } public int getWeight() { return weight; } public int getCost() { return cost; } @Override public boolean equals(Object obj) { if (obj == null ) { return false; } if (getClass() != obj.getClass()) { return false; } final Cargo c = (Cargo)obj; if (sku == c.sku && weight == c.weight && cost == c.cost ) { return true; } return false; } } <file_sep>package com.points.backpack; import java.util.ArrayList; import java.util.List; public class CargoCombo { private List<Cargo> cargoList; private int totalWeight; private int totalCost; private CargoCombo() {} public CargoCombo(Cargo cargo) { this.cargoList = new ArrayList<>(); if (cargo != null ) { cargoList.add(cargo); updateTotalWeightAndCost(); } } public CargoCombo(List<Cargo> cargoList) { this.cargoList = cargoList; if (cargoList == null ) { this.cargoList = new ArrayList<>(); } updateTotalWeightAndCost(); } public boolean addToCargoCombo(Cargo cargo) { if (cargo == null ) { return false; } cargoList.add(cargo); totalWeight += cargo.getWeight(); totalCost += cargo.getCost(); return true; } public Cargo removeLastCargoItem() { if (cargoList == null || cargoList.isEmpty() ) { return null; } Cargo item = cargoList.remove(cargoList.size() - 1); totalWeight -= item.getWeight(); totalCost -= item.getCost(); return item; } private void updateTotalWeightAndCost() { totalWeight = cargoList.stream().mapToInt(c -> c.getWeight()).sum(); totalCost = cargoList.stream().mapToInt(c -> c.getCost()).sum(); } public int getTotalWeight() { return totalWeight; } public int getTotalCost() { return totalCost; } public List getCargo() { return cargoList; } }
034559848d236d7e0a6c54729a8aca9a1873266e
[ "Java", "Text" ]
4
Text
ahuer/backpack
eeab927148955618b01cd5881f1632156b1e8650
1d50e43bf06b06bcc3822651404de6fe317ecf2e
refs/heads/master
<repo_name>kasbarov/MWA_Lab2<file_sep>/2_findInTree.js const find = fileName => tree => { // search in files for (treeFileName of tree.files){ if (fileName === treeFileName){ // file found return true; } } // file not found in current foler, search in subfolders recursively for (subfolder of tree.subFolders){ let fileFound = find (fileName) (subfolder); // if file found return true, otherwise continue searching if (fileFound) return true; } // if all subfolder searched and file not found return false return false; }; const tree = { name : "home", files : ["notes.txt","todo.txt"], subFolders: [ { name : "payroll", files : ["paper.pdf","funds.csv"], subFolders: [] }, { name: "misc", files : ["summer1.jpg","summer2.jpg", "summer3.jpg"], subFolders: [ { name : "logs", files : ["logs1","logs2","logs3","logs4"], subFolders: [] }] }] }; console.log(find("paper.pdf")(tree)); console.log(find("randomfile")(tree)); <file_sep>/1_WrittenExercise.md 1- the conoclusion is setIntermediate sometimes is faster than setTimeout, since setIntermediate is registered on the check phase which run immediately after I/O callbacks; however, setTimeOut is registered in the timer quesue and hence it 'does not gurantee' to execute immediately. 2- Use setImmediate if you want to queue the function behind whatever I/O event callbacks that are already in the event queue. Use process.nextTick to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes. 3- built-in Node Modules: - fs To handle the file system - http To make Node.js act as an HTTP server - https To make Node.js act as an HTTPS server. - os Provides information about the operation system - timers To execute a function after a given number of milliseconds - v8 To access information about V8 (the JavaScript engine) - crypto To handle OpenSSL cryptographic functions - events To handle events - net To create servers and clients - querystring To handle URL query strings
c93ecec97c4e794ad04f723f719a0f76f80bfba0
[ "JavaScript", "Markdown" ]
2
JavaScript
kasbarov/MWA_Lab2
ffa704d25094c9bc84ef0a3a3531c96d2534fd49
56fc0f5cb8e2c57e9c34d468b4fdeacd78913ae9