前端技术
HTML
CSS
Javascript
前端框架和UI库
VUE
ReactJS
AngularJS
JQuery
NodeJS
JSON
Element-UI
Bootstrap
Material UI
服务端和客户端
Java
Python
PHP
Golang
Scala
Kotlin
Groovy
Ruby
Lua
.net
c#
c++
后端WEB和工程框架
SpringBoot
SpringCloud
Struts2
MyBatis
Hibernate
Tornado
Beego
Go-Spring
Go Gin
Go Iris
Dubbo
HessianRPC
Maven
Gradle
数据库
MySQL
Oracle
Mongo
中间件与web容器
Redis
MemCache
Etcd
Cassandra
Kafka
RabbitMQ
RocketMQ
ActiveMQ
Nacos
Consul
Tomcat
Nginx
Netty
大数据技术
Hive
Impala
ClickHouse
DorisDB
Greenplum
PostgreSQL
HBase
Kylin
Hadoop
Apache Pig
ZooKeeper
SeaTunnel
Sqoop
Datax
Flink
Spark
Mahout
数据搜索与日志
ElasticSearch
Apache Lucene
Apache Solr
Kibana
Logstash
数据可视化与OLAP
Apache Atlas
Superset
Saiku
Tesseract
系统与容器
Linux
Shell
Docker
Kubernetes
[split]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
转载文章
...ID = t._2.split("\t")[2];return new Tuple2<String, Tuple2<String,String>>(userID, t);} });JavaPairRDD<String, Tuple2<Tuple2<String, String>, Optional<Boolean>>> joined = rdd2Pair.leftOuterJoin(blackListRDD);JavaPairRDD<String, String> result = joined.filter(new Function<Tuple2<String,Tuple2<Tuple2<String,String>,Optional<Boolean>>>, Boolean>() {public Boolean call(Tuple2<String, Tuple2<Tuple2<String, String>, Optional<Boolean>>> tuple)throws Exception {// TODO Auto-generated method stubOptional<Boolean> optional = tuple._2._2;if(optional.isPresent() && optional.get()){return false;} else {return true;} }}).mapToPair(new PairFunction<Tuple2<String,Tuple2<Tuple2<String,String>,Optional<Boolean>>>, String, String>() {public Tuple2<String, String> call(Tuple2<String, Tuple2<Tuple2<String, String>, Optional<Boolean>>> t)throws Exception {// TODO Auto-generated method stubreturn t._2._1;} });return result;} });//广告点击的基本数据格式:timestamp、ip、userID、adID、province、cityJavaPairDStream<String, Long> pairs = filteredadClickedStreaming.mapToPair(new PairFunction<Tuple2<String,String>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, String> t) throws Exception {String[] splited=t._2.split("\t");String timestamp = splited[0]; //YYYY-MM-DDString ip = splited[1];String userID = splited[2];String adID = splited[3];String province = splited[4];String city = splited[5]; String clickedRecord = timestamp + "_" +ip + "_"+userID+"_"+adID+"_"+province +"_"+city;return new Tuple2<String, Long>(clickedRecord, 1L);} });/ 第4.3步:在单词实例计数为1基础上,统计每个单词在文件中出现的总次数/JavaPairDStream<String, Long> adClickedUsers= pairs.reduceByKey(new Function2<Long, Long, Long>() {public Long call(Long i1, Long i2) throws Exception{return i1 + i2;} });/判断有效的点击,复杂化的采用机器学习训练模型进行在线过滤 简单的根据ip判断1天不超过100次;也可以通过一个batch duration的点击次数判断是否非法广告点击,通过一个batch来判断是不完整的,还需要一天的数据也可以每一个小时来判断。/JavaPairDStream<String, Long> filterClickedBatch = adClickedUsers.filter(new Function<Tuple2<String,Long>, Boolean>() {public Boolean call(Tuple2<String, Long> v1) throws Exception {if (1 < v1._2){//更新一些黑名单的数据库表return false;} else { return true;} }});//filterClickedBatch.print();//写入数据库filterClickedBatch.foreachRDD(new Function<JavaPairRDD<String,Long>, Void>() {public Void call(JavaPairRDD<String, Long> rdd) throws Exception {rdd.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Long>>>() {public void call(Iterator<Tuple2<String, Long>> partition) throws Exception {//使用数据库连接池的高效读写数据库的方式将数据写入数据库mysql//例如一次插入 1000条 records,使用insertBatch 或 updateBatch//插入的用户数据信息:userID,adID,clickedCount,time//这里面有一个问题,可能出现两条记录的key是一样的,此时需要更新累加操作List<UserAdClicked> userAdClickedList = new ArrayList<UserAdClicked>();while(partition.hasNext()) {Tuple2<String, Long> record = partition.next();String[] splited = record._1.split("\t");UserAdClicked userClicked = new UserAdClicked();userClicked.setTimestamp(splited[0]);userClicked.setIp(splited[1]);userClicked.setUserID(splited[2]);userClicked.setAdID(splited[3]);userClicked.setProvince(splited[4]);userClicked.setCity(splited[5]);userAdClickedList.add(userClicked);}final List<UserAdClicked> inserting = new ArrayList<UserAdClicked>();final List<UserAdClicked> updating = new ArrayList<UserAdClicked>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();//表的字段timestamp、ip、userID、adID、province、city、clickedCountfor(final UserAdClicked clicked : userAdClickedList) {jdbcWrapper.doQuery("SELECT clickedCount FROM adclicked WHERE"+ " timestamp =? AND userID = ? AND adID = ?",new Object[]{clicked.getTimestamp(), clicked.getUserID(),clicked.getAdID()}, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {// TODO Auto-generated method stubif(result.next()) {long count = result.getLong(1);clicked.setClickedCount(count);updating.add(clicked);} else {inserting.add(clicked);clicked.setClickedCount(1L);} }});}//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(UserAdClicked insertRecord : inserting) {insertParametersList.add(new Object[] {insertRecord.getTimestamp(),insertRecord.getIp(),insertRecord.getUserID(),insertRecord.getAdID(),insertRecord.getProvince(),insertRecord.getCity(),insertRecord.getClickedCount()});}jdbcWrapper.doBatch("INSERT INTO adclicked VALUES(?, ?, ?, ?, ?, ?, ?)", insertParametersList);//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> updateParametersList = new ArrayList<Object[]>();for(UserAdClicked updateRecord : updating) {updateParametersList.add(new Object[] {updateRecord.getTimestamp(),updateRecord.getIp(),updateRecord.getUserID(),updateRecord.getAdID(),updateRecord.getProvince(),updateRecord.getCity(),updateRecord.getClickedCount() + 1});}jdbcWrapper.doBatch("UPDATE adclicked SET clickedCount = ? WHERE"+ " timestamp =? AND ip = ? AND userID = ? AND adID = ? "+ "AND province = ? AND city = ?", updateParametersList);} });return null;} });//再次过滤,从数据库中读取数据过滤黑名单JavaPairDStream<String, Long> blackListBasedOnHistory = filterClickedBatch.filter(new Function<Tuple2<String,Long>, Boolean>() {public Boolean call(Tuple2<String, Long> v1) throws Exception {//广告点击的基本数据格式:timestamp,ip,userID,adID,province,cityString[] splited = v1._1.split("\t"); //提取key值String date =splited[0];String userID =splited[2];String adID =splited[3];//查询一下数据库同一个用户同一个广告id点击量超过50次列入黑名单//接下来 根据date、userID、adID条件去查询用户点击广告的数据表,获得总的点击次数//这个时候基于点击次数判断是否属于黑名单点击int clickedCountTotalToday = 81 ;if (clickedCountTotalToday > 50) {return true;}else {return false ;} }});//map操作,找出用户的idJavaDStream<String> blackListuserIDBasedInBatchOnhistroy =blackListBasedOnHistory.map(new Function<Tuple2<String,Long>, String>() {public String call(Tuple2<String, Long> v1) throws Exception {// TODO Auto-generated method stubreturn v1._1.split("\t")[2];} });//有一个问题,数据可能重复,在一个partition里面重复,这个好办;//但多个partition不能保证一个用户重复,需要对黑名单的整个rdd进行去重操作。//rdd去重了,partition也就去重了,一石二鸟,一箭双雕// 找出了黑名单,下一步就写入黑名单数据库表中JavaDStream<String> blackListUniqueuserBasedInBatchOnhistroy = blackListuserIDBasedInBatchOnhistroy.transform(new Function<JavaRDD<String>, JavaRDD<String>>() {public JavaRDD<String> call(JavaRDD<String> rdd) throws Exception {// TODO Auto-generated method stubreturn rdd.distinct();} });// 下一步写入到数据表中blackListUniqueuserBasedInBatchOnhistroy.foreachRDD(new Function<JavaRDD<String>, Void>() {public Void call(JavaRDD<String> rdd) throws Exception {rdd.foreachPartition(new VoidFunction<Iterator<String>>() {public void call(Iterator<String> t) throws Exception {// TODO Auto-generated method stub//插入的用户信息可以只包含:useID//此时直接插入黑名单数据表即可。//写入数据库List<Object[]> blackList = new ArrayList<Object[]>();while(t.hasNext()) {blackList.add(new Object[]{t.next()});}JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();jdbcWrapper.doBatch("INSERT INTO blacklisttable values (?)", blackList);} });return null;} });/广告点击累计动态更新,每个updateStateByKey都会在Batch Duration的时间间隔的基础上进行广告点击次数的更新, 更新之后我们一般都会持久化到外部存储设备上,在这里我们存储到MySQL数据库中/JavaPairDStream<String, Long> updateStateByKeyDSteam = filteredadClickedStreaming.mapToPair(new PairFunction<Tuple2<String,String>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, String> t)throws Exception {String[] splited=t._2.split("\t");String timestamp = splited[0]; //YYYY-MM-DDString ip = splited[1];String userID = splited[2];String adID = splited[3];String province = splited[4];String city = splited[5]; String clickedRecord = timestamp + "_" +ip + "_"+userID+"_"+adID+"_"+province +"_"+city;return new Tuple2<String, Long>(clickedRecord, 1L);} }).updateStateByKey(new Function2<List<Long>, Optional<Long>, Optional<Long>>() {public Optional<Long> call(List<Long> v1, Optional<Long> v2)throws Exception {// v1:当前的Key在当前的Batch Duration中出现的次数的集合,例如{1,1,1,。。。,1}// v2:当前的Key在以前的Batch Duration中积累下来的结果;Long clickedTotalHistory = 0L; if(v2.isPresent()){clickedTotalHistory = v2.get();}for(Long one : v1) {clickedTotalHistory += one;}return Optional.of(clickedTotalHistory);} });updateStateByKeyDSteam.foreachRDD(new Function<JavaPairRDD<String,Long>, Void>() {public Void call(JavaPairRDD<String, Long> rdd) throws Exception {rdd.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Long>>>() {public void call(Iterator<Tuple2<String, Long>> partition) throws Exception {//使用数据库连接池的高效读写数据库的方式将数据写入数据库mysql//例如一次插入 1000条 records,使用insertBatch 或 updateBatch//插入的用户数据信息:timestamp、adID、province、city//这里面有一个问题,可能出现两条记录的key是一样的,此时需要更新累加操作List<AdClicked> AdClickedList = new ArrayList<AdClicked>();while(partition.hasNext()) {Tuple2<String, Long> record = partition.next();String[] splited = record._1.split("\t");AdClicked adClicked = new AdClicked();adClicked.setTimestamp(splited[0]);adClicked.setAdID(splited[1]);adClicked.setProvince(splited[2]);adClicked.setCity(splited[3]);adClicked.setClickedCount(record._2);AdClickedList.add(adClicked);}final List<AdClicked> inserting = new ArrayList<AdClicked>();final List<AdClicked> updating = new ArrayList<AdClicked>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();//表的字段timestamp、ip、userID、adID、province、city、clickedCountfor(final AdClicked clicked : AdClickedList) {jdbcWrapper.doQuery("SELECT clickedCount FROM adclickedcount WHERE"+ " timestamp = ? AND adID = ? AND province = ? AND city = ?",new Object[]{clicked.getTimestamp(), clicked.getAdID(),clicked.getProvince(), clicked.getCity()}, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {// TODO Auto-generated method stubif(result.next()) {long count = result.getLong(1);clicked.setClickedCount(count);updating.add(clicked);} else {inserting.add(clicked);clicked.setClickedCount(1L);} }});}//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(AdClicked insertRecord : inserting) {insertParametersList.add(new Object[] {insertRecord.getTimestamp(),insertRecord.getAdID(),insertRecord.getProvince(),insertRecord.getCity(),insertRecord.getClickedCount()});}jdbcWrapper.doBatch("INSERT INTO adclickedcount VALUES(?, ?, ?, ?, ?)", insertParametersList);//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> updateParametersList = new ArrayList<Object[]>();for(AdClicked updateRecord : updating) {updateParametersList.add(new Object[] {updateRecord.getClickedCount(),updateRecord.getTimestamp(),updateRecord.getAdID(),updateRecord.getProvince(),updateRecord.getCity()});}jdbcWrapper.doBatch("UPDATE adclickedcount SET clickedCount = ? WHERE"+ " timestamp =? AND adID = ? AND province = ? AND city = ?", updateParametersList);} });return null;} });/ 对广告点击进行TopN计算,计算出每天每个省份Top5排名的广告 因为我们直接对RDD进行操作,所以使用了transfomr算子;/updateStateByKeyDSteam.transform(new Function<JavaPairRDD<String,Long>, JavaRDD<Row>>() {public JavaRDD<Row> call(JavaPairRDD<String, Long> rdd) throws Exception {JavaRDD<Row> rowRDD = rdd.mapToPair(new PairFunction<Tuple2<String,Long>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, Long> t)throws Exception {// TODO Auto-generated method stubString[] splited=t._1.split("_");String timestamp = splited[0]; //YYYY-MM-DDString adID = splited[3];String province = splited[4];String clickedRecord = timestamp + "_" + adID + "_" + province;return new Tuple2<String, Long>(clickedRecord, t._2);} }).reduceByKey(new Function2<Long, Long, Long>() {public Long call(Long v1, Long v2) throws Exception {// TODO Auto-generated method stubreturn v1 + v2;} }).map(new Function<Tuple2<String,Long>, Row>() {public Row call(Tuple2<String, Long> v1) throws Exception {// TODO Auto-generated method stubString[] splited=v1._1.split("_");String timestamp = splited[0]; //YYYY-MM-DDString adID = splited[3];String province = splited[4];return RowFactory.create(timestamp, adID, province, v1._2);} });StructType structType = DataTypes.createStructType(Arrays.asList(DataTypes.createStructField("timestamp", DataTypes.StringType, true),DataTypes.createStructField("adID", DataTypes.StringType, true),DataTypes.createStructField("province", DataTypes.StringType, true),DataTypes.createStructField("clickedCount", DataTypes.LongType, true)));HiveContext hiveContext = new HiveContext(rdd.context());DataFrame df = hiveContext.createDataFrame(rowRDD, structType);df.registerTempTable("topNTableSource");DataFrame result = hiveContext.sql("SELECT timestamp, adID, province, clickedCount, FROM"+ " (SELECT timestamp, adID, province,clickedCount, "+ "ROW_NUMBER() OVER(PARTITION BY province ORDER BY clickeCount DESC) rank "+ "FROM topNTableSource) subquery "+ "WHERE rank <= 5");return result.toJavaRDD();} }).foreachRDD(new Function<JavaRDD<Row>, Void>() {public Void call(JavaRDD<Row> rdd) throws Exception {// TODO Auto-generated method stubrdd.foreachPartition(new VoidFunction<Iterator<Row>>() {public void call(Iterator<Row> t) throws Exception {// TODO Auto-generated method stubList<AdProvinceTopN> adProvinceTopN = new ArrayList<AdProvinceTopN>();while(t.hasNext()) {Row row = t.next();AdProvinceTopN item = new AdProvinceTopN();item.setTimestamp(row.getString(0));item.setAdID(row.getString(1));item.setProvince(row.getString(2));item.setClickedCount(row.getLong(3));adProvinceTopN.add(item);}// final List<AdProvinceTopN> inserting = new ArrayList<AdProvinceTopN>();// final List<AdProvinceTopN> updating = new ArrayList<AdProvinceTopN>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();Set<String> set = new HashSet<String>();for(AdProvinceTopN item: adProvinceTopN){set.add(item.getTimestamp() + "_" + item.getProvince());}//表的字段timestamp、adID、province、clickedCountArrayList<Object[]> deleteParametersList = new ArrayList<Object[]>();for(String deleteRecord : set) {String[] splited = deleteRecord.split("_");deleteParametersList.add(new Object[]{splited[0],splited[1]});}jdbcWrapper.doBatch("DELETE FROM adprovincetopn WHERE timestamp = ? AND province = ?", deleteParametersList);//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(AdProvinceTopN insertRecord : adProvinceTopN) {insertParametersList.add(new Object[] {insertRecord.getClickedCount(),insertRecord.getTimestamp(),insertRecord.getAdID(),insertRecord.getProvince()});}jdbcWrapper.doBatch("INSERT INTO adprovincetopn VALUES (?, ?, ?, ?)", insertParametersList);} });return null;} });/ 计算过去半个小时内广告点击的趋势 广告点击的基本数据格式:timestamp、ip、userID、adID、province、city/filteredadClickedStreaming.mapToPair(new PairFunction<Tuple2<String,String>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, String> t)throws Exception {String splited[] = t._2.split("\t");String adID = splited[3];String time = splited[0]; //Todo:后续需要重构代码实现时间戳和分钟的转换提取。此处需要提取出该广告的点击分钟单位return new Tuple2<String, Long>(time + "_" + adID, 1L);} }).reduceByKeyAndWindow(new Function2<Long, Long, Long>() {public Long call(Long v1, Long v2) throws Exception {// TODO Auto-generated method stubreturn v1 + v2;} }, new Function2<Long, Long, Long>() {public Long call(Long v1, Long v2) throws Exception {// TODO Auto-generated method stubreturn v1 - v2;} }, Durations.minutes(30), Durations.milliseconds(5)).foreachRDD(new Function<JavaPairRDD<String,Long>, Void>() {public Void call(JavaPairRDD<String, Long> rdd) throws Exception {// TODO Auto-generated method stubrdd.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Long>>>() {public void call(Iterator<Tuple2<String, Long>> partition)throws Exception {List<AdTrendStat> adTrend = new ArrayList<AdTrendStat>();// TODO Auto-generated method stubwhile(partition.hasNext()) {Tuple2<String, Long> record = partition.next();String[] splited = record._1.split("_");String time = splited[0];String adID = splited[1];Long clickedCount = record._2;/ 在插入数据到数据库的时候具体需要哪些字段?time、adID、clickedCount; 而我们通过J2EE技术进行趋势绘图的时候肯定是需要年、月、日、时、分这个维度的,所以我们在这里需要 年月日、小时、分钟这些时间维度;/AdTrendStat adTrendStat = new AdTrendStat();adTrendStat.setAdID(adID);adTrendStat.setClickedCount(clickedCount);adTrendStat.set_date(time); //Todo:获取年月日adTrendStat.set_hour(time); //Todo:获取小时adTrendStat.set_minute(time);//Todo:获取分钟adTrend.add(adTrendStat);}final List<AdTrendStat> inserting = new ArrayList<AdTrendStat>();final List<AdTrendStat> updating = new ArrayList<AdTrendStat>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();//表的字段timestamp、ip、userID、adID、province、city、clickedCountfor(final AdTrendStat trend : adTrend) {final AdTrendCountHistory adTrendhistory = new AdTrendCountHistory();jdbcWrapper.doQuery("SELECT clickedCount FROM adclickedtrend WHERE"+ " date =? AND hour = ? AND minute = ? AND AdID = ?",new Object[]{trend.get_date(), trend.get_hour(), trend.get_minute(),trend.getAdID()}, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {// TODO Auto-generated method stubif(result.next()) {long count = result.getLong(1);adTrendhistory.setClickedCountHistoryLong(count);updating.add(trend);} else { inserting.add(trend);} }});}//表的字段date、hour、minute、adID、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(AdTrendStat insertRecord : inserting) {insertParametersList.add(new Object[] {insertRecord.get_date(),insertRecord.get_hour(),insertRecord.get_minute(),insertRecord.getAdID(),insertRecord.getClickedCount()});}jdbcWrapper.doBatch("INSERT INTO adclickedtrend VALUES(?, ?, ?, ?, ?)", insertParametersList);//表的字段date、hour、minute、adID、clickedCountList<Object[]> updateParametersList = new ArrayList<Object[]>();for(AdTrendStat updateRecord : updating) {updateParametersList.add(new Object[] {updateRecord.getClickedCount(),updateRecord.get_date(),updateRecord.get_hour(),updateRecord.get_minute(),updateRecord.getAdID()});}jdbcWrapper.doBatch("UPDATE adclickedtrend SET clickedCount = ? WHERE"+ " date =? AND hour = ? AND minute = ? AND AdID = ?", updateParametersList);} });return null;} });;/ Spark Streaming 执行引擎也就是Driver开始运行,Driver启动的时候是位于一条新的线程中的,当然其内部有消息循环体,用于 接收应用程序本身或者Executor中的消息,/javassc.start();javassc.awaitTermination();javassc.close();}private static JavaStreamingContext createContext(String checkpointDirectory, SparkConf conf) {// If you do not see this printed, that means the StreamingContext has been loaded// from the new checkpointSystem.out.println("Creating new context");// Create the context with a 5 second batch sizeJavaStreamingContext ssc = new JavaStreamingContext(conf, Durations.seconds(10));ssc.checkpoint(checkpointDirectory);return ssc;} }class JDBCWrapper {private static JDBCWrapper jdbcInstance = null;private static LinkedBlockingQueue<Connection> dbConnectionPool = new LinkedBlockingQueue<Connection>();static {try {Class.forName("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} }public static JDBCWrapper getJDBCInstance() {if(jdbcInstance == null) {synchronized (JDBCWrapper.class) {if(jdbcInstance == null) {jdbcInstance = new JDBCWrapper();} }}return jdbcInstance; }private JDBCWrapper() {for(int i = 0; i < 10; i++){try {Connection conn = DriverManager.getConnection("jdbc:mysql://Master:3306/sparkstreaming","root", "root");dbConnectionPool.put(conn);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} } }public synchronized Connection getConnection() {while(0 == dbConnectionPool.size()){try {Thread.sleep(20);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }return dbConnectionPool.poll();}public int[] doBatch(String sqlText, List<Object[]> paramsList){Connection conn = getConnection();PreparedStatement preparedStatement = null;int[] result = null;try {conn.setAutoCommit(false);preparedStatement = conn.prepareStatement(sqlText);for(Object[] parameters: paramsList) {for(int i = 0; i < parameters.length; i++){preparedStatement.setObject(i + 1, parameters[i]);} preparedStatement.addBatch();}result = preparedStatement.executeBatch();conn.commit();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if(preparedStatement != null) {try {preparedStatement.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} }if(conn != null) {try {dbConnectionPool.put(conn);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }}return result; }public void doQuery(String sqlText, Object[] paramsList, ExecuteCallBack callback){Connection conn = getConnection();PreparedStatement preparedStatement = null;ResultSet result = null;try {preparedStatement = conn.prepareStatement(sqlText);for(int i = 0; i < paramsList.length; i++){preparedStatement.setObject(i + 1, paramsList[i]);} result = preparedStatement.executeQuery();try {callback.resultCallBack(result);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} } catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if(preparedStatement != null) {try {preparedStatement.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} }if(conn != null) {try {dbConnectionPool.put(conn);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }} }}interface ExecuteCallBack {void resultCallBack(ResultSet result) throws Exception;}class UserAdClicked {private String timestamp;private String ip;private String userID;private String adID;private String province;private String city;private Long clickedCount;public String getTimestamp() {return timestamp;}public void setTimestamp(String timestamp) {this.timestamp = timestamp;}public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public String getUserID() {return userID;}public void setUserID(String userID) {this.userID = userID;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdClicked {private String timestamp;private String adID;private String province;private String city;private Long clickedCount;public String getTimestamp() {return timestamp;}public void setTimestamp(String timestamp) {this.timestamp = timestamp;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdProvinceTopN {private String timestamp;private String adID;private String province;private Long clickedCount;public String getTimestamp() {return timestamp;}public void setTimestamp(String timestamp) {this.timestamp = timestamp;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdTrendStat {private String _date;private String _hour;private String _minute;private String adID;private Long clickedCount;public String get_date() {return _date;}public void set_date(String _date) {this._date = _date;}public String get_hour() {return _hour;}public void set_hour(String _hour) {this._hour = _hour;}public String get_minute() {return _minute;}public void set_minute(String _minute) {this._minute = _minute;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdTrendCountHistory{private Long clickedCountHistoryLong;public Long getClickedCountHistoryLong() {return clickedCountHistoryLong;}public void setClickedCountHistoryLong(Long clickedCountHistoryLong) {this.clickedCountHistoryLong = clickedCountHistoryLong;} } 本篇文章为转载内容。原文链接:https://blog.csdn.net/tom_8899_li/article/details/71194434。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-02-14 19:16:35
297
转载
转载文章
...rint(name.split()) 默认分隔符为空格,返回值为一个列表 print(name.split('o')) split 可以指定分隔符的位置 demo = 'a/b/c/d/e' print(demo.split('/',1)) ['a', 'b/c/d/e'] print(demo.split('/',2)) ['a', 'b', 'c/d/e'] rsplit 可以指定从右边切分 print(demo.rsplit('/',1)) ['a/b/c/d', 'e'] print(name) 注意看name的值 join 拼接字符串 name = ' ' print(name.join(['wang','cong'])) 必须为可迭代对象 注意join和 + 的不同 name = '' print(name.join(['w','a','n','g'])) wang print(name + 'wang' + 'cong') wangcong print(name) 注意看name的值 replace 字符串替换 name = 'wang ' print(name.replace('','cong')) wang cong 注意这里是全部替换 name = 'wang ' print(name.replace('','cong')) wang congcongcongcongcong print(name) 注意看name的值 find,rfind,index,rindex,count str1 = 'hello world' print(str1.find('l')) 返回第一个'l'的索引值 print(str1.find('b')) 找不到返回-1 print(str1.find('l',3,5)) 顾头不顾尾 rfind:从右边开始查找 index,rindex 同find,rfind 只不过找不到的时候不报错 count :统计字母出现的次数 print(str1.count('l',1,4)) 顾头不顾尾,如果不指定范围则查找所有 一些转义字符 \(在末尾时):续行符 ;\\:反斜杠 \n :换行 ;\t :横向制表符 ;\':单引号;\":双引号 字符串格式化符号 %c:格式化字符以及其ASCII码 print("%c"%89) Y print("%c"%'Y') Y %s:格式化字符串 print("%s" %"wang cong") wang cong %d 格式化整数 number = 87 print("%d" % number) 87 %u 格式化无符号整型 %o 格式化无符号八进制数 print("%o" % number) 1X27:八进制数显示 %x 格式化无符号十六进制数 (小写) number = 15 print("%x" % number) f %X 格式化无符号十六进制数 (大写) print("%X" % number) F 转载于:https://www.cnblogs.com/cong12586/p/11349697.html 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_38168760/article/details/102271589。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-05-11 17:43:10
353
转载
转载文章
...=old_info.split("_www.achome.cn_"); for(var j=0;j<=5;j++) { if(old_link[j].indexOf(linkname)!=-1) insert=false; if(old_link[j]=="null") break; } } if(insert) { wlink+=getCookie("history_info"); setCookie("history_info",wlink); //写入cookie,该函数后面有声明 history_show().reload(); break; } } srcElem = srcElem.parentNode; } } catch(e){} return true; } document.οnclick=glog;//使每一次页面的点击动作都执行glog函数 第2部分:Cookies的相关函数 复制内容到剪贴板 代码: //cookie的相关函数 //读取cookie中指定的内容 function getCookieVal (offset) { var endstr = document.cookie.indexOf (";", offset); if (endstr == -1) endstr = document.cookie.length; return unescape(document.cookie.substring(offset, endstr)); } function getCookie (name) { var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (document.cookie.substring(i, j) == arg) return getCookieVal (j); i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break; } return null; } //将浏览动作写入cookie function setCookie (name, value) { var exp = new Date(); exp.setTime (exp.getTime()+3600000000); document.cookie = name + "=" + value + "; expires=" + exp.toGMTString(); } 第3部分:页面显示函数 复制内容到剪贴板 代码: function history_show() { var history_info=getCookie("history_info"); //取出cookie中的历史记录 var content=""; //定义一个显示变量 if(history_info!=null) { history_arg=history_info.split("_www.achome.cn_"); var i; for(i=0;i<=5;i++) { if(history_arg[i]!="null") { var wlink=history_arg[i].split("+"); content+=("↑"+""+wlink[0]+" "); } document.getElementById("history").innerHTML=content; } } else {document.getElementById("history").innerHTML="对不起,您没有任何浏览纪录";} } 代码差不多就是这些了 就为大家分析到这里 还有不足之处还请大家多多指教 下面可以运行代码查看效果 查看效果 //cookie的相关函数 function getCookieVal (offset) { var endstr = document.cookie.indexOf (";", offset); if (endstr == -1) endstr = document.cookie.length; return unescape(document.cookie.substring(offset, endstr)); } function getCookie (name) { var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (document.cookie.substring(i, j) == arg) return getCookieVal (j); i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break; } return null; } function setCookie (name, value) { var exp = new Date(); exp.setTime (exp.getTime()+3600000000); document.cookie = name + "=" + value + "; expires=" + exp.toGMTString(); } function glog(evt) { evt=evt?evt:window.event;var srcElem=(evt.target)?evt.target:evt.srcElement; try { while(srcElem.parentNode&&srcElem!=srcElem.parentNode) { if(srcElem.tagName&&srcElem.tagName.toUpperCase()=="A") { linkname=srcElem.innerHTML; address=srcElem.href+"_www.achome.cn_"; wlink=linkname+"+"+address; old_info=getCookie("history_info"); var insert=true; if(old_info==null) //判断cookie是否为空 { insert=true; } else { var old_link=old_info.split("_www.achome.cn_"); for(var j=0;j<=5;j++) { if(old_link[j].indexOf(linkname)!=-1) insert=false; if(old_link[j]=="null") break; } } / if(insert) //如果符合条件则重新写入数据 { wlink+=getCookie("history_info"); setCookie("history_info",wlink); history_show().reload(); break; } } srcElem = srcElem.parentNode; } } catch(e){} return true; } document.οnclick=glog; function history_show() { var history_info=getCookie("history_info"); var content=""; if(history_info!=null) { history_arg=history_info.split("_www.achome.cn_"); var i; for(i=0;i<=5;i++) { if(history_arg[i]!="null") { var wlink=history_arg[i].split("+"); content+=("↑"+""+wlink[0]+" "); } document.getElementById("history").innerHTML=content; } } else {document.getElementById("history").innerHTML="对不起,您没有任何浏览纪录";} } // JavaScript Document 浏览历史排行(只显示6个最近访问站点并且没有重复的站点出现) history_show(); 点击链接: 网站1 网站2 网站3 网站4 网站5 网站6 网站7 网站8 网站9 如果有其他疑问请登陆www.achome.cn与我联系 提示:您可以先修改部分代码再运行 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_30611227/article/details/117818020。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-04-30 21:14:40
48
转载
转载文章
...n synsets]splits = [line.split(" ") for line in synsets]key_to_classname = {spl[0]: " ".join(spl[1:]) for spl in splits} class_url = "".join( [ "https://raw.githubusercontent.com/Cadene/", "pretrained-models.pytorch/master/data/", "imagenet_classes.txt", ] ) class_name = "imagenet_classes.txt" class_path = download_testdata(class_url, class_name, module="data") https://raw.githubusercontent.com/Cadene/pretrained-models.pytorch/master/data/imagenet_classes.txtclass_path = 'imagenet_classes.txt'with open(class_path) as f:class_id_to_key = f.readlines()class_id_to_key = [x.strip() for x in class_id_to_key] Get top-1 result for TVMtop1_tvm = np.argmax(tvm_output.numpy()[0])tvm_class_key = class_id_to_key[top1_tvm] Convert input to PyTorch variable and get PyTorch result for comparisonwith torch.no_grad():torch_img = torch.from_numpy(img)output = model(torch_img) Get top-1 result for PyTorchtop1_torch = np.argmax(output.numpy())torch_class_key = class_id_to_key[top1_torch]print("Relay top-1 id: {}, class name: {}".format(top1_tvm, key_to_classname[tvm_class_key]))print("Torch top-1 id: {}, class name: {}".format(top1_torch, key_to_classname[torch_class_key])) 2. 配置vscode 安装两个vscode远程连接所需的两个插件,具体如下图所示: 安装完成之后,在左侧工具栏会出现一个图标,点击图标进行ssh配置: ssh yourname@yourip -A 然后右键选择在当前窗口进行连接: 除此之外,还可以设置免费登录,具体可参考这篇文章。 当然,也可以使用windows本地的WSL2,vscode连接WSL还需要安装WSL和Dev Containers这两个插件。 在服务器端执行code .会自动安装vscode server,安装位置在用户的根目录下: 3. 安装FFI Navigator 由于TVM是由Python和C++混合开发,且大多数的IDE仅支持在同一种语言中查找函数定义,因此对于跨语言的FFI 调用,即Python跳转到C++或者C++跳转到Python,vscode是做不到的。虽然解决这个问题在技术上可能非常具有挑战性,但我们可以通过构建一个与FFI注册码模式匹配并恢复必要信息的项目特定分析器来解决这个问题,FFI Navigator就这样诞生了,作者仍然是陈天奇博士。 安装方式如下: 建议使用源码安装git clone https://github.com/tqchen/ffi-navigator.git 安装python依赖cd ffi-navigator/pythonpython setyp.py install vscode需要安装FFI Navigator插件,直接搜索安装即可(安装到服务器端)。 最后需要在.vscode/setting.json进行配置,内容如下: {"python.analysis.extraPaths": ["${workspaceFolder}/python"], // 添加额外导入路径, 告诉pylance自定义的python库在哪里"ffi_navigator.pythonpath": "/home/liyanpeng/anaconda3/envs/tvmenv/bin/python", // 配置FFI Navigator"python.defaultInterpreterPath": "/home/liyanpeng/anaconda3/envs/tvmenv/bin/python","files.associations": {"type_traits": "cpp","fstream": "cpp","thread": "cpp",".tcc": "cpp"} } 更详细内容可以参考项目链接。 结束语 对于vscode的使用技巧及C/C++相关的配置,这里不再详细的介绍了,感兴趣的小伙伴们可以了解下。 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_42730750/article/details/126723224。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-12 20:04:26
87
转载
转载文章
... filename.split('_') name1 = test name2 = 001 name3 = 2.jpgname4, name5 = name3.split('.') name4 = 2 name5 = jpgif name5 == 'jpg' or name5 == 'png':try:os.mkdir(current_path+'/'+name4)print('成功建立文件夹:'+name4)except:passtry:shutil.move(current_path+'/'+filename, current_path+'/'+name4[:])print(filename+'转移成功!')except Exception as e:print('文件 %s 转移失败' % filename)print('转移错误原因:' + e)print('整理完毕!') 2.3 数据存在的缺陷 数据集内的图片数量很多,由于后面介绍的云端训练的限制,只能采用部分数据(本人采用的是1000张,大家可以自行增减数目)。 数据集为国外的数据集,很多数字写的跟我们不一样。如果想要更好的适用于我们国内的场景,可以对数据集进行手动的筛选。下面是他们写的数字2: 可以看出跟我们的不一样,不过数据集中仍然存在跟常规书写的一样的,我们需要进行人为的筛选。 2.4 优化建议(核心) 分析发现,部分数字精度不高的原因主要是国外手写很随意,我们可以通过调整网络参数(如下)、人为筛选数据(如上)、增大数据集等方式进行优化。 二、模型训练 主要参考文章:通过云端自动生成openmv的神经网络模型,进行目标检测 !!!唯一不同的点是我图像参数设置的是灰度而不是上述文章的RGB。 下面是我模型训练时的参数设置(仅供参考): 通过混淆矩阵可以看出,主要的错误在于数字2、6、8。我们可以通过查看识别错误的数字来分析可能的原因。 三、项目实现 !!!我们需要先将上述步骤中导出文件中的所有内容复制粘贴带OpenMV中自带的U盘中。然后将其中的.py文件名称改为main 1. 代码实现 本人修改后的完整代码展示如下,使用的是OpenMV IDE(官网下载): 数字识别后控制直流电机转速from pyb import Pin, Timerimport sensor, image, time, os, tf, math, random, lcd, uos, gc 根据识别的数字输出不同占比的PWM波def run(number):if inverse == True:ain1.low()ain2.high()else:ain1.high()ain2.low()ch1.pulse_width_percent(abs(number10)) 具体参数调整自行搜索sensor.reset() 初始化感光元件sensor.set_pixformat(sensor.GRAYSCALE) set_pixformat : 设置像素模式(GRAYSCALSE : 灰色; RGB565 : 彩色)sensor.set_framesize(sensor.QQVGA2) set_framesize : 设置处理图像的大小sensor.set_windowing((128, 160)) set_windowing : 设置提取区域大小sensor.skip_frames(time = 2000) skip_frames :跳过2000ms再读取图像lcd.init() 初始化lcd屏幕。inverse = False True : 电机反转 False : 电机正转ain1 = Pin('P1', Pin.OUT_PP) 引脚P1作为输出ain2 = Pin('P4', Pin.OUT_PP) 引脚P4作为输出ain1.low() P1初始化低电平ain2.low() P4初始化低电平tim = Timer(2, freq = 1000) 采用定时器2,频率为1000Hzch1 = tim.channel(4, Timer.PWM, pin = Pin('P5'), pulse_width_percent = 100) 输出通道1 配置PWM模式下的定时器(高电平有效) 端口为P5 初始占空比为100%clock = time.clock() 设置一个时钟用于追踪FPS 加载模型try:net = tf.load("trained.tflite", load_to_fb=uos.stat('trained.tflite')[6] > (gc.mem_free() - (641024)))except Exception as e:print(e)raise Exception('Failed to load "trained.tflite", did you copy the .tflite and labels.txt file onto the mass-storage device? (' + str(e) + ')') 加载标签try:labels = [line.rstrip('\n') for line in open("labels.txt")]except Exception as e:raise Exception('Failed to load "labels.txt", did you copy the .tflite and labels.txt file onto the mass-storage device? (' + str(e) + ')') 不断的进行运行while(True):clock.tick() 更新时钟img = sensor.snapshot().binary([(0,64)]) 抓取一张图像以灰度图显示lcd.display(img) 拍照并显示图像for obj in net.classify(img, min_scale=1.0, scale_mul=0.8, x_overlap=0.5, y_overlap=0.5): 初始化最大值和标签max_num = -1max_index = -1print("\nPredictions at [x=%d,y=%d,w=%d,h=%d]" % obj.rect())img.draw_rectangle(obj.rect()) 预测值和标签写成一个列表predictions_list = list(zip(labels, obj.output())) 输出各个标签的预测值,找到最大值进行输出for i in range(len(predictions_list)):print('%s 的概率为: %f' % (predictions_list[i][0], predictions_list[i][1]))if predictions_list[i][1] > max_num:max_num = predictions_list[i][1]max_index = int(predictions_list[i][0])run(max_index)print('该数字预测为:%d' % max_index)print('FPS为:', clock.fps())print('PWM波占空比为: %d%%' % (max_index10)) 2. 采用器件 使用的器件为OpenMV4 H7 Plus和L298N以及常用的直流电机。关键是找到器件的引脚图,再进行简单的连线即可。 参考文章:【L298N驱动模块学习笔记】–openmv驱动 参考文章:【openmv】原理图 引脚图 2. 注意事项 上述代码中我用到了lcd屏幕,主要是为了方便离机操作。使用过程中,OpenMV的lcd初始化时会重置端口,所有我们在输出PWM波的时候一定不要发生引脚冲突。我们可以在OpenMV官网查看lcd用到的端口: 可以看到上述用到的是P0、P2、P3、P6、P7和P8。所有我们输出PWM波时要避开这些端口。下面是OpenMV的PWM资源: 总结 本人第一次自己做东西也是第一次使用python,所以代码和项目写的都很粗糙,只是简单的识别数字控制直流电机。我也是四处借鉴修改后写下的大小,这篇文章主要是为了给那些像我一样的小白们提供一点帮助,减少大家查找资料的时间。模型的缺陷以及改进方法上述中已经说明,如果我有写错或者大家有更好的方法欢迎大家告诉我,大家一起进步! 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_57100435/article/details/130740351。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2024-01-10 08:44:41
282
转载
JQuery插件下载
...Query插件介绍 Split.js是一款专为网页开发者设计的可调节大小的拆分视图面板插件。这款插件的最大特点就是它完全基于纯JavaScript实现,不需要任何外部依赖,这使得它在加载速度和运行效率上具有明显的优势。Split.js拥有简洁明了的接口,使得用户能够轻松地创建各种复杂的布局结构。通过使用Split.js,开发者可以快速搭建出响应式的拆分视图或者分割面板,实现页面内容的灵活布局。插件提供了丰富的配置选项,允许用户根据实际需求调整面板的比例、尺寸以及间距等参数,以达到最佳的视觉效果。此外,Split.js还支持拖拽操作来动态改变面板的大小,极大地提升了用户体验。Split.js的设计理念在于简化开发流程,提高工作效率。无论是初学者还是经验丰富的开发者,都可以快速上手并充分利用其功能。这款插件适用于各种场景,如网站仪表盘、文件浏览器、图片编辑器等,为网页增添更多可能性。总之,Split.js凭借其强大的功能和易用性,在众多拆分视图插件中脱颖而出,成为网页开发者的理想选择。 点我下载 文件大小:19.85 KB 您将下载一个JQuery插件资源包,该资源包内部文件的目录结构如下: 本网站提供JQuery插件下载功能,旨在帮助广大用户在工作学习中提升效率、节约时间。 本网站的下载内容来自于互联网。如您发现任何侵犯您权益的内容,请立即告知我们,我们将迅速响应并删除相关内容。 免责声明:站内所有资源仅供个人学习研究及参考之用,严禁将这些资源应用于商业场景。 若擅自商用导致的一切后果,由使用者承担责任。
2025-01-11 11:00:06
649
本站
JQuery
...ou"; // 使用split方法按照逗号分隔字符串成数组 var arr = str.split(','); // 循环打印出数组的元素 for(var i = 0; i< arr.length; i++){ console.log(arr[i]); } 在上面的代码中,我们首先定义了一个字符串变量str,然后使用split方法将字符串按照逗号分隔成数组arr。接着使用循环遍历数组中的元素,并打印出每一个元素的值。通过执行上面的代码,控制台输出将会是以下内容: hello world how are you 可以看到,我们已经成功的按照逗号分隔了字符串,并将每一个元素转换成了数组中的元素。这种方法可以应用于任意的字符串分隔操作,只需要将split方法中的分隔符改成需要的字符即可。 以上就是使用jQuery按照指定字符分隔字符串的方法,希望对你有所帮助!
2023-12-16 18:58:28
409
逻辑鬼才
VUE
...s.message.split('').reverse().join('') } } }) 接下来是逻辑渲染, <div id="app"> <p 根据条件显示="显现">You can see me!</p> </div> var app = new Vue({ el: 'app', data: { 显现: true } }) 还有循环渲染, <div id="app"> <ul> <li 数组遍历渲染="item in 项目"> { { item } } </li> </ul> </div> var app = new Vue({ el: 'app', data: { 项目: ['Vue', 'React', 'Angular'] } }) 最后是事件响应, <div id="app"> <button v-on:敲击="次数 增加 1">Add 1</button> <p>You have 敲击ed the button { { 次数 } } times.</p> </div> var app = new Vue({ el: 'app', data: { 次数: 0 } }) 掌握vue要诀,按部就班逐步了解。
2023-04-23 13:30:02
69
算法侠
转载文章
...eError: e.split is not a function at view.umd.min.js:1 success:function(res){that.user_photo=res.tempFilePaths;//报错} 改为 success:function(res){that.user_photo=res.tempFilePaths[0];} 原因,通过 console.log(JSON.stringify(res.tempFilePaths)); 可知 16:31:14.617 ["_doc/uniapp_temp_1587198502520/compressed/1587198670833.jpeg"] at pages\my\user-set-info.vue:81 res.tempFilePaths为数组,所以当上传一张图片时,取得图片临时地址为res.tempFilePaths[0]; 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_41884068/article/details/105601975。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-03-05 15:38:13
59
转载
Java
... userData.split(":"); String username = userInfo[0]; String password = userInfo[1]; System.out.println("ID "+id+": username="+username+"\t password="+password); } 上述代码中,我们首先将ID和相应的的用户信息存在Map中。然后我们把需要检索的ID加入一个List中,然后采用foreach循环逐个检索Map中相应的的数据,并且将数据按照“账号:口令”的模式分割,最终打印账号和口令。 另外,如果用户信息量过大,我们也可以采用数据库进行检索。下面是一个采用JDBC从MySQL数据库中检索数据的示例代码。 String url = "jdbc:mysql://localhost:3306/userdb"; String user = "root"; String password = "123456"; List<String> ids = new ArrayList<>(); ids.add("id1"); ids.add("id2"); ids.add("id3"); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try{ conn = DriverManager.getConnection(url,user,password); String sql = "SELECT username,password FROM user WHERE id=?"; ps = conn.prepareStatement(sql); for(String id:ids){ ps.setString(1,id); rs = ps.executeQuery(); while(rs.next()){ String username = rs.getString("username"); String password = rs.getString("password"); System.out.println("ID "+id+": username="+username+"\t password="+password); } } }catch(SQLException e){ e.printStackTrace(); }finally{ try{ if(rs!=null){ rs.close(); } if(ps!=null){ ps.close(); } if(conn!=null){ conn.close(); } }catch(SQLException e){ e.printStackTrace(); } } 上述代码首先建立了与数据库的连接,然后采用PrepareStatement对象配置查询的SQL语句。在foreach循环中,我们通过配置PreparedStatement的参数并执行SQL查询获取查询结果,然后循环遍历结果集,打印账号和口令。 总之,不管是采用Map还是JDBC建立数据库连接,都可以通过Java实现根据多个ID检索账号和口令的功能。
2023-10-25 12:49:36
342
键盘勇士
转载文章
...ueMessage.split("@");if (strs.length >= 2) {qywxService.push(strs[0], strs[1]);} }} } @Configurationpublic class RabbitConfig {@Beanpublic Queue queue(){return new Queue("zyRabbitMQ");} } 4.企业微信的service层、impl层 原代码如下: @Servicepublic class QywxService implements IQywxService {//企业微信public static final String CORPID = "";public static final Integer AGENTID = ;public static final String CORPSECRET = "";public void push(String user, String content) {System.out.println("=====================================push()=============================");WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();config.setCorpId(CORPID); // 设置微信企业号的appidconfig.setCorpSecret(CORPSECRET); // 设置微信企业号的app corpSecretconfig.setAgentId(AGENTID); // 设置微信企业号应用IDWxCpServiceImpl wxCpService = new WxCpServiceImpl();wxCpService.setWxCpConfigStorage(config);System.out.println(user + "===" + content);WxCpMessage message = WxCpMessage.TEXT().agentId(AGENTID).toUser(user).content(content).build();System.out.println("send message===" + content);WxCpMessageSendResult wxCpMessageSendResult = new WxCpMessageSendResult();try {wxCpMessageSendResult = wxCpService.messageSend(message);} catch (WxErrorException e) {e.printStackTrace();System.out.println(e.getCause() + "===" + e.getMessage());}if (wxCpMessageSendResult.getErrCode() == 0) {System.out.println("0===推送成功");} else {System.out.println("500===推送失败");} }} public interface IQywxService {//消息推送public void push(String user,String content) throws WxErrorException;} 5.在具体的方法中调用convertAndSend方法 -->用于企业微信消息提醒 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_42926893/article/details/129683787。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-04-14 10:07:08
460
转载
Flink
...gt;(value.split(",")[0], Integer.parseInt(value.split(",")[1])); } }) .keyBy(0) .sum(1) .addSink(new PrintSinkFunction<>()); env.enableCheckpointing(5000); env.setStateBackend(new FsStateBackend("hdfs://path/to/state/backend")); 在这个例子中,我们使用了Kafka作为数据源,然后对输入的数据进行简单的映射和聚合操作。通过开启Checkpoint并设置好状态后端,我们确保应用即使重启,也能迅速恢复状态,继续处理新数据。这样就不用担心重启时要从头再来啦! 4. 总结与反思 通过上述讨论,我们可以看到,Flink提供的Checkpoint和Savepoint机制极大地提升了数据冷启动的可重用性。选择合适的状态后端也是关键因素之一。当然啦,这些办法也不是一用就万事大吉的,还得根据实际情况不断调整和优化呢。 希望这篇文章能帮助你更好地理解和解决FlinkJob数据冷启动的可重用性问题。如果你有任何疑问或者有更好的解决方案,欢迎在评论区留言交流!
2024-12-27 16:00:23
37
彩虹之上
Tesseract
...oved_text.split() if word.lower() in english_words]) 5. 针对异常情况的处理 当Tesseract抛出异常时,应遵循常规的异常处理原则。例如,捕获Image.open()可能导致的IOError,或者pytesseract.image_to_string()可能引发的RuntimeError等。 python try: img = Image.open('nonexistent_image.png') text = pytesseract.image_to_string(img) except IOError: print("无法打开图片文件!") except RuntimeError as e: print(f"运行时错误:{e}") 总结来说,处理Tesseract的错误和异常情况是一项涉及多个层面的工作,包括理解其内在局限性、优化输入图像、调整识别参数、结果后处理以及有效应对异常。在这个过程中,耐心调试、持续学习和实践反思都是非常关键的。让我们用人类特有的情感化思考和主观能动性去驾驭这一强大的工具,让Tesseract更好地服务于我们的需求吧!
2023-07-17 18:52:17
84
海阔天空
SeaTunnel
...ava的File类的split方法来实现这个功能: java File file = new File("data.txt"); List files = Arrays.asList(file.split("\\G", 5)); 在上面的例子中,我们将大文件"data.txt"分割成了5个小文件。 2. 使用更高速的网络 如果我们的网络状况不佳,我们可以考虑升级我们的网络设备,或者更换到更高质量的网络服务商。 3. 使用缓存 我们可以使用缓存来存储已经传输过的数据,避免重复传输。例如,我们可以使用Redis作为缓存服务器: java Jedis jedis = new Jedis("localhost"); String data = jedis.get(key); if (data != null) { // 数据已经在缓存中,不需要再次传输 } else { // 数据不在缓存中,需要从源获取并存储到缓存中 } 在上面的例子中,我们在尝试获取数据之前,先检查数据是否已经在缓存中。 四、总结 SeaTunnel是一个强大的工具,可以帮助我们处理大规模的数据流。然而,在实际操作SeaTunnel的时候,我们免不了可能会碰上数据传输速度不给力的情况。你知道吗,如果我们灵活运用一些小技巧,就能让SeaTunnel这小子在传输数据时跑得飞快。首先,咱们可以巧妙地把数据“切片分块”,别让它一次性噎着,这样传输起来就更顺畅了。其次,挑个网速倍儿棒的环境,就像给它搬进了信息高速公路,嗖嗖的。再者,利用缓存技术提前备好一些常用的数据,随用随取,省去了不少等待时间。这样一来,SeaTunnel的数据传输速度妥妥地就能大幅提升啦! 以上就是我对解决SeaTunnel数据传输速度慢问题的一些想法和建议。如果您有任何问题,欢迎随时与我交流。
2023-11-23 21:19:10
179
桃李春风一杯酒-t
Etcd
...onse.text.split('\n'): key, value = line.strip().split(': ') if key == 'etcd_disk_total': total_size = int(value) elif key == 'etcd_disk_used': used_size = int(value) elif key == 'etcd_disk_inodes_total': total_inodes = int(value) elif key == 'etcd_disk_inodes_used': used_inodes = int(value) return (used_size, total_size, used_inodes, total_inodes) def update_disk_usage(): used_size, total_size, used_inodes, total_inodes = get_disk_usage() counter.labels(total_size).inc() disk_usage.labels(used_size).inc() while True: update_disk_usage() time.sleep(60) 五、结论 总的来说,监控Etcd节点的健康状态是分布式系统管理中的一个重要环节。通过各种各样的监控小工具和我们自己设置的独特指标,咱们能更接地气地掌握Etcd节点的运行状态,这样一来,任何小毛小病都甭想逃过咱们的眼睛,能够及时揪出来、顺手就给解决了。在未来,随着分布式系统的日益壮大和进化,我们还得继续钻研和优化监控方案,好让它们更能应对各种眼花缭乱的复杂场景。
2023-12-30 10:21:28
512
梦幻星空-t
Sqoop
...s = [line.split()[0] for line in source_schema.strip().split("\n")] 生成创建表的SQL语句 create_table_sql = f"CREATE TABLE employees ({', '.join([f'{col} VARCHAR(255)' for col in columns])});" print(create_table_sql) 运行这个脚本后,它会输出如下SQL语句: sql CREATE TABLE employees (id VARCHAR(255), name VARCHAR(255), age VARCHAR(255)); 然后我们可以执行这个SQL语句来创建目标表。这种方法虽然复杂一些,但可以实现自动化管理,减少人为错误。 5. 结论 通过以上几种方法,我们可以有效地解决Sqoop导入数据时表结构同步的问题。每种方法都有其优缺点,选择哪种方法取决于具体的需求和环境。我个人倾向于使用脚本自动化处理,因为它既灵活又高效。当然,你也可以根据实际情况选择最适合自己的方法。 希望这些内容能对你有所帮助!如果你有任何问题或建议,欢迎随时留言讨论。我们一起学习,一起进步!
2025-01-28 16:19:24
115
诗和远方
AngularJS
... && input.split) { var names = input.split(' '); return names[names.length - 1]; } else { return input; // 如果输入非字符串,则直接返回原值 } }; }); 上述代码中,我们定义了一个名为lastName的过滤器,它接受一个参数input(即用户全名),并返回该名字的最后一个单词作为姓氏。 2. 在视图中使用过滤器 接下来,我们在HTML模板中引用这个过滤器: html { { user.fullName | lastName } } 在这里,{ { user.fullName | lastName } }就是一个典型的过滤器使用方式,| lastName表示对user.fullName这个属性应用了我们刚刚创建的lastName过滤器。 三、进阶 添加更多功能和参数(4) 当然,AngularJS过滤器的功能远不止于此。我们可以让过滤器接收额外的参数,以便提供更多的定制能力。例如,如果我们想让用户可以选择是否显示中间名,可以这样修改过滤器: javascript angular.module('myApp') .filter('lastName', function() { return function(input, showMiddleName) { // 判断是否需要显示中间名 if (!showMiddleName) { // 仅显示姓氏 return (input || '').split(' ').pop(); } else { // 显示全名 return input; } }; }); 然后在视图中传递参数: html { { user.fullName | lastName:showMiddleName } } 以上,我们已经成功地从零开始创建了一个具备基础功能且支持参数化的AngularJS过滤器,并将其运用到了实际场景中。希望这次的探索旅程能帮助你更好地理解和掌握AngularJS过滤器的创建和使用方法。在未来面对更复杂的数据处理需求时,不妨尝试自定义过滤器,让你的应用更具灵活性和可维护性! 总结一下,无论是简化数据展示,还是丰富用户交互体验,AngularJS过滤器都扮演着至关重要的角色。只要我们善于利用并不断实践,就一定能解锁更多有趣且实用的玩法。所以,让我们保持好奇,持续探索,尽情享受编程的乐趣吧!
2024-03-09 11:18:03
476
柳暗花明又一村
转载文章
..., arr = n.split('.'), oldPath = src + '/' + n, newPath = dist + '/' + filename + index + '.' + arr[arr.length - 1]; fs.stat(oldPath, (err, stats) => { if (err) { console.log(err); } else if (stats.isFile()) { readStream = fs.createReadStream(oldPath); writeStream = fs.createWriteStream(newPath); readStream.pipe(writeStream); } }); index++; }) } 效果 总结 node提供了很多模块可以帮助我们完成不同需求的功能开发,使javascript不仅仅局限与浏览器中,尝试自己编写一些脚本有助于对这些模块的理解,同时也能提高办公效率。 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_33205138/article/details/112036462。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-30 19:15:04
67
转载
Tesseract
...ds = text.split() for word in words: word_image = image.crop((0, 0, len(word), 1)) print(pytesseract.image_to_string(word_image)) 四、结语 通过以上的分析和讨论,我们可以看出,虽然低质量图像给Tesseract的识别带来了一定的挑战,但是我们还是可以通过一系列的优化策略来提升其性能。真心希望这篇文章能给亲带来一些实实在在的帮助,如果有啥疑问、想法或者建议,尽管随时找我唠唠嗑,咱一起探讨探讨哈!
2023-02-06 17:45:52
65
诗和远方-t
Beego
...= strings.Split(ctx.Request.URL.Path, "/") if len(urlParts) > 2 && urlParts[1] == "custom" { switch urlParts[2] { case "action1": ctx.Output.Body([]byte("Executing Action 1")) return case "action2": ctx.Output.Body([]byte("Executing Action 2")) return } } // 若未命中自定义路由,则继续向下执行默认路由逻辑 }) 在这个例子中,我们在进入默认路由之前插入了一个过滤器,对请求路径进行解析,并针对特定路径执行相应动作。 4. 总结与思考 自定义路由规则为我们的应用带来了无比的灵活性,让我们能够更好地适配各种复杂的业务场景。在我们真正动手开发的时候,得把Beego的路由功能玩得溜起来,不断捣鼓和微调路由设置,让它们既能搞定各种功能需求,又能保持干净利落、易于维护和扩展性棒棒哒。记住,路由设计并非一蹴而就,而是伴随着项目迭代演进而逐步完善的。所以,别怕尝试,大胆创新,让每个API都找到它的“归宿”,这就是我们在Beego中实现自定义路由的乐趣所在!
2023-07-13 09:35:46
621
青山绿水
Spark
...> line.split("\\s+")) val wordCounts = words.groupBy($"value").count() wordCounts.show() // 显示结果 4.3 处理外部依赖 如果任务依赖于外部资源,我们需要确保这些资源是可用的。例如,如果任务需要访问数据库,我们需要检查数据库连接是否正常。 scala val jdbcDF = spark.read .format("jdbc") .option("url", "jdbc:mysql://localhost:3306/database_name") .option("dbtable", "table_name") .option("user", "username") .option("password", "password") .load() jdbcDF.show() 4.4 日志分析 最后,我们可以通过查看日志来获取更多的信息。日志中可能会包含更详细的错误信息,帮助我们更好地定位问题。 bash spark-submit --class com.example.MyJob --master local[] my-job.jar 5. 总结 通过以上步骤,我成功解决了这个令人头疼的问题。虽然过程中遇到了不少困难,但最终还是找到了合适的解决方案。希望我的经验能对大家有所帮助。如果还有其他问题,欢迎随时交流讨论! --- 这篇文章涵盖了从问题背景到具体解决方案的全过程,希望对你有所帮助。如果你在实际操作中遇到其他问题,不妨多查阅官方文档或者向社区求助,相信总能找到答案。
2025-03-02 15:38:28
94
林中小径
Apache Pig
...片(Logical Splitting) , 在Apache Pig中,数据分片是指将输入的大规模数据集逻辑上划分为多个部分或子集的操作。通过使用SPLIT语句,可以根据特定条件将数据分割成多个独立的数据流,并行进行处理。这样做的好处是能够充分利用分布式计算资源,提升数据处理效率。 数据压缩 , 数据压缩是在存储或传输数据前减少其占用空间的技术。在Apache Pig中,支持对加载和存储的数据采用gzip、bz2等多种压缩格式,以降低存储成本并减少网络传输和磁盘I/O过程中的时间消耗。通过合理的压缩策略,可以在不影响数据完整性的前提下提高系统整体性能。例如,在实际操作中,可以将原始数据文件压缩后加载到Pig中进行处理,再将处理结果压缩后存储,从而有效节省存储空间并优化数据读取速度。
2023-12-10 16:07:09
458
昨夜星辰昨夜风
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
cut -d ',' -f 1,3 file.csv
- 根据逗号分隔符提取csv文件中第1列和第3列的内容。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
2023-04-28
2023-08-09
2023-06-18
2023-04-14
2023-02-18
2023-04-17
2024-01-11
2023-10-03
2023-09-09
2023-06-13
2023-08-07
2023-03-11
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"