Java float类型的1.000 如何转换为 int类型的 1 求教

Java float类型的1.000 如何转换为 int类型的 1 求教

6个回答

最简单的方法,强制类型转换呀
int i = (int) 1.000;
然后就是int类型了。

package test2;

public class aaa {

public static void main(String[] args) {
    int a;
    a=(int)1.000;
    System.out.println(a);
}

}
这是一个简单的示例

int a = (int)1.000f;//a is 1

public class INT {

public static void main(String[] args) {
    float a =1;
    System.out.println(a);
    int b=(int)a;
    System.out.println(b);
}

}

我是来学习的。

强制转型就行了(int)

直接实现强制类型转换就可以了,float = 1.23f ;int b = (int)f;
float转为int时,直接舍弃float的小数,取整数部分

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
java.sql.SQLException问题

代码: public static void main(String[] args) { // TODO Auto-generated method stub //定义需要的对象 PreparedStatement ps=null; Connection ct=null; ResultSet rs=null; try { //初始化我们的对象 //1.加载驱动 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //2.得到链接 ct=DriverManager.getConnection("jdbc:microsoft:sqlserver://192.168.102:1433;databaseName=test"); //3.创建火箭车 ps=ct.prepareStatement("select * from emp"); //执行(如果是增加,删除,修改 ,executUpdate()。如果是查询 executeQuery()) rs=ps.executeQuery(); //循环的取出(名字,薪水,部门号) while(rs.next()){ String name=rs.getString(2); float sal=rs.getFloat(6); int deptNo=rs.getInt(8); System.out.println(name+" "+sal+" "+deptNo); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } 异常: java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=test at java.sql.DriverManager.getConnection(DriverManager.java:602) at java.sql.DriverManager.getConnection(DriverManager.java:185) at com.test2.Test3.main(Test3.java:29) Win7 64位操作系统,sql server2012

spring2.5.6 配置 openJpa 异常

最近在做一个小列子,原本是用配置文件方式注入的,之后我想改为用注解的方式注入,问题就出现了。 错误代码如下: [code="java"]2010-2-4 22:18:04 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet default threw exception java.lang.IllegalArgumentException: entityManagerFactory or jpaTemplate is required at org.springframework.orm.jpa.support.JpaDaoSupport.checkDaoConfig(JpaDaoSupport.java:119) at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:671) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:610) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:499) at org.springframework.beans.factory.annotation.InjectionMetadata.injectMethods(InjectionMetadata.java:117) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:253) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:998) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:671) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:610) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1076) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:982) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:329) at com.opensymphony.xwork2.spring.SpringObjectFactory.autoWireBean(SpringObjectFactory.java:168) at com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:155) at com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:129) at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:143) at com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:113) at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:275) at com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:365) at com.opensymphony.xwork2.DefaultActionInvocation.access$000(DefaultActionInvocation.java:38) at com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:83) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.<init>(DefaultActionInvocation.java:74) at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:189) at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:41)[code="java"][/code] at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:494) at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619)[/code] java代码如下: [code="java"] @Repository public class ExamDAOImpl extends JpaDaoSupport implements ExamDAO{ private String hql = "from Exam a "; //新增试卷 public void create(Exam exam) { this.getJpaTemplate().persist(exam); } //修改试卷 public void update(Exam exam) { this.getJpaTemplate().merge(exam); } //删除试卷 public void delete(Exam exam) { this.getJpaTemplate().remove(this.getJpaTemplate().merge(exam)); } //根据id获取试卷信息 public Exam query(int id) { Exam exam = this.getJpaTemplate().find(Exam.class, id); return exam; } //获取所有试卷的信息 @SuppressWarnings("unchecked") public List<Exam> queryList() { List<Exam> list = new ArrayList<Exam>(); list = this.getJpaTemplate().find(hql); return list; } } @Namespace("/") @Results({@Result("jsp/examManagement.jsp"), @Result(name="createQuestion", value = "jsp/questionManagement.jsp"), @Result(name="exam", value = "jsp/exam.jsp"), @Result(name="examResult", value = "jsp/examResult.jsp")}) public class ExamAction extends ActionSupport { private static final long serialVersionUID = 5192939935859483841L; //新增试卷信息 public String create() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); //进行新增 getExamService().create(exam); //获取已有的试卷信息 List<Exam> listExams = getExamService().queryList(); //将已有的试卷信息传递给页面 req.setAttribute("listExams", listExams); //存放消息 req.setAttribute("msg", "新增成功"); return SUCCESS; } //修改试卷信息 public String update() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); //进行修改 getExamService().update(exam); //获取已有的试卷信息 List<Exam> listExams = getExamService().queryList(); //将已有的试卷信息传递给页面 req.setAttribute("listExams", listExams); //存放消息 req.setAttribute("msg", "修改成功"); return SUCCESS; } //删除试卷信息 public String delete() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); //进行删除 getExamService().delete(exam); //获取已有的试卷信息 List<Exam> listExams = getExamService().queryList(); //将已有的试卷信息传递给页面 req.setAttribute("listExams", listExams); //存放消息 req.setAttribute("msg", "删除成功"); return SUCCESS; } //设定该试卷下的题目 public String createQuestion() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); exam = getExamService().query(exam.getId()); //获取该试卷题目下已有的题目 Set<Question> listQuestions = exam.getQuestion(); //将该试卷题目下已有的题目信息传递给页面 req.setAttribute("listQuestions", listQuestions); //将该试卷信息传递给页面 req.setAttribute("exam", exam); //存放消息 req.setAttribute("msg", "欢迎进入" + exam.getName() + "试题题目管理系统"); return "createQuestion"; } //进行考试 public String exam() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); exam = getExamService().query(exam.getId()); //将该试卷信息传递给页面 req.setAttribute("exam", exam); //存放消息 req.setAttribute("msg", "欢迎您开始《" + exam.getName() + "》试卷"); return "exam"; } //统计试卷成绩 public String submitExam() { HttpServletRequest req = ServletActionContext.getRequest(); //获取试卷信息 Exam exam = new Exam(); exam = getExamService().query(Integer.valueOf(req.getParameter("examId"))); //定义该此考试的分数 float result = 0f; //获取该试卷下的题目 Set<Question> listQuestions = exam.getQuestion(); Iterator<Question> iterator = listQuestions.iterator(); //获取每个题目下的项目 while (iterator != null && iterator.hasNext()) { Question question = (Question)iterator.next(); //获取该题目下的项目 List<QuestionItem> listQuestionItems = question.getQuestionItem(); //获取用户选择的题目下的项目 Assert.notNull((String)req.getParameter(question.getId() + "")); int questionId = Integer.valueOf((String)req.getParameter(question.getId() + "")); //累计用户提交的题目下的项目 for (int j = 0; listQuestionItems != null && j < listQuestionItems.size(); j++) { QuestionItem questionItem = (QuestionItem)listQuestionItems.get(j); if(questionId == questionItem.getId()) { if (questionItem.getIsOk() == 1) { //统计成绩 result = result + question.getPoint(); break; } } } } //将该试卷信息传递给页面 req.setAttribute("exam", exam); //将成绩传递给页面 req.setAttribute("result", result); //存放消息 req.setAttribute("msg", "欢迎您查看《" + exam.getName() + "》试卷的成绩"); return "examResult"; } public String index() { HttpServletRequest req = ServletActionContext.getRequest(); //获取已有的试卷信息 List<Exam> listExams = getExamService().queryList(); //将已有的试卷信息传递给页面 //System.out.println("listExams.size==="+listExams.size()); req.setAttribute("listExams", listExams); req.setAttribute("msg", "欢迎进入试卷题目管理系统"); return SUCCESS; } //获取试卷业务逻辑 public ExamService getExamService(){ return examService; } //设定试卷业务逻辑 @Autowired public void setExamService(ExamService examService){ this.examService = examService; } private ExamService examService; //获取试题项目业务逻辑 public QuestionItemService getQuestionItemService(){ return questionItemService; } //设定试题项目业务逻辑 @Autowired public void setQuestionItemService(QuestionItemService questionItemService){ this.questionItemService = questionItemService; } private QuestionItemService questionItemService; //封装试卷基本信息 public Exam getExamBean(HttpServletRequest req, HttpServletResponse res) { Exam exam = new Exam(); try { //判断是否是新增或者修改还是删除,如果是新增则不需要id String hh = req.getParameter("examId" + (String)req.getParameter("checkbox") + ""); if (!"".equals(hh) && hh != null) { exam.setId(Integer.valueOf(req.getParameter("examId" + (String)req.getParameter("checkbox") + ""))); } //获取基本信息 exam.setName(((String)req.getParameter("name" + (String)req.getParameter("checkbox") + ""))); } catch (Exception ex) { ex.printStackTrace(); } return exam; } } [/code] struts和spring的配置文件如下: [code="java"] <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!--表示可以使用动态方法调用,即userAction!delete.action的形式--> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <!--表示struts处于开发状态--> <constant name="struts.devMode" value="true" /> <constant name="struts.convention.classes.reload" value="true" /> <constant name="struts.objectFactory.spring.autoWire" value="type" /> <!--使用默认的命名空间、即根目录/,在访问的时候,直接http://localhost:8080/webExam/userAction!delete.action--> <!--<package name="default" extends="struts-default"> 定义动态方法调用examAction!*.action <action name="examAction" class="examAction"> <result>jsp/examManagement.jsp</result> <result name="createQuestion">jsp/questionManagement.jsp</result> <result name="exam">jsp/exam.jsp</result> <result name="examResult">jsp/examResult.jsp</result> </action> 定义动态方法调用questionAction!*.action <action name="questionAction" class="questionAction"> <result>jsp/questionManagement.jsp</result> <result name="createItem">jsp/questionItemManagement.jsp</result> </action> 定义动态方法调用questionItemAction!*.action <action name="questionItemAction" class="questionItemAction"> <result>jsp/questionItemManagement.jsp</result> </action> </package>--> </struts> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:http-conf="http://cxf.apache.org/transports/http/configuration" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" default-lazy-init="true"> <context:component-scan base-package="com.webExam.dao.impl,com.webExam.service.impl"/> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="entityManager"/> <property name="jpaProperties"> <props></props> </property> </bean> </beans> [/code] persistence文件如下: [code="java"]<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <!--定义持久单元--> <persistence-unit name="entityManager" transaction-type="RESOURCE_LOCAL"> <!--这里采用Hibernate提供的持久化类--> <provider>org.hibernate.ejb.HibernatePersistence</provider> <!--定义持久化属性--> <properties> <!--定义方言、fetch深度、是否显示sql--> <property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect" /> <property name="hibernate.max_fetch_depth" value="3" /> <property name="hibernate.show_sql" value="true" /> <!--定义是否自动生成表,create表示每次加载都重新生成,update表示每次加载只是更新表--> <property name="hibernate.hbm2ddl.auto" value="update" /> <!--定义数据库连接的相关属性--> <property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver" /> <property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:FLOW" /> <!--定义数据库连接的用户名、密码等--> <property name="hibernate.connection.username" value="arch" /> <property name="hibernate.connection.password" value="arch" /> </properties> </persistence-unit> </persistence>[/code]

java 里面通过es查询不到数据。都要哭了。

如题。java代码如下 ``` public List<AvgPowerVo> getAvgPower(AvgPowerParam param) { logger.debug("get avg power start"); List<AvgPowerVo> list = new ArrayList<>(); SearchResponse response = null; BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); TermsAggregationBuilder orderAgg = AggregationBuilders.terms("order ").field("pkgts_date.keyword").order(Terms.Order.term(true)); if (StringUtils.isNotEmpty(param.getVin())) { boolQueryBuilder.must(QueryBuilders.matchQuery("vin", param.getVin())); } int week = param.getWeek(); Date start = DateUtil.getLastWeekStartTime(week); Date end = DateUtil.getLastWeekEndTime(week); if (week == 0) { start = DateUtil.getLastWeekStartTime(12); } boolQueryBuilder.must(QueryBuilders.rangeQuery("pkgts_date").gte(start).lte(end)); SearchRequestBuilder requestBuilder = esClient.getClient() .prepareSearch(esAvgPowerIndex) .setTypes(esAvgPowerType) .addAggregation(orderAgg) .setQuery(boolQueryBuilder); response = requestBuilder.execute().actionGet(); if (response != null) { SearchHits searchHits = response.getHits(); SearchHit[] hits = searchHits.getHits(); for (SearchHit hit : hits) { Map<String, Object> rs = hit.getSource(); AvgPowerVo avgPowerVo = new AvgPowerVo(); String date = (String) rs.get("pkgts_date"); if (StringUtils.isNotEmpty(date)) { date = date.substring(0, 10); } avgPowerVo.setPkgtsDate(DateUtil.formatToDate(date)); avgPowerVo.setAvgConsumOnce((Double) rs.get("avg_consum_once")); avgPowerVo.setAvgConsumAdd((Double) rs.get("avg_consum_add")); list.add(avgPowerVo); } } return list; } ``` 然后这个是java里面执行的查询语句 ``` { "query" : { "bool" : { "must" : [ { "match" : { "vin" : { "query" : "LMGFE1G88D1022052", "operator" : "OR", "prefix_length" : 0, "max_expansions" : 50, "fuzzy_transpositions" : true, "lenient" : false, "zero_terms_query" : "NONE", "boost" : 1.0 } } }, { "range" : { "pkgts_date" : { "from" : "2017-11-02T16:00:00.000Z", "to" : "2018-01-26T15:59:59.999Z", "include_lower" : true, "include_upper" : true, "boost" : 1.0 } } } ], "disable_coord" : false, "adjust_pure_negative" : true, "boost" : 1.0 } }, "aggregations" : { "order " : { "terms" : { "field" : "pkgts_date.keyword", "size" : 10, "min_doc_count" : 1, "shard_min_doc_count" : 0, "show_term_doc_count_error" : false, "order" : { "_term" : "asc" } } } } } ``` 然后我把这个拿到chrome客户端去查询。能够查询出来。。。 ``` { "query": { "bool": { "must": [ { "range": { "pkgts_time": { "gte": "2017-11-02T16:00:00.000Z", "lt": "2018-01-26T15:59:59.999Z" } } } , { "term": { "vin.keyword": "LMGFE1G88D1022052" } } ], "must_not": [ ], "should": [ ] } }, "from": 0, "size": 50, "sort": [ ], "aggs": { } } ``` 有大神来帮忙回答下吗。

为什么我的Go数组排序代码比Java慢得多?

<div class="post-text" itemprop="text"> <p>After migrating one of my computing heavy backend programs from Java to Go, I find that the performance degraded instead of improving. I tested around some and it seems the array sorting code is the culprit (which I used heavily in my program). I have written the below two simplified programs to do a comparison, and somehow it seems Go's built-in sort function is a lot slower than Java's Arrays.sort method?</p> <pre><code>package main import ( "fmt" "math/rand" "sort" "time" ) func main() { fmt.Println("Starting") const x = 1000000 const y = x * 10 var s [y]float64 s1 := rand.NewSource(time.Now().UnixNano()) r1 := rand.New(s1) start1 := time.Now() for i := 0; i &lt; y; i++ { s[i] = r1.Float64() } end1 := time.Since(start1) ss := s[:] start2 := time.Now() sort.Float64s(ss) end2 := time.Since(start2) fmt.Println(end1) fmt.Println(end2) fmt.Println("Number: ", ss[x]) } </code></pre> <p>and it produces results like this:</p> <pre><code>Starting 136.6331ms // The time taken to generate 10,000,000 random numbers 3.456781s // The time taken to sort the 10,000,000 random numbers Number: 0.10000285497001288 </code></pre> <p>While with the Java program here</p> <pre><code>import java.util.*; class RSTest { public static void main(String[] args) { System.out.println("Starting"); int x = 1000000; int y = x * 10; Random gen = new Random(System.currentTimeMillis()); double[] s = new double[y]; long start1 = System.nanoTime(); for (int i = 0; i &lt; y; i++) { s[i] = gen.nextDouble(); } long end1 = System.nanoTime(); long start2 = System.nanoTime(); Arrays.sort(s); long end2 = System.nanoTime(); System.out.println((end1 - start1) / (1000000000.0)); System.out.println((end2 - start2) / (1000000000.0)); System.out.println(s[x]); } } </code></pre> <p>the results are like this</p> <pre><code>Starting 0.2252634 // The time taken to generate 10,000,000 random numbers 1.0303157 // The time taken to sort the 10,000,000 random numbers 0.0999513608326642 </code></pre> <p>the Go program takes around 130ms to generate 10 million random numbers and assign them to an array while Jave takes around 230ms to generate 10 million random numbers and assign them to an array, this part I think is the improvement I expect from going from Java to Go.</p> <p>But for the sorting part, it took Java only around 1s to sort the 10 million random numbers but it took Go around 3.5s to do the 10 million random number sort? And this is quite consistent from multiple runs of the test.</p> <p>So does that mean Go's built-in sort function is really this much inferior to Java's Arrays.sort method? Or did I use Go's sort function wrong? Or something is wrong with my programs?</p> <p>Thanks.</p> <p>Note: this is from Go 1.11 and Java 8, the current versions I'm running on my server. Also, please note that the two programs I posted here are purely for testing purposes that I have written in a couple minutes so may (or rather, most certainly do) contain some code that doesn't make much sense for real production systems.</p> <p>Some Update:</p> <p>Thanks to @nussjustin's suggestion, I tried sort.Slice with some promising results.</p> <p>As currently I'm out of office and using a slower notebook, the baseline results for the two above tests are like this now:</p> <p>For the Java Arrays.sort test</p> <pre><code>Starting 0.3590694 1.6030528 // The time taken to sort the 10,000,000 random numbers 0.10000905418967532 </code></pre> <p>For the Go sort.Float64s test</p> <pre><code>Go Starting 233.1957ms 5.4633992s // The time taken to sort the 10,000,000 random numbers Number: 0.10002801819954663 </code></pre> <p>And now after modifying the Go test with sort.Slice</p> <pre><code>package main import ( "fmt" "math/rand" "sort" "time" ) func main() { fmt.Println("Starting") const x = 1000000 const y = x * 10 var s [y]float64 s1 := rand.NewSource(time.Now().UnixNano()) r1 := rand.New(s1) start1 := time.Now() for i := 0; i &lt; y; i++ { s[i] = r1.Float64() } end1 := time.Since(start1) ss := s[:] start2 := time.Now() sort.Slice(ss, func(i, j int) bool { return ss[i] &lt; ss[j] }) end2 := time.Since(start2) fmt.Println(end1) fmt.Println(end2) fmt.Println("Number: ", ss[x]) } </code></pre> <p>The result is a big improvement over sort.Float64s, but still not as good as Java's array sort</p> <pre><code>Starting 281.4262ms 3.6745684s // The time taken to sort the 10,000,000 random numbers Number: 0.10010604106864159 </code></pre> <p>And I think someone complained that there is only 1 distribution for the tests (who later removed his comment), I tested for sorting normal distribution of random numbers too (albeit I'd say such a huge performance difference in sorting uniform distribution of random numbers is already quite a bad sign since the algorithms of sorting uniform distribution of random numbers should be quite mature already)</p> <p>I just replace the random number generator from uniform distribution to normal distribution like this</p> <p>Go:</p> <pre><code>s[i] = r1.NormFloat64() </code></pre> <p>Java:</p> <pre><code>s[i] = gen.nextGaussian(); </code></pre> <p>And the result of Java's Arrays.sort method is</p> <pre><code>Starting 1.4126348 1.6118655 -1.2820310313627319 </code></pre> <p>And Go's sort.Slice </p> <pre><code>Starting 434.9106ms 3.8936811s Number: -1.2818667132095363 </code></pre> <p>So Go is sort.Slice is still about twice slower than Java's Arrays.sort, same as for uniform distribution of random numbers. The good thing is that in generating the normal distribution of random numbers, Go is three times faster than Java, compared to about 70% faster in generating uniform distribution of numbers.</p> </div>

java web怎样实现商品分类显示

自己写了一个小的javaweb项目,用的jsp+servlet。 想实现商品的分类显示,但是不知道怎样从jsp页面传值给dao层,以及查询语句怎么写? 求大神帮助。 这是jsp页面: ``` <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%> <%@ page import="cn.edu.qust.bookcitys.entity.Items"%> <%@ page import="cn.edu.qust.bookcitys.dao.ItemsDao"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>展示</title> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/common.css" rel="stylesheet"> <link href="css/show.css" rel="stylesheet"> </head> <body> <header> <!-- logo --> <div class="index-header-top"> <img src="images/logo.png" class="logo"> </div> <!--导航栏--> <nav class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <ul class="nav navbar-nav"> <li><a href="index.jsp">首页</a></li> <li class="active"><a href="show.jsp" target="_self">展示</a></li> <li><a href="cart.jsp" target="_self">购物车</a></li> <li><a href="login.jsp" target="_self">登录</a></li> </ul> </div> </nav> </header> <div class="details_container"> <div class="details_left"> <dl> <dt class="book"> <a href="show.jsp?sort=1">文学</a> </dt> <dd> <a href="#">作品集</a> </dd> <dd> <a href="#">名著</a> </dd> <dd> <a href="#">小说</a> </dd> </dl> <dl> <dt class="xbook"> <a href="show.jsp?sort=2">青春</a> </dt> <dd> <a href="#">青春</a> </dd> <dd> <a href="#">励志</a> </dd> <dd> <a href="#">校园</a> </dd> </dl> <dl> <dt class="book"> <a href="show.jsp?sort=3">生活</a> </dt> <dd> <a href="#">作品集</a> </dd> <dd> <a href="#">名著</a> </dd> <dd> <a href="#">小说</a> </dd> </dl> </div> <div class="details_right"> <div style="width: 1000px;"> <% ItemsDao itemsDao = new ItemsDao(); String sort = request.getParameter("sort"); ArrayList<Items> list = itemsDao.getAllItems(); if (list != null && list.size() > 0) { for (int i = 0; i < list.size(); i++) { Items item = list.get(i); request.setAttribute("item",item); %> <div style="width: 180px; height: 220px; float: left;"> <a href="details.jsp?id=${item.id }"><img style="float: left;" src="images/${item.picture }" width="170px" height="120px" border="1" /></a> <span style="float: left; margin: 5px 0px 0px 5px; color: blue">${item.name }</span> <span style="float: left; margin: 5px 0px 0px 5px; color: #000">作者:${item.author }&nbsp;&nbsp; 价格: ${item.price }¥ </span> </div> <% } } %> </div> </div> </div> <div class="details_bottom"> <footer> Copyright &copy; Made By 泥石流 </footer> </div> <!-- 如果要使用Bootstrap的js插件,必须先调入jQuery --> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.min.js"></script> <!-- 包括所有bootstrap的js插件或者可以根据需要使用的js插件调用 --> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </body> </html> ``` ``` 这是dao层: package cn.edu.qust.bookcitys.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import cn.edu.qust.bookcitys.entity.Items; import cn.edu.qust.bookcitys.util.DBHelper; //商品的业务逻辑类 public class ItemsDao { //获得所有的商品信息 public ArrayList<Items> getAllItems(){ Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; ArrayList<Items> list = new ArrayList<Items>();//商品集合 try{ conn = DBHelper.getConnection(); // String sql = "select * from items where sort=?;";//sql语句 String sql = "select * from items ;";//sql语句 stmt = conn.prepareStatement(sql); // stmt.setInt(1, sort); rs = stmt.executeQuery(); while(rs.next()){ Items item = new Items(); item.setId(rs.getInt("id")); item.setName(rs.getString("name")); item.setAuthor(rs.getString("author")); item.setNumber(rs.getInt("number")); item.setPrice(rs.getInt("price")); item.setPicture(rs.getString("picture")); item.setSort(rs.getInt("sort")); list.add(item);//每次遍历把一个商品加入集合 } return list; } catch(Exception e){ e.printStackTrace(); return null; } finally{ //释放数据集对象 if(rs!=null){ try{ rs.close(); rs = null; } catch(Exception e){ e.printStackTrace(); } } //释放语句对象 if(stmt!=null){ try{ stmt.close(); stmt = null; } catch(Exception e){ e.printStackTrace(); } } } } //根据商品编号获得商品资料 public Items getItemsById(int id){ Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try{ conn = DBHelper.getConnection(); String sql = "select * from items where id=?;";//sql语句 stmt = conn.prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); if(rs.next()){ Items item = new Items(); item.setId(rs.getInt("id")); item.setName(rs.getString("name")); item.setAuthor(rs.getString("author")); item.setNumber(rs.getInt("number")); item.setPrice(rs.getInt("price"));; item.setPicture(rs.getString("picture")); item.setSort(rs.getInt("sort")); return item; } else{ return null; } } catch(Exception e){ e.printStackTrace(); return null; } finally{ //释放数据集对象 if(rs!=null){ try{ rs.close(); rs = null; } catch(Exception e){ e.printStackTrace(); } } //释放语句对象 if(stmt!=null){ try{ stmt.close(); stmt = null; } catch(Exception e){ e.printStackTrace(); } } } } //获取最近浏览的前3条信息 public ArrayList<Items> getViewList(String list){ System.out.println("list:"+list); ArrayList<Items> itemlist = new ArrayList<Items>(); int iCount = 3; if(list!=null&&list.length()>0){ String[] arr = list.split("#"); System.out.println("arr.length="+arr.length); //如果商品记录大于等于3条 if(arr.length>=3){ for(int i=arr.length-1;i>=arr.length-iCount;i--){ itemlist.add(getItemsById(Integer.parseInt(arr[i]))); } } else{ for(int i = arr.length-1;i>=0;i--){ itemlist.add(getItemsById(Integer.parseInt(arr[i]))); } } return itemlist; } else{ return null; } } } ``` ``` 想把sort的值传到dao层并实现分类显示。

android这个错误怎么改啊?

两部分代码分开写可以,放在一起写不知道哪里错了 . ``` import java.util.ArrayList; import java.util.List; import android.app.ActionBar; import android.app.Activity; import android.content.res.Configuration; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.DrawerLayout.DrawerListener; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends Activity implements OnItemClickListener, DrawerListener { private DrawerLayout drawerLayout; private ListView lv_drawer; private ArrayAdapter<String> adapter_drawer; private ArrayList<String> list_drawer; private String string_drawer; private ActionBarDrawerToggle toggle; private ListView lv_swiperefresh; private SwipeRefreshLayout swipeRefreshLayout; private ArrayAdapter<String> adapter_swipe; private ArrayList<String> list_swipe; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); drawerLayout = (DrawerLayout) findViewById(R.id.drawer); lv_drawer = (ListView) findViewById(R.id.list_drawer); list_drawer = new ArrayList<String>(); for (int i = 0; i <= 5; i++) { list_drawer.add("天香-天心" + i); } adapter_drawer = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list_drawer); lv_drawer.setAdapter(adapter_drawer); lv_drawer.setOnItemClickListener(this); ActionBar bar = getActionBar(); bar.setDisplayHomeAsUpEnabled(true); bar.setHomeButtonEnabled(true); string_drawer = (String) bar.getTitle(); toggle = new ActionBarDrawerToggle(this, drawerLayout, android.R.drawable.ic_media_play, 0, 0); drawerLayout.setDrawerListener(this); lv_swiperefresh = (ListView) findViewById(R.id.lv_swipe); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefreshlayout); list_swipe = new ArrayList<String>(); for (int i = 0; i <= 3; i++) { list_swipe.add("项目" + i); } adapter_swipe = new ArrayAdapter<String>(this, R.layout.item, R.id.lv_swipe, list_swipe); lv_swiperefresh.setAdapter(adapter_swipe); swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { new updata().execute(); } }); } private class updata extends AsyncTask<Void, Void, List<String>> { @Override protected List<String> doInBackground(Void... params) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } List<String> newData = new ArrayList<String>(); newData.add("新数据1"); newData.add("新数据2"); newData.add("新数据3"); return newData; } @Override protected void onPostExecute(List<String> result) { adapter_swipe.addAll(result); swipeRefreshLayout.setRefreshing(false); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (toggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onPostCreate(Bundle savedInstanceState) { toggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { toggle.onConfigurationChanged(newConfig); } @Override public void onDrawerClosed(View arg0) { getActionBar().setTitle(string_drawer); } @Override public void onDrawerOpened(View arg0) { getActionBar().setTitle("success"); } @Override public void onDrawerSlide(View arg0, float arg1) { } @Override public void onDrawerStateChanged(int arg0) { } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(this, lv_drawer.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show(); drawerLayout.closeDrawer(lv_drawer); } } ``` ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.refresh_drawer_demo.MainActivity" > <android.support.v4.widget.DrawerLayout android:id="@+id/drawer" android:layout_height="match_parent" android:layout_width="match_parent"> <FrameLayout android:id="@+id/frame_drawer" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout> <ListView android:id="@+id/list_drawer" android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="start" android:choiceMode="singleChoice" android:divider="@android:color/transparent" android:dividerHeight="0dp" android:background="#ffffcc" ></ListView> </android.support.v4.widget.DrawerLayout> <android.support.v4.widget.SwipeRefreshLayout android:id="@+id/swiperefreshlayout" android:layout_width="match_parent" android:layout_height="wrap_content" > <ListView android:id="@+id/lv_swipe" android:layout_width="match_parent" android:layout_height="match_parent" > </ListView> </android.support.v4.widget.SwipeRefreshLayout> </RelativeLayout> ``` ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="40dip" android:textColor="#000" android:gravity="center_vertical" android:textSize="18sp" /> </LinearLayout> ``` 【错误报告】 . ``` 10-03 03:18:42.596: E/memtrack(1969): Couldn't load memtrack module (No such file or directory) 10-03 03:18:42.606: E/android.os.Debug(1969): failed to load memtrack module: -2 10-03 03:18:42.936: E/memtrack(1979): Couldn't load memtrack module (No such file or directory) 10-03 03:18:42.936: E/android.os.Debug(1979): failed to load memtrack module: -2 10-03 03:18:42.976: E/gralloc_goldfish(939): gralloc_alloc: Mismatched usage flags: 246 x 410, usage 333 10-03 03:18:42.976: E/(939): GraphicBufferAlloc::createGraphicBuffer(w=246, h=410) failed (Invalid argument), handle=0x0 10-03 03:18:42.976: E/BufferQueue(1278): [ScreenshotClient] dequeueBuffer: SurfaceComposer::createGraphicBuffer failed 10-03 03:18:43.136: E/AndroidRuntime(1991): FATAL EXCEPTION: main 10-03 03:18:43.136: E/AndroidRuntime(1991): Process: com.example.refresh_drawer_demo, PID: 1991 10-03 03:18:43.136: E/AndroidRuntime(1991): android.util.SuperNotCalledException: Activity {com.example.refresh_drawer_demo/com.example.refresh_drawer_demo.MainActivity} did not call through to super.onPostCreate() 10-03 03:18:43.136: E/AndroidRuntime(1991): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 10-03 03:18:43.136: E/AndroidRuntime(1991): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 10-03 03:18:43.136: E/AndroidRuntime(1991): at android.app.ActivityThread.access$800(ActivityThread.java:135) 10-03 03:18:43.136: E/AndroidRuntime(1991): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 10-03 03:18:43.136: E/AndroidRuntime(1991): at android.os.Handler.dispatchMessage(Handler.java:102) 10-03 03:18:43.136: E/AndroidRuntime(1991): at android.os.Looper.loop(Looper.java:136) 10-03 03:18:43.136: E/AndroidRuntime(1991): at android.app.ActivityThread.main(ActivityThread.java:5017) 10-03 03:18:43.136: E/AndroidRuntime(1991): at java.lang.reflect.Method.invokeNative(Native Method) 10-03 03:18:43.136: E/AndroidRuntime(1991): at java.lang.reflect.Method.invoke(Method.java:515) 10-03 03:18:43.136: E/AndroidRuntime(1991): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 10-03 03:18:43.136: E/AndroidRuntime(1991): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 10-03 03:18:43.136: E/AndroidRuntime(1991): at dalvik.system.NativeStart.main(Native Method) 10-03 03:18:43.366: E/gralloc_goldfish(939): gralloc_alloc: Mismatched usage flags: 246 x 410, usage 333 10-03 03:18:43.366: E/(939): GraphicBufferAlloc::createGraphicBuffer(w=246, h=410) failed (Invalid argument), handle=0x0 10-03 03:18:43.366: E/BufferQueue(1278): [ScreenshotClient] dequeueBuffer: SurfaceComposer::createGraphicBuffer failed 10-03 03:18:53.006: E/WindowManager(1278): Starting window AppWindowToken{b34da468 token=Token{b3681700 ActivityRecord{b39889b0 u0 com.example.refresh_drawer_demo/.MainActivity t5}}} timed out ```

将0000-00-00 00:00:00 datetime从mysql插入postgresql

<div class="post-text" itemprop="text"> <p>I'm trying to go from a mysql database to a postgresql database. I created a script with this query</p> <pre><code> if ($result-&gt;num_rows &gt; 0) { while($row = $result-&gt;fetch_assoc()) { $psql = "INSERT INTO subscriptions_sub (sub_id,cust_id,tarrif_id,des,datetime_created,datetime_modified,credit,credit_limit,status,date_start,date_end,backoffice_userref,backoffice_deleted,backoffice_createdon,backoffice_createdby, backoffice_updatedon,backoffice_updatedby,backoffice_administration,backoffice_readonly,backoffice_order,backoffice_dummy) VALUES('" .(int) $row["sub_id"] . "','" . (int) $row["cust_id"] . "','" . (int) $row["tarrif_id"] . "','" . $row["des"] . "','" . $row["datetime_created"] . "','" . $row["datetime_modified"] . "','" . $row["credit"] . "','" . $row["credit_limit"] . "','" . $row["status"] . "','" . $row["date_start"] . "','" . $row["date_end"] . "','" . $row["backoffice_userref"] . "','" . $row["backoffice_deleted"] . "','" . $row["backoffice_createdon"] . "','" . $row["backoffice_createdby"] . "','" . $row["backoffice_updatedon"] . "','" . (int) $row["backoffice_updatedby"] . "','" . (int) $row["backoffice_administration"] . "','" . $row["backoffice_readonly"] . "','" . (int)$row["backoffice_order"] . "','" . $row["backoffice_dummy"] . "'); "; print_r($row); $ret = pg_query($db, $psql); if(!$ret){ echo pg_last_error($db); } else { echo "Records created succesfully "; } } </code></pre> <p>this is my subscription.sub</p> <pre><code> _columns = { 'sub_id': fields.integer('Subscription ID', size=10), 'cust_id': fields.many2one('res.partner','customer_id', 'Customer ID'), 'tarrif_id': fields.integer('Tariefplan ID', size=10, required=True), 'des': fields.char('Description', size=64), 'datetime_created': fields.datetime('Created', default='0'), 'datetime_modified': fields.datetime('Modified', default='0'), 'credit': fields.float('Credit', digits=(10,4)), 'credit_limit': fields.float('Credit limit', digits=(10,4)), 'status': fields.selection([('active','Active'),('inactive','Inactive'),('ended','Ended'),('deleted','Deleted'),('disabled','Disabled')], 'Status', default='active', required=True), 'date_start': fields.date('Date start'), 'date_end': fields.date('Date end'), 'backoffice_userref': fields.integer('Backoffice_userref', size=10), 'backoffice_deleted': fields.boolean('Backoffice_deleted', size=1, default='0', required=True), 'backoffice_createdon': fields.datetime('Backoffice_createdon', default='0'), 'backoffice_createdby': fields.integer('Backoffice_createdby', size=10, default='0', required=True), 'backoffice_updatedon': fields.datetime('Backoffice_updatedon', default='0'), 'backoffice_updatedby': fields.integer('Backoffice_updatedby', size=10, default='0', required=True), 'backoffice_administration': fields.integer('Backoffice_administration', size=10, default='1', required=True), 'backoffice_readonly': fields.boolean('Backoffice_readonly', size=1, default='0', required=True), 'backoffice_order': fields.integer('Backoffice_order', size=20, default='-1', required=True), 'backoffice_dummy': fields.boolean('Backoffice_dummy', size=1, default='0', required=True), #'qty_available': fields.related('customer_id','subscription_id',type='char', relation="partner.res", string="subscription", store=True) } </code></pre> <p>for example: the datetime_created field has the value '0000-00-00 00:00:00' in the mysql database with type TIMESTAMP.<br> When I execute my script is shows the error:</p> <p>ERROR: date/time field value out of range: "0000-00-00 00:00:00".</p> <p>Is it possible to convert the datetime from mysql to postgresql?</p> </div>

C++代码改Python实现PCA算法:从一组照片中获取特征脸(特征向量)?

PCA处理的基本步骤为: 1、获取m个样本,每个样本有n个特征。 2、每个样本作为一行,构成m*n的举证A。 3、将矩阵转置再乘以自己得到C=A(t)*A。 4、求出矩阵C的特征值及特征向量,特征向量即为特征脸。 以下是C++实现代码,求解决一份Python实现出的代码 ``` #include "stdafx.h" #include <string> #include <opencv2\opencv.hpp> using namespace std; using namespace cv; int _tmain(int argc, _TCHAR* argv[]) { //获取了mean_face int num_sample = 38; int norm_row = 64, norm_col = 56; int num; Mat imgs = loadImages(num); Mat mean_face = Mat(norm_row, norm_col, CV_8UC1); vector<int> mean_face_total; mean_face_total.resize(norm_row * norm_col); for (int i = 0; i < num; i++) { for (int j = 0; j < norm_row * norm_col; j++) { mean_face_total.at(j) += imgs.at<uchar>(i * norm_row * norm_col + j); //eigen_face_total[j] += imgs.at<uchar>(i * 192 * 168 + j); } } for (int j = 0; j < norm_row * norm_col; j++) { mean_face.at<uchar>(j) = (uchar)(mean_face_total.at(j) / num); } imwrite("C:/Users/dhj555/Desktop/YelaFaces/eigen_face/0001.jpg", mean_face); imshow("eigen_face", mean_face); //1、初始化数据 CvMat* pData = cvCreateMat(num_sample, norm_row * norm_col, CV_32FC1); CvMat* pMean = cvCreateMat(1, norm_row * norm_col, CV_32FC1); //每个数标志一个特征值 CvMat* pEigVals = cvCreateMat(1, min(num_sample, norm_row * norm_col), CV_32FC1); //每行表示一个特征向量 CvMat* pEigVecs = cvCreateMat(min(num_sample, norm_row * norm_col), norm_row * norm_col, CV_32FC1); for (int i = 0; i < num_sample; i++) { for (int j = 0; j < norm_row * norm_col; j++) cvmSet(pData, i, j, imgs.at<uchar>(i * norm_row * norm_col + j)); } //2、PCA处理 cvCalcPCA(pData, pMean, pEigVals, pEigVecs, CV_PCA_DATA_AS_ROW); //3、选出前P个特征向量(主成份),然后投影,结果保存在pResult中,pResult中包含了P个系数 //CvMat* pResult = cvCreateMat(num_sample, 20, CV_32FC1); //cvProjectPCA(pData, pMean, pEigVecs, pResult); //4、重构, 结果保存在pRecon中 //CvMat* pRecon = cvCreateMat(num_sample, norm_row*norm_col, CV_32FC1); //cvBackProjectPCA(pResult, pMean, pEigVecs, pRecon); //5、显示重构的图像 //Mat mRecon = Mat(pRecon); //4、显示与保存特征向量 for (int i = 0; i < min(num_sample, norm_row * norm_col); i++) { float min = LLONG_MAX, max = LLONG_MIN, span = 0.0; for (int index = 0; index < norm_row*norm_col; index++) { float d = cvmGet(pEigVecs, i, index); if (d>max) max = d; if (d < min) min = d; } span = max - min; Mat eigen_face = Mat(norm_row, norm_col, CV_8UC1); for (int index = 0; index < norm_row*norm_col; index++) { float d = cvmGet(pEigVecs, i, index); eigen_face.at<uchar>(index) = (d - min) / span * 255.0; } char buffer[128]; sprintf_s(buffer, "C:/Users/dhj555/Desktop/YelaFaces/eigen_face/001/1-000%d.jpg", i); string imgPath(buffer); imshow(imgPath, eigen_face); printf("%d st:\t%f\n", i, cvmGet(pEigVals, 0, i)); imwrite(imgPath, eigen_face); } } ```

Android上传摄像头图像,视频到php服务器

<div class="post-text" itemprop="text"> <p>I am trying to capture image or record a video using camera and then upload to my server. On the server side, i used PHP language to read the file and moved it to a particular location.</p> <p>This is the PHP script</p> <p></p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>&lt;?php // Path to move uploaded files $target_path = "uploads/"; // array for final json respone $response = array(); // getting server ip address $server_ip = gethostbyname(gethostname()); // final file url that is being uploaded $file_upload_url = 'http://' . $server_ip . '/' . 'AndroidFileUpload' . '/' . $target_path; if (isset($_FILES['image']['name'])) { $target_path = $target_path . basename($_FILES['image']['name']); // reading other post parameters $email = isset($_POST['email']) ? $_POST['email'] : ''; $website = isset($_POST['website']) ? $_POST['website'] : ''; $response['file_name'] = basename($_FILES['image']['name']); $response['email'] = $email; $response['website'] = $website; try { // Throws exception incase file is not being moved if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) { // make error flag true $response['error'] = true; $response['message'] = 'Could not move the file!'; } // File successfully uploaded $response['message'] = 'File uploaded successfully!'; $response['error'] = false; $response['file_path'] = $file_upload_url . basename($_FILES['image']['name']); } catch (Exception $e) { // Exception occurred. Make error flag true $response['error'] = true; $response['message'] = $e-&gt;getMessage(); } } else { // File parameter is missing $response['error'] = true; $response['message'] = 'Not received any file!F'; } // Echo final json response to client echo json_encode($response); ?&gt;</code></pre> </div> </div> <p>and then i got PHP error like this </p> <p><img src="https://i.stack.imgur.com/51abI.png" alt="enter image description here"></p> <p>i do not have experience in PHP coding, i want to know what's wrong with this PHP.</p> <p>The android client is complete run, it can take photo and video very well, even upload is completed, but i got nothing in my server client folder.</p> <p><img src="https://i.stack.imgur.com/SGd2E.jpg" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/9Ads7.png" alt="enter image description here"> There are my android code:</p> <p><strong>MainActivity.java</strong></p> <pre><code>public class MainActivity extends Activity { // LogCat tag private static final String TAG = MainActivity.class.getSimpleName(); // Camera activity request codes private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100; private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200; public static final int MEDIA_TYPE_IMAGE = 1; public static final int MEDIA_TYPE_VIDEO = 2; private Uri fileUri; // file url to store image/video private Button btnCapturePicture, btnRecordVideo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Changing action bar background color // These two lines are not needed getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar)))); btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture); btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo); /** * Capture image button click event */ btnCapturePicture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // capture picture captureImage(); } }); /** * Record video button click event */ btnRecordVideo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // record video recordVideo(); } }); // Checking camera availability if (!isDeviceSupportCamera()) { Toast.makeText(getApplicationContext(), "Sorry! Your device doesn't support camera", Toast.LENGTH_LONG).show(); // will close the app if the device does't have camera finish(); } } /** * Checking device has camera hardware or not * */ private boolean isDeviceSupportCamera() { if (getApplicationContext().getPackageManager().hasSystemFeature( PackageManager.FEATURE_CAMERA)) { // this device has a camera return true; } else { // no camera on this device return false; } } /** * Launching camera app to capture image */ private void captureImage() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // start the image capture Intent startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE); } /** * Launching camera app to record video */ private void recordVideo() { Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO); // set video quality intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file // name // start the video capture Intent startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE); } /** * Here we store the file url as it will be null after returning from camera * app */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // save file url in bundle as it will be null on screen orientation // changes outState.putParcelable("file_uri", fileUri); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // get the file url fileUri = savedInstanceState.getParcelable("file_uri"); } /** * Receiving activity result method will be called after closing the camera * */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if the result is capturing Image if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) { if (resultCode == RESULT_OK) { // successfully captured the image // launching upload activity launchUploadActivity(true); } else if (resultCode == RESULT_CANCELED) { // user cancelled Image capture Toast.makeText(getApplicationContext(), "User cancelled image capture", Toast.LENGTH_SHORT) .show(); } else { // failed to capture image Toast.makeText(getApplicationContext(), "Sorry! Failed to capture image", Toast.LENGTH_SHORT) .show(); } } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) { if (resultCode == RESULT_OK) { // video successfully recorded // launching upload activity launchUploadActivity(false); } else if (resultCode == RESULT_CANCELED) { // user cancelled recording Toast.makeText(getApplicationContext(), "User cancelled video recording", Toast.LENGTH_SHORT) .show(); } else { // failed to record video Toast.makeText(getApplicationContext(), "Sorry! Failed to record video", Toast.LENGTH_SHORT) .show(); } } } private void launchUploadActivity(boolean isImage){ Intent i = new Intent(MainActivity.this, UploadActivity.class); i.putExtra("filePath", fileUri.getPath()); i.putExtra("isImage", isImage); startActivity(i); } /** * ------------ Helper Methods ---------------------- * */ /** * Creating file uri to store image/video */ public Uri getOutputMediaFileUri(int type) { return Uri.fromFile(getOutputMediaFile(type)); } /** * returning image / video */ private static File getOutputMediaFile(int type) { // External sdcard location File mediaStorageDir = new File( Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), Config.IMAGE_DIRECTORY_NAME); // Create the storage directory if it does not exist if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d(TAG, "Oops! Failed create " + Config.IMAGE_DIRECTORY_NAME + " directory"); return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); File mediaFile; if (type == MEDIA_TYPE_IMAGE) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); } else if (type == MEDIA_TYPE_VIDEO) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4"); } else { return null; } return mediaFile; } </code></pre> <p>}</p> <p><strong>Config.java</strong></p> <pre><code>public class Config { // File upload url (replace the ip with your server address) public static final String FILE_UPLOAD_URL = "http://wangjian.site90.net/AndroidFileUpload/fileUpload.php"; // Directory name to store captured images and videos public static final String IMAGE_DIRECTORY_NAME = "Android File Upload"; </code></pre> <p>}</p> <p><strong>UploadActivity.java</strong></p> <pre><code>public class UploadActivity extends Activity{ // LogCat tag private static final String TAG = MainActivity.class.getSimpleName(); private ProgressBar progressBar; private String filePath = null; private TextView txtPercentage; private ImageView imgPreview; private VideoView vidPreview; private Button btnUpload; long totalSize = 0; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_upload); txtPercentage = (TextView) findViewById(R.id.txtPercentage); btnUpload = (Button) findViewById(R.id.btnUpload); progressBar = (ProgressBar) findViewById(R.id.progressBar); imgPreview = (ImageView) findViewById(R.id.imgPreview); vidPreview = (VideoView) findViewById(R.id.videoPreview); // Changing action bar background color getActionBar().setBackgroundDrawable( new ColorDrawable(Color.parseColor(getResources().getString( R.color.action_bar)))); // Receiving the data from previous activity Intent i = getIntent(); // image or video path that is captured in previous activity filePath = i.getStringExtra("filePath"); // boolean flag to identify the media type, image or video boolean isImage = i.getBooleanExtra("isImage", true); if (filePath != null) { // Displaying the image or video on the screen previewMedia(isImage); } else { Toast.makeText(getApplicationContext(), "Sorry, file path is missing!", Toast.LENGTH_LONG).show(); } btnUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // uploading the file to server new UploadFileToServer().execute(); } }); } /** * Displaying captured image/video on the screen * */ private void previewMedia(boolean isImage) { // Checking whether captured media is image or video if (isImage) { imgPreview.setVisibility(View.VISIBLE); vidPreview.setVisibility(View.GONE); // bimatp factory BitmapFactory.Options options = new BitmapFactory.Options(); // down sizing image as it throws OutOfMemory Exception for larger // images options.inSampleSize = 8; final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options); imgPreview.setImageBitmap(bitmap); } else { imgPreview.setVisibility(View.GONE); vidPreview.setVisibility(View.VISIBLE); vidPreview.setVideoPath(filePath); // start playing vidPreview.start(); } } /** * Uploading the file to server * */ private class UploadFileToServer extends AsyncTask&lt;Void, Integer, String&gt; { @Override protected void onPreExecute() { // setting progress bar to zero progressBar.setProgress(0); super.onPreExecute(); } @Override protected void onProgressUpdate(Integer... progress) { // Making progress bar visible progressBar.setVisibility(View.VISIBLE); // updating progress bar value progressBar.setProgress(progress[0]); // updating percentage value txtPercentage.setText(String.valueOf(progress[0]) + "%"); } @Override protected String doInBackground(Void... params) { return uploadFile(); } @SuppressWarnings("deprecation") private String uploadFile(){ String responseString = null; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL); try { AndroidMultiPartEntity entity = new AndroidMultiPartEntity( new ProgressListener() { @Override public void transferred(long num) { publishProgress((int) ((num / (float) totalSize) * 100)); } }); File sourceFile = new File(filePath); // Adding file data to http body entity.addPart("image", new FileBody(sourceFile)); // Extra parameters if you want to pass to server entity.addPart("website",new StringBody("www.androidhive.info")); entity.addPart("email", new StringBody("abc@gmail.com")); totalSize = entity.getContentLength(); httppost.setEntity(entity); // Making server call HttpResponse response = httpclient.execute(httppost); HttpEntity r_entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { // Server response responseString = EntityUtils.toString(r_entity); } else { responseString = "Error occurred! Http Status Code: " + statusCode; } } catch (ClientProtocolException e) { responseString = e.toString(); } catch (IOException e) { responseString = e.toString(); } return responseString; } @Override protected void onPostExecute(String result) { Log.e(TAG, "Response from server: " + result); // showing the server response in an alert dialog showAlert(result); super.onPostExecute(result); } } /** * Method to show alert dialog * */ private void showAlert(String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message).setTitle("Response from Servers") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // do nothing } }); AlertDialog alert = builder.create(); alert.show(); } </code></pre> <p>}</p> <p><strong>Manifest.xml</strong></p> <p></p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.wangjian.klmeet_photo" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="16" android:targetSdkVersion="16" /&gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; &lt;uses-permission android:name="android.permission.RECORD_AUDIO" /&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;activity android:name=".MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name="com.wangjian.klmeet_photo.UploadActivity" android:screenOrientation="portrait" &gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt;</code></pre> </div> </div> <p>this is LogCat:</p> <pre><code>06-04 03:53:12.440: E/MainActivity(7920): &lt;b&gt;Fatal error&lt;/b&gt;: Call to undefined function gethostname() in &lt;b&gt;/home/a4256838/public_html/AndroidFileUpload/fileUpload.php&lt;/b&gt; on line &lt;b&gt;10&lt;/b&gt;&lt;br /&gt; 06-04 03:53:12.440: E/MainActivity(7920): &lt;br&gt;&lt;table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'&gt;&lt;tr&gt;&lt;td&gt;&lt;div align='center'&gt;&lt;a href='http://www.000webhost.com/'&gt;&lt;font face='Arial' size='1' color='#000000'&gt;Free Web Hosting&lt;/font&gt;&lt;/a&gt;&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; </code></pre> <p>I'm a newbie at this stuff so any help will be appreciated. thanks so much! And i will upload more details if needed. </p> </div>

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

搜狗输入法也在挑战国人的智商!

故事总是一个接着一个到来...上周写完《鲁大师已经彻底沦为一款垃圾流氓软件!》这篇文章之后,鲁大师的市场工作人员就找到了我,希望把这篇文章删除掉。经过一番沟通我先把这篇文章从公号中删除了...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《Oracle Java SE编程自学与面试指南》最佳学习路线图2020年最新版(进大厂必备)

正确选择比瞎努力更重要!

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

字节跳动面试官竟然问了我JDBC?

轻松等回家通知

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

阿里面试官让我用Zk(Zookeeper)实现分布式锁

他可能没想到,我当场手写出来了

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

2020春招面试了10多家大厂,我把问烂了的数据库事务知识点总结了一下

2020年截止目前,我面试了阿里巴巴、腾讯、美团、拼多多、京东、快手等互联网大厂。我发现数据库事务在面试中出现的次数非常多。

爬虫(101)爬点重口味的

小弟最近在学校无聊的很哪,浏览网页突然看到一张图片,都快流鼻血。。。然后小弟冥思苦想,得干一点有趣的事情python 爬虫库安装https://s.taobao.com/api?_ks...

在拼多多上班,是一种什么样的体验?我心态崩了呀!

之前有很多读者咨询我:武哥,在拼多多上班是一种什么样的体验?由于一直很忙,没抽出时间来和大家分享。上周末特地花点时间来写了一篇文章,跟大家分享一下拼多多的日常。 1. 倒时差的作息 可能很多小伙伴都听说了,拼多多加班很严重。这怎么说呢?作息上确实和其他公司有点区别,大家知道 996,那么自然也就能理解拼多多的“11 11 6”了。 所以当很多小伙伴早上出门时,他们是这样的: 我们是这样的: 当...

应聘3万的职位,有必要这么刁难我么。。。沙雕。。。

又一次被面试官带到坑里面了。面试官:springmvc用过么?我:用过啊,经常用呢面试官:springmvc中为什么需要用父子容器?我:嗯。。。没听明白你说的什么。面试官:就是contr...

太狠了,疫情期间面试,一个问题砍了我5000!

疫情期间找工作确实有点难度,想拿到满意的薪资,确实要点实力啊!面试官:Spring中的@Value用过么,介绍一下我:@Value可以标注在字段上面,可以将外部配置文件中的数据,比如可以...

自学编程的 6 个致命误区

嗨,小伙伴们大家好,我是沉默王二。本篇文章来和大家聊聊自学编程中的一些误区——这是我在 B 站上看了羊哥的一期视频后有感而发的文章。因为确实有很多读者也曾私信问过我这些方面的问题,很有代表性,所以我就结合自己的亲身体会来谈一谈,希望对小伙伴们有所启发。 01、追求时髦 所谓基础不牢,地动山摇啊。可很多小伙伴压根就没注意过这个问题,市面上出什么新鲜的技术就想去尝试,结果把自己学的乱七八糟,心灰意冷...

漫画:什么是 “眼镜蛇效应” ?

世界是复杂的。每当你做出一个决定的时候,你的出发点通常是好的,但结果一定会好吗?在印度的某个地区,当地野生的眼镜蛇非常泛滥。众所周知,眼镜蛇有剧毒,又具有很强的攻击性,给当地居民的生命安...

大海啊,夏天啊,全是腿啊,python带你爬取长腿妹子图

知乎还是很友好的 总体来说没啥难度 简单说下思路 1.评论是动态加载的 直接找json接口 2.分析接口参数,我测试的时候一次最多能拿20条数据(不过我还是一条一条拿的) 3.循环发送请求,其实可以先把评论数抓下来再for range 我只是比较懒(。・ω・。) 4.有的评论没图片,简单try一下或者if处理 首先需要引入爬虫库 import requests from bs4 import Be...

【相亲】95年高颜值妹子,喜欢上进的男生

颜值有点高,条件有点好

汉字不能编程?别闹了,只是看着有点豪横!容易被开除!

作者:小傅哥 博客:https://bugstack.cn 沉淀、分享、成长,让自己和他人都能有所收获! 一、前言 在编程的路上你是否想过,用汉字写一写代码? 最近有初学编程的小伙伴问小傅哥,汉字可以写代码吗。自己英文不好,要是汉字可以写代码就好了。难道你要的是易语言?其实并不是,小伙伴也是学习 Java 的初学者,刚刚学习到 Spring 看着一片没有注释的代码实在不好理解,要是都是汉字写...

立即提问
相关内容推荐