前端技术
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
[click]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
转载文章
...ass MockAdClickedStat {/ @param args/public static void main(String[] args) {final Random random = new Random();final String[] provinces = new String[]{"Guangdong", "Zhejiang", "Jiangsu", "Fujian"};final Map<String, String[]> cities = new HashMap<String, String[]>();cities.put("Guangdong", new String[]{"Guangzhou", "Shenzhen", "Dongguan"});cities.put("Zhejiang", new String[]{"Hangzhou", "Wenzhou", "Ningbo"});cities.put("Jiangsu", new String[]{"Nanjing", "Suzhou", "Wuxi"});cities.put("Fujian", new String[]{"Fuzhou", "Xiamen", "Sanming"});final String[] ips = new String[] {"192.168.112.240","192.168.112.239","192.168.112.245","192.168.112.246","192.168.112.247","192.168.112.248","192.168.112.249","192.168.112.250","192.168.112.251","192.168.112.252","192.168.112.253","192.168.112.254",};/ Kafka相关的基本配置信息/Properties kafkaConf = new Properties();kafkaConf.put("serializer.class", "kafka.serializer.StringEncoder");kafkaConf.put("metadeta.broker.list", "Master:9092,Worker1:9092,Worker2:9092");ProducerConfig producerConfig = new ProducerConfig(kafkaConf);final Producer<Integer, String> producer = new Producer<Integer, String>(producerConfig);new Thread(new Runnable() {public void run() {while(true) {//在线处理广告点击流的基本数据格式:timestamp、ip、userID、adID、province、cityLong timestamp = new Date().getTime();String ip = ips[random.nextInt(12)]; //可以采用网络上免费提供的ip库int userID = random.nextInt(10000);int adID = random.nextInt(100);String province = provinces[random.nextInt(4)];String city = cities.get(province)[random.nextInt(3)];String clickedAd = timestamp + "\t" + ip + "\t" + userID + "\t" + adID + "\t" + province + "\t" + city;producer.send(new KeyedMessage<Integer, String>("AdClicked", clickedAd));try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }} }).start();} } package com.tom.spark.SparkApps.sparkstreaming;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.LinkedBlockingQueue;import kafka.serializer.StringDecoder;import org.apache.spark.SparkConf;import org.apache.spark.api.java.JavaPairRDD;import org.apache.spark.api.java.JavaRDD;import org.apache.spark.api.java.JavaSparkContext;import org.apache.spark.api.java.function.Function;import org.apache.spark.api.java.function.Function2;import org.apache.spark.api.java.function.PairFunction;import org.apache.spark.api.java.function.VoidFunction;import org.apache.spark.sql.DataFrame;import org.apache.spark.sql.Row;import org.apache.spark.sql.RowFactory;import org.apache.spark.sql.hive.HiveContext;import org.apache.spark.sql.types.DataTypes;import org.apache.spark.sql.types.StructType;import org.apache.spark.streaming.Durations;import org.apache.spark.streaming.api.java.JavaDStream;import org.apache.spark.streaming.api.java.JavaPairDStream;import org.apache.spark.streaming.api.java.JavaPairInputDStream;import org.apache.spark.streaming.api.java.JavaStreamingContext;import org.apache.spark.streaming.api.java.JavaStreamingContextFactory;import org.apache.spark.streaming.kafka.KafkaUtils;import com.google.common.base.Optional;import scala.Tuple2;/ 数据处理,Kafka消费者/public class AdClickedStreamingStats {/ @param args/public static void main(String[] args) {// TODO Auto-generated method stub//好处:1、checkpoint 2、工厂final SparkConf conf = new SparkConf().setAppName("SparkStreamingOnKafkaDirect").setMaster("hdfs://Master:7077/");final String checkpointDirectory = "hdfs://Master:9000/library/SparkStreaming/CheckPoint_Data";JavaStreamingContextFactory factory = new JavaStreamingContextFactory() {public JavaStreamingContext create() {// TODO Auto-generated method stubreturn createContext(checkpointDirectory, conf);} };/ 可以从失败中恢复Driver,不过还需要指定Driver这个进程运行在Cluster,并且在提交应用程序的时候制定--supervise;/JavaStreamingContext javassc = JavaStreamingContext.getOrCreate(checkpointDirectory, factory);/ 第三步:创建Spark Streaming输入数据来源input Stream: 1、数据输入来源可以基于File、HDFS、Flume、Kafka、Socket等 2、在这里我们指定数据来源于网络Socket端口,Spark Streaming连接上该端口并在运行的时候一直监听该端口的数据 (当然该端口服务首先必须存在),并且在后续会根据业务需要不断有数据产生(当然对于Spark Streaming 应用程序的运行而言,有无数据其处理流程都是一样的) 3、如果经常在每间隔5秒钟没有数据的话不断启动空的Job其实会造成调度资源的浪费,因为并没有数据需要发生计算;所以 实际的企业级生成环境的代码在具体提交Job前会判断是否有数据,如果没有的话就不再提交Job;///创建Kafka元数据来让Spark Streaming这个Kafka Consumer利用Map<String, String> kafkaParameters = new HashMap<String, String>();kafkaParameters.put("metadata.broker.list", "Master:9092,Worker1:9092,Worker2:9092");Set<String> topics = new HashSet<String>();topics.add("SparkStreamingDirected");JavaPairInputDStream<String, String> adClickedStreaming = KafkaUtils.createDirectStream(javassc, String.class, String.class, StringDecoder.class, StringDecoder.class,kafkaParameters, topics);/因为要对黑名单进行过滤,而数据是在RDD中的,所以必然使用transform这个函数; 但是在这里我们必须使用transformToPair,原因是读取进来的Kafka的数据是Pair<String,String>类型, 另一个原因是过滤后的数据要进行进一步处理,所以必须是读进的Kafka数据的原始类型 在此再次说明,每个Batch Duration中实际上讲输入的数据就是被一个且仅被一个RDD封装的,你可以有多个 InputDStream,但其实在产生job的时候,这些不同的InputDStream在Batch Duration中就相当于Spark基于HDFS 数据操作的不同文件来源而已罢了。/JavaPairDStream<String, String> filteredadClickedStreaming = adClickedStreaming.transformToPair(new Function<JavaPairRDD<String,String>, JavaPairRDD<String,String>>() {public JavaPairRDD<String, String> call(JavaPairRDD<String, String> rdd) throws Exception {/ 在线黑名单过滤思路步骤: 1、从数据库中获取黑名单转换成RDD,即新的RDD实例封装黑名单数据; 2、然后把代表黑名单的RDD的实例和Batch Duration产生的RDD进行Join操作, 准确的说是进行leftOuterJoin操作,也就是说使用Batch Duration产生的RDD和代表黑名单的RDD实例进行 leftOuterJoin操作,如果两者都有内容的话,就会是true,否则的话就是false 我们要留下的是leftOuterJoin结果为false; /final List<String> blackListNames = new ArrayList<String>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();jdbcWrapper.doQuery("SELECT FROM blacklisttable", null, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {while(result.next()){blackListNames.add(result.getString(1));} }});List<Tuple2<String, Boolean>> blackListTuple = new ArrayList<Tuple2<String,Boolean>>();for(String name : blackListNames) {blackListTuple.add(new Tuple2<String, Boolean>(name, true));}List<Tuple2<String, Boolean>> blacklistFromListDB = blackListTuple; //数据来自于查询的黑名单表并且映射成为<String, Boolean>JavaSparkContext jsc = new JavaSparkContext(rdd.context());/ 黑名单的表中只有userID,但是如果要进行join操作的话就必须是Key-Value,所以在这里我们需要 基于数据表中的数据产生Key-Value类型的数据集合/JavaPairRDD<String, Boolean> blackListRDD = jsc.parallelizePairs(blacklistFromListDB);/ 进行操作的时候肯定是基于userID进行join,所以必须把传入的rdd进行mapToPair操作转化成为符合格式的RDD/JavaPairRDD<String, Tuple2<String, String>> rdd2Pair = rdd.mapToPair(new PairFunction<Tuple2<String,String>, String, Tuple2<String, String>>() {public Tuple2<String, Tuple2<String, String>> call(Tuple2<String, String> t) throws Exception {// TODO Auto-generated method stubString userID = 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
296
转载
Element-UI
...expand-on-click-node highlight-current @node-click="handleNodeClick" > 在这个例子中,我们定义了一个树形控件,并传入了一组数据作为数据源。然后呢,我们给node-click事件装上了“监听器”,就像派了个小侦探守在那儿。当用户心血来潮点到某个节点时,这位小侦探就立马行动,把那个被点中的节点信息给咱详细报告出来。 如果在运行这段代码时,你发现某些节点无法正常展开或收起,那么你就需要根据上述的方法来进行排查和解决。 六、结语 总的来说,使用Element-UI的树形控件时节点渲染错误或无法展开与收起,这可能是因为我们的代码实现存在问题,或者是Element-UI本身的一些限制导致的。但是,只要我们能像侦探一样,准确找到问题藏身之处,然后对症下药,采取合适的解决策略,那么这个问题肯定能被我们手到擒来,顺利解决掉。所以,让我们一起努力,让前端开发变得更简单、更高效吧!
2023-08-31 16:39:17
503
追梦人-t
转载文章
..."submit" @click.prevent="searchKey" id="searchbtn">搜索</button></div></fieldset></form><ul class="relKeyTop"><li><a>狂神说Java</a></li><li><a>狂神说前端</a></li><li><a>狂神说Linux</a></li><li><a>狂神说大数据</a></li><li><a>狂神聊理财</a></li></ul></div></div></div></div></div><el-button @click="download" id="download">下载</el-button><!-- <el-button @click="concurrenceDownload" >并发下载测试</el-button>--><el-button @click="stop">停止</el-button><el-button @click="start">开始</el-button>{ {fileFinalOffset} }{ {contentList} }<el-progress type="circle" :percentage="percentage"></el-progress></div><!--前端使用Vue,实现前后端分离--><script th:src="@{/js/axios.min.js}"></script><script th:src="@{/js/vue.min.js}"></script><!-- 引入样式 --><link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"><!-- 引入组件库 --><script src="https://unpkg.com/element-ui/lib/index.js"></script><script>new Vue({ el: 'app',data: {keyword: '', //搜索关键字results: [] ,//搜索结果percentage: 0, // 下载进度filesCurrentPage:0,//文件开始偏移量fileFinalOffset:0, //文件最后偏移量stopRecursiveTags:true, //停止递归标签,默认是true 继续进行递归contentList: [], // 文件流数组breakpointResumeTags:false, //断点续传标签,默认是false 不进行断点续传temp:[],fileMap:new Map(),timer:null, //定时器名称},methods: {//根据关键字搜索商品信息searchKey(){var keyword=this.keyword;axios.get('/search/JD/search/'+keyword+"/1/10").then(res=>{this.results=res.data;//绑定数据console.log(this.results)console.table(this.results)})},//停止下载stop(){//改变递归标签为falsethis.stopRecursiveTags=false;},//开始下载start(){//重置递归标签为true 最后进行合并this.stopRecursiveTags=true;//重置断点续传标签this.breakpointResumeTags=true;//重新调用下载方法this.download();},// 分段下载需要后端配合download() {// 下载地址const url = "/down?fileName="+this.keyword.trim()+"&drive=E";console.log(url)const chunkSize = 1024 1024 50; // 单个分段大小,这里测试用100Mlet filesTotalSize = chunkSize; // 安装包总大小,默认100Mlet filesPages = 1; // 总共分几段下载//计算百分比之前先清空上次的if(this.percentage==100){this.percentage=0;}let sentAxios = (num) => {let rande = chunkSize;//判断是否开启了断点续传(断点续传没法并行-需要上次请求的结果作为参数)if (this.breakpointResumeTags){rande = ${Number(this.fileFinalOffset)+1}-${num chunkSize + 1};}else {if (num) {rande = ${(num - 1) chunkSize + 2}-${num chunkSize + 1};} else {// 第一次0-1方便获取总数,计算下载进度,每段下载字节范围区间rande = "0-1";} }let headers = {range: rande,};axios({method: "get",url: url.trim(),async: true,data: {},headers: headers,responseType: "blob"}).then((response) => {if (response.status == 200 || response.status == 206) {//检查了下才发现,后端对文件流做了一层封装,所以将content指向response.data即可const content = response.data;//截取文件总长度和最后偏移量let result= response.headers["content-range"].split("/");// 获取文件总大小,方便计算下载百分比filesTotalSize =result[1];//获取最后一片文件位置,用于断点续传this.fileFinalOffset=result[0].split("-")[1]// 计算总共页数,向上取整filesPages = Math.ceil(filesTotalSize / chunkSize);// 文件流数组this.contentList.push(content);// 递归获取文件数据(判断是否要继续递归)if (this.filesCurrentPage < filesPages&&this.stopRecursiveTags==true) {this.filesCurrentPage++;//计算下载百分比 当前下载的片数/总片数this.percentage=Number((this.contentList.length/filesPages)100).toFixed(2);sentAxios(this.filesCurrentPage);//结束递归return;}//递归标签为true 才进行下载if (this.stopRecursiveTags){// 文件名称const fileName =decodeURIComponent(response.headers["fname"]);//构造一个blob对象来处理数据const blob = new Blob(this.contentList);//对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性//IE10以上支持blob但是依然不支持downloadif ("download" in document.createElement("a")) {//支持a标签download的浏览器const link = document.createElement("a"); //创建a标签link.download = fileName; //a标签添加属性link.style.display = "none";link.href = URL.createObjectURL(blob);document.body.appendChild(link);link.click(); //执行下载URL.revokeObjectURL(link.href); //释放urldocument.body.removeChild(link); //释放标签} else {//其他浏览器navigator.msSaveBlob(blob, fileName);} }} else {//调用暂停方法,记录当前下载位置console.log("下载失败")} }).catch(function (error) {console.log(error);});};// 第一次获取数据方便获取总数sentAxios(this.filesCurrentPage);this.$message({message: '文件开始下载!',type: 'success'});} }})</script></body></html> 本篇文章为转载内容。原文链接:https://blog.csdn.net/kangshihang1998/article/details/129407214。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-19 08:12:45
545
转载
Python
... a') link.click() 关闭浏览器 driver.quit() 上面的代码通过使用Selenium模块 - 库件和Chrome浏览器来模仿 - 模拟人 - 实体的点击行为,实现了在百度查找 - 寻找Python后点击第一个查找 - 寻找结果的链接的功能。在实际应用中,这种模仿 - 模拟点击的方式可以用于各种自动化 - 自动化的操作,比如通过点击来实现站点 - 网页的自动登录,自动发送邮件等等。
2024-05-01 16:24:58
244
编程狂人
JQuery
...,在代码中配置按键的click事件后,点击按键并没有反馈。 $(document).ready(function(){ $("myButton").click(function(){ alert("Clicked!"); //这里配置了一个提示框 }); }); 根据我的经历和参考文献,检查的方法如下: 1.检查代码句法是不是准确,如括号是不是对应、方法是不是准确等。 $(document).ready(function(){ $("myButton").click(function(){ alert("Clicked!"); //这里配置了一个提示框 //}); //这里标注掉了括号,造成代码句法错误 }); 2.检查代码有没有被阻止执行,如代码依赖的库或其他代码是不是准确。 $(document).ready(function(){ $("myButton").click(function(){ alert("Clicked!"); //这里配置了一个提示框 }); }); //这里漏掉了jQuery库 3.检查页面是不是准确引入了相关文件,如jQuery库、CSS文件等。 My Page //这里漏掉了引入jQuery库的代码 总之,要解决按键的click事件无效,要求认真检查代码和页面的每一个细节。
2023-03-10 18:35:11
147
码农
Element-UI
...同时可以通过row-click事件监听行的点击事件。 然后,我们需要明白,要实现行的展开/收起效果,需要两个关键点:一是获取当前被点击的行数据;二是修改该行的状态,使其可以展示子内容。 三、解决方案 1. 获取当前被点击的行数据 通过el-table提供的row-click事件,我们可以轻松地获取到当前被点击的行数据。以下是一个简单的示例: html 2. 修改该行的状态,使其可以展示子内容 对于这个问题,我们需要自己添加一个状态变量,并且在row-click事件触发时更新这个状态变量。下面是一个简单的示例: html 四、总结 通过上述方法,我们成功实现了在Vue.js项目中使用Element-UI的el-table组件时,点击行任意位置都能实现展开/收起的效果。要特别留意的是,这里的“展开/收起”可不只是简单的藏起来露出来那么简单,关键得保证表头、表体这些部分都整整齐齐的,不能让人瞅见有啥突兀的蹦跶情况发生哈。如果对这个问题感兴趣,欢迎留言讨论,一起学习进步!
2023-10-23 16:53:41
403
青山绿水_t
VUE
...t;button @click="generatePDF">创建PDF</button> </div> </template> <script> import { generatePDF } from "vue-online-pdf"; export default { data() { return { content: "", }; }, methods: { async generatePDF() { const pdfBlob = await generatePDF(this.content); const url = window.URL.createObjectURL(pdfBlob); const link = document.createElement("a"); link.href = url; link.setAttribute("download", "my-document.pdf"); document.body.appendChild(link); link.click(); }, }, }; </script> 上面的代码演示了一个容易的实现方式,当你在输入区域中输入内容并按下“创建PDF”按键时,它将会自动转换为PDF文档并获取到你的电脑中。 总之,使用Vue在线PDF可以帮助我们轻松快捷地创建PDF文档,而且减少了很多繁琐的步骤,非常方便实用。
2023-11-07 11:10:47
77
程序媛
JQuery
...tyle> click-text { font-size: 24px; cursor: pointer; } .myclass { color: red; } </style> </head> <body> <p id="click-text">触碰我测试</p> <script> $(document).ready(function() { $("click-text").click(function() { $(this).addClass("myclass"); alert("你触碰了我!"); }); }); </script> </body> </html> 代码介绍: <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> 这一行是加载 jQuery 脚本文件。 <p id="click-text">触碰我测试</p> 这一行是一个待触碰的 p 元素。 $(document).ready(function() {}); 这一行是等页面加载完成后运行的代码。 $("click-text").click(function() {}); 这一行是给触碰事件赋予一个响应函数,当该 p 元素被触碰时,运行该响应函数内的代码。 $(this).addClass("myclass"); 这一行是给被触碰的 p 元素赋予一个名为 myclass 的类,以便在 CSS 样式中使用。 alert("你触碰了我!"); 这一行是弹出一个警告对话框,通知用户触碰了该 p 元素。 .myclass { color: red; } 这一段是将 myclass 类的字体颜色变为红色。 使用以上代码,即可在网页中完成触碰某个元素后启动某些处理的功能。
2023-01-01 08:53:25
311
码农
VUE
...message" @click="handleClick" /> </div> </template> <script> import MyComponent from './MyComponent.vue'; export default { components: { MyComponent }, data() { return { message: 'Hello Vue!' } }, methods: { handleClick() { alert('Clicked!'); } } } </script> // SVGA示例代码 var player = new SVGA.Player('canvas'); var parser = new SVGA.Parser(); parser.load('anim.svga', function(videoItem) { player.setVideoItem(videoItem); player.startAnimation(); });
2023-01-11 22:10:45
96
程序媛
ReactJS
...; } handleClick() { this.setState({ count: this.state.count + 1 }); } render() { return ( 点击我 已点击次数:{this.state.count} ); } } export default MyComponent; javascript import React from 'react'; const MyComponent = ({ count }) => ( alert(Clicked ${count} times)}>Click me Count: {count} ); export default React.memo(MyComponent); 四、优化状态管理 1. 合理使用Redux或其他状态管理库 当我们需要管理大量状态时,可以考虑使用Redux或其他状态管理库。它们可以帮助我们将状态集中管理,提高代码的可维护性和可复用性。 2. 尽量避免全局状态 当我们的应用状态非常复杂时,很容易陷入“全局状态”的陷阱。在我们编写代码的时候,最好能绕开全局状态这个坑,尽量采用更清爽的方式传递信息。比如说,我们可以把状态当作“礼物”通过props传给组件,或者玩个“电话游戏”,用回调函数来告诉组件当前的状态。这样不仅能让代码逻辑更加清晰易懂,还能避免一些意想不到的bug出现。
2023-12-05 22:17:14
108
雪落无痕-t
Python
...te_button.clicked.connect(self.translate_text) 布局设计 layout = QVBoxLayout() layout.addWidget(self.input_label) layout.addWidget(self.input_line) layout.addWidget(self.translate_button) self.setCentralWidget(layout) 在这个类中,我们定义了一个构造函数initUI,它主要负责创建窗口布局。我们还特意设计了一个叫做translate_text的方法,你就想象一下,当你轻轻一点那个“翻译”按钮的时候,这个方法就像被按下了启动开关,立马就开始工作啦! 五、运行程序 最后,我们需要在主函数中创建并显示窗口,并设置应用程序参数以便退出: python if __name__ == '__main__': app = QApplication(sys.argv) window = TranslateWindow() window.show() sys.exit(app.exec_()) 六、总结 Python是一种非常强大的语言,它可以用来做很多事情,包括桌面翻译。借助Google Translate API和其他翻译工具,我们能够轻轻松松、快速地搞定各种文本翻译任务,就像有了一个随身的翻译小助手一样方便。用PyQt5这类工具库,咱们就能轻松设计出美美的用户界面,让大伙儿使用起来更舒心、更享受。 这只是一个基础的示例,实际上,我们还可以添加更多的功能,例如保存翻译历史、支持更多语言等。希望这篇文章能帮助你更好地理解和使用Python进行桌面翻译。
2023-09-30 17:41:35
248
半夏微凉_t
ReactJS
...的命名方式(如onclick),但在ReactJS中,事件绑定则需要使用驼峰命名(如onClick)。这是一个新手很容易踩到的坑。 jsx // 错误示例: Click me // 正确示例: Click me 在上述例子中,onclick是无效的事件绑定方式,正确的做法应为onClick。 3. 错误二 忘记bind方法 在React类组件中,如果直接在事件处理函数中引用this关键字,可能会出现undefined的问题,这是因为事件处理函数默认没有绑定到当前组件实例。为此,我们需要在构造函数中进行手动绑定,或者使用箭头函数。 jsx class MyComponent extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); // 手动绑定 } handleClick() { console.log('Clicked:', this.props.message); } render() { return Click me; } } // 或者使用箭头函数实现自动绑定 class MyComponent extends React.Component { handleClick = () => { console.log('Clicked:', this.props.message); } render() { return Click me; } } 在这个案例中,如果不进行绑定或使用箭头函数,this在handleClick函数内部将不会指向组件实例,从而无法访问组件的状态和属性。 4. 错误三 动态事件绑定 在某些场景下,我们可能需要根据条件动态地绑定不同的事件处理函数。这时候,假如我们在渲染的过程中直接在里头定义函数,就像每次做饭都重新买个锅一样,会导致每一次渲染的时候,都会生成一个新的函数实例。这就像是你本来只是想热个剩菜,结果却触发了整个厨房的重新运作,完全是没必要的重新渲染过程。 jsx // 错误示例: render() { const handleClick = () => { console.log('Clicked'); }; return Click me; } // 正确示例: class MyComponent extends React.Component { handleClick = () => { console.log('Clicked'); } render() { let clickHandler; if (this.props.shouldLog) { clickHandler = this.handleClick; } else { clickHandler = () => {}; // 空函数防止不必要的调用 } return Click me; } } 在正确示例中,我们提前定义好事件处理函数,并在render方法中根据条件选择合适的处理函数进行绑定,避免了每次渲染都创建新函数的情况。 5. 结语 面对ReactJS中的事件绑定问题,关键在于深入理解其工作原理并遵循最佳实践。真功夫都是从实践中磨出来的,只有不断摔跤、摸爬滚打、学习钻研,解决各种实际问题,我们才能真正把ReactJS这个牛X的前端框架玩得溜起来。希望你在ReactJS的世界里探险时,能够巧妙地避开那些常让人跌跤的事件绑定坑洼,亲手打造出更加强劲又稳当的组件代码,让编程之路更加顺风顺水。下次当你再次面对事件绑定问题时,相信你会带着更坚定的信心和更深的理解去应对它!
2023-08-11 19:00:01
130
幽谷听泉
Javascript
...括但不限于: - click:当鼠标单击元素时触发。 - dblclick:当鼠标双击元素时触发。 - mousedown:当鼠标按钮被按下时触发。 - mouseup:当鼠标按钮被释放(松开)时触发。 - mousemove:当鼠标指针在元素内部移动时连续触发。 - mouseenter 和 mouseleave:分别在鼠标进入和离开元素时触发。 - mouseover 和 mouseout:当鼠标进入或离开元素及其任何子元素时触发。 2. 监听鼠标事件的语法 在JavaScript中,我们通常通过DOM元素的addEventListener方法来监听这些鼠标事件。下面是一个基本的代码示例,演示如何为一个按钮添加点击事件监听器: javascript // 获取页面上的某个按钮元素 var myButton = document.getElementById('myButton'); // 为按钮添加click事件监听器 myButton.addEventListener('click', function(event) { // 当按钮被点击时,执行这个函数 console.log('Button clicked!'); // event对象包含了关于此事件的各种信息,例如点击的位置等 console.log('Clicked at: ' + event.clientX + ', ' + event.clientY); }); // 注意:如果你使用的是ES6箭头函数,可以简化为如下形式: myButton.addEventListener('click', (event) => { console.log('Button clicked using arrow function!'); }); 3. 处理多个鼠标事件 我们可以同时为同一个元素监听多种鼠标事件,每个事件对应不同的处理函数: javascript var myDiv = document.getElementById('myDiv'); // 单击事件 myDiv.addEventListener('click', function() { this.style.backgroundColor = 'red'; // 点击后背景变红 }); // 鼠标悬停事件 myDiv.addEventListener('mouseover', function() { this.textContent = 'Mouse is over!'; // 鼠标悬停时显示提示文字 }); // 鼠标离开事件 myDiv.addEventListener('mouseleave', function() { this.textContent = ''; // 鼠标离开后清除提示文字 }); 4. 移除事件监听器 有时我们需要动态移除已添加的事件监听器,这时可以使用removeEventListener方法: javascript var myInput = document.getElementById('myInput'); // 添加focus事件监听器 function handleFocus() { console.log('Input gained focus'); } myInput.addEventListener('focus', handleFocus); // 在某些条件满足时,移除该监听器 function disableFocusListener() { myInput.removeEventListener('focus', handleFocus); console.log('Focus listener has been removed.'); } // 假设某个操作后需要移除监听器,调用disableFocusListener函数即可 以上就是JavaScript监听鼠标事件的基本内容。通过实例代码的学习,相信你已经掌握了这一重要技能。但是千万记住啊,在实际操作里,根据项目的具体需求和用户体验的实际情况,我们可能需要对这些事件进行更深度、更精细的处理和优化,就像是给它们来一场全面升级的大改造一样。探索永无止境,希望你在JavaScript的道路上越走越远,享受编程带来的乐趣!
2023-04-06 13:52:34
335
烟雨江南
JQuery
...useButton.click(function() { if (player.hasClass('playing')) { player.removeClass('playing').addClass('paused'); $(this).text('Play'); } else { player.removeClass('paused').addClass('playing'); $(this).text('Pause'); } }); // 添加音量滑动条滑动事件监听器 volumeSlider.on('input', function() { var percent = $(this).val(); setVolume(percent); }); // 更新音量值 function setVolume(value) { volumeSlider.val(value); var volumePercent = (value / 100) 100; var volumeValueText = volumePercent + '%'; $('.volume-value').text(volumeValueText); } // 计算并设置进度条长度 function updateProgress(currentTime, duration) { var playedLength = (currentTime / duration) 100; var playedBarWidth = playedLength + '%'; playedBar.width(playedBarWidth); } }); 五、添加进度条更新功能 最后,我们要让进度条能够随着音乐播放的进度而自动更新。为了实现这个目标,咱们得时不时瞅一眼现在播放的时间,然后根据这个时间,像算数课那样,计算出当前的进度。然后,我们将新的进度设置为进度条的宽度。 以下是这部分代码示例: javascript // 定义定时器 var timerId; // 开始播放后设置定时器 function startPlaying() { timerId = setInterval(function() { var currentTime = audio.currentTime; var duration = audio.duration; updateProgress(currentTime, duration); }, 1000); } // 停止播放时清除定时器 function stopPlaying() { clearInterval(timerId); } 六、总结 以上就是使用jQuery创建一个带滑动条的播放器的全过程。从创建播放器界面到添加交互功能,再到添加进度条更新功能,每一个环节都需要我们仔细考虑和精心设计。虽然这个过程就像一场冒险,会遇到各种预料不到的挑战和难题,但是只要我们像跑马拉松那样,咬紧牙关、坚持到底,就绝对能把这个任务漂亮地搞定,妥妥的! 在这个过程中,我们也学到了很多有用的知识和技术,例如HTML、CSS、jQuery的基本语法、事件处理和动画等。这些知识和技术将会对我们今后的网页开发工作产生深远的影响。 最后,我希望这篇教程能够对你有所帮助。如果你有任何疑问或者建议,欢迎随时与我联系。祝你在学习之路一切顺利!
2023-01-20 22:28:12
351
山涧溪流-t
HTML
...Listener('click', () => { log.info('User clicked on the button!'); log.error('An unexpected error occurred during the click event!', new Error('Error details')); }); 上述代码中,我们分别用log.info()和log.error()记录了不同级别的信息。这些日志会自动乖乖地蹦进默认的日志文件里头,这个文件一般都藏在你电脑的AppData目录下,具体哪个小角落就得看你的操作系统啦。 3. 自定义日志文件路径及格式 如果你希望自定义日志文件的位置和名称,可以通过以下方式设置: javascript log.transports.file.getFile().path = path.join(app.getPath('userData'), 'custom-log.log'); 同时,electron-log也支持多种格式化选项,包括JSON、pretty-print等,可以根据需求调整: javascript log.transports.file.format = '{h}:{i}:{s} {level}: {text}'; 4. 思考与讨论 值得注意的是,虽然我们在渲染进程中直接调用了electron-log,但实际上所有的日志都通过IPC通信机制传递给主进程,再由主进程负责实际的写入文件操作。这么干,既能确保安全,防止渲染进程直接去摆弄磁盘,还能让日志管理变得简单省事儿多了。 在整个过程中,electron-log不仅充当了开发者的眼睛,洞察每一处可能的问题点,还像一本详尽的操作手册,忠实记录着应用运行的每一步足迹。这种实时、细致入微的日志系统,绝对是我们Electron应用背后的强大后盾,让我们的应用跑得既稳又强。 总的来说,通过electron-log,我们在 Electron 渲染进程中记录和输出日志变得轻松易行,大大提高了调试效率和问题定位的速度。每一个开发者都该好好利用这些工具,让咱们的应用程序像人一样“开口说话”,把它们的“心里话”都告诉我们。
2023-10-02 19:00:44
551
岁月如歌_
Bootstrap
...供的on()或click()等方法进行事件绑定。但是,初学者可能因为不熟悉这些API而导致事件无法触发: javascript // 错误示例:尝试直接在元素上绑定事件,而不是在DOM加载完成后 $('myModal').click(function() { // 这里的逻辑不会执行,因为在元素渲染到页面之前就进行了绑定 }); // 正确示例:应在DOM加载完成后再绑定事件 $(document).ready(function () { $('myModal').on('click', function() { // 这里的逻辑会在点击时执行 }); }); 3.2 动态生成的组件事件丢失 当我们在运行时动态添加Bootstrap组件时,原有的静态绑定事件可能无法捕获新生成元素的事件: javascript // 错误示例:先绑定事件,后动态创建元素 $('body').on('click', 'dynamicModal', function() { // 这里并不会处理后来动态添加的modal的点击事件 }); // 动态创建Modal var newModal = $(' ... '); $('body').append(newModal); // 正确示例:使用事件委托来处理动态生成元素的事件 $('body').on('click', '.modal', function() { // 这样可以处理所有已存在及将来动态添加的modal的点击事件 }); 3.3 组件初始化顺序问题 Bootstrap组件需要在HTML结构完整构建且相关CSS、JS文件加载完毕后进行初始化。若提前或遗漏初始化步骤,可能导致事件未被正确绑定: javascript // 错误示例:没有调用.modal('show')来初始化模态框 var myModal = $('myModal'); myModal.click(function() { // 如果没有初始化,这里的点击事件不会生效 }); // 正确示例:确保在绑定事件前已经初始化了组件 var myModal = $('myModal'); myModal.modal({ show: false }); // 初始化模态框 myModal.on('click', function() { myModal.modal('toggle'); // 点击时切换模态框显示状态 }); 4. 结论与思考 综上所述,Bootstrap组件事件的正确绑定对于保证应用程序功能的完整性至关重要。咱们得好好琢磨一下Bootstrap究竟是怎么工作的,把它的那些事件绑定的独门绝技掌握透彻,特别是对于那些动态冒出来的内容以及组件初始化这一块儿,得多留个心眼儿,重点研究研究。同时,理解并熟练运用jQuery的事件委托机制也是解决问题的关键所在。实践中不断探索、调试和优化,才能让我们的Bootstrap项目更加健壮而富有活力。让我们一起在编程的道路上,用心感受每一个组件事件带来的“心跳”,体验那微妙而美妙的交互瞬间吧!
2023-01-21 12:58:12
544
月影清风
转载文章
...ouseEvent.CLICK,clickHandler); } private function clickHandler(e:MouseEvent) { if (bt.label=="请点击链接") { bt.label="请点击断开"; nc=new NetConnection(); nc.connect("rtmp://localhost/viniFMS"); nc.addEventListener(NetStatusEvent.NET_STATUS,statusHandler); nc.call("sayServermsg",myRespond,"Hi"); } else { txt.text=""; bt.label="请点击链接"; nc.close(); } } private function statusHandler(e:NetStatusEvent) { if (e.info.code=="NetConnection.Connect.Success") { trace("ok"); } } private function success(result:Object) { trace("成功:"+result.toString()); txt.text=result.toString(); } private function failed(result:Object) { trace("失败:"+result.toString()); } } } 将as文件保存为Main.as 在test.fla的属性那的文档类输入Main。保存。 Three:建立通讯文件(.asc) 1.选择文件>新建>actionscript通信文件。 输入以下代码: application.onConnect=function(client){ application.acceptConnection(client); client.sayServermsg=function(msg){ return msg+",欢迎你来到FMS的世界 !"; } } 将文件保存到fms的application的文件夹下的viniFMS文件夹下,文件名为:main.asc. 确保FMS的服务已经打开,80端口没有被php等占用。 然后运行flash,点击按钮。就会有结果出现了。如下图所示。 再点击按钮。关闭连接。再点就是打开。如此循环。客户端会得到服务器端返回的 数据。 一个客户端用actionscript编码来连接到服务器,处理事件,和做其它工作。通过flash CS3你可以使用actionscript 3.0,2.0或1.0,但是actionscript3.0提供更多特性。要想使用flex,你必须使用actionscript 3.0. Actionscript3.0显著的不同于actionscript 2.0。这个向导假设你是在正在编写actionscript 3.0的类,这些类是一些外部的.as文件,有符合你的开发环境的目录结构的包的名称 转载于:https://blog.51cto.com/vini123/681426 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_33895475/article/details/91647859。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-09-10 18:10:29
65
转载
转载文章
...ref="" ng-click="reSearch(0)">全部评价({$total})</a></span> <span><a href="" ng-click="reSearch(1)">好评({$good})</a></span> <span><a href="" ng-click="reSearch(2)">中评({$medium})</a></span> <span><a href="" ng-click="reSearch(3)">差评({$pool})</a></span> </p></div></div><ul class="_comments" ><li ng-repeat="item in commentlist"><div class="fl"><img src="{ {item.image} }" alt="" /><p class="tel">{ { item.cellphone } }</p></div><div class="fr"><div class="desc"><p>{ { item.content } }</p><div class="tips"><div class="tip">实用高效</div><div class="tip">服务态度好</div></div><p class="doservice"><span> 办理业务:香港公司注册</span> <span class="datetime">{ {item.add_time} }</span></p></div></div></li> </ul><div class="pagination" ng-if="totalNum!=1"><a ng-if="hasPrev()" ng-click="paging($event,0)">上一页</a><a ng-click="paging($event,1)">1</a><a ng-click="paging($event,2)">2</a><a ng-if="totalNum>2" ng-click="paging($event,3)">3</a><a ng-if="hasNext()" ng-click="paging($event,-1)">下一页</a><a ng-click="paging($event,-2)">末页</a><a>总共{ {totalNum} }页</a></div></div> js代码 var app=angular.module('myApp',[]);app.controller('commCtrl', function($scope, $http) {var reSearch=function(postPoints){var postData={'id':goods_id, //产品id'post_points':postPoints||$scope.paginationConf.postPoints, //全部0,好评1,中评2,差评3'limit':$scope.paginationConf.itemsPerPage, //行数'page':$scope.paginationConf.currentPage //页数};$http({method: 'POST',url: '/comment',data:postData,}).then(function successCallback(response) {// 请求成功执行代码// console.log(response.data)$scope.totalNum=Math.ceil(response.data.total/$scope.paginationConf.itemsPerPage);$scope.commentlist=response.data.list;}, function errorCallback(response) {// 请求失败执行代码console.log('请求失败')});}$scope.reSearch=reSearch;$scope.paginationConf={firstPage:1, //起始页 currentPage:1, //当前页itemsPerPage:5, //每页展示的数据条数postPoints:0 // 全部0,好评1,中评2,差评3}; $scope.paging=function(evt,nType){$(evt.target).addClass("active").siblings().removeClass("active");switch(nType){case -2:$scope.paginationConf.currentPage=$scope.totalNum;break;case -1:$scope.paginationConf.currentPage++;break;case 1:$scope.paginationConf.currentPage=1;break;case 2:$scope.paginationConf.currentPage=2;break;case 3:$scope.paginationConf.currentPage=3;break;default:$scope.paginationConf.currentPage--;} $scope.reSearch(0);}$scope.hasNext=function(){if($scope.paginationConf.currentPage<$scope.totalNum){return true;}else{return false;} }$scope.hasPrev=function(){if($scope.paginationConf.currentPage>1){return true;}else{return false;} }$scope.reSearch(0);// $scope.$watch('paginationConf.currentPage + paginationConf.postPoints', reSearch(0));}) 第一次用angular分页,处理的有些简陋,还有一些疑问留着下次解答: 1.ng-controller放在排序的外层包裹内容显示不出来,也不报错,放在最外层或者body下面包裹的第一层上才显示数据 在angular的函数里面获取元素de属性值,可通过click方法传参($event.target),相当于jquery的this 更多参考:https://www.cnblogs.com/sxz2008/p/6379427.html 本篇文章为转载内容。原文链接:https://blog.csdn.net/samscat/article/details/103328461。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-12 14:36:16
71
转载
转载文章
...%BA&s=121&click=0&page=";//遍历执行,获取所有的数据 for (int i = 1; i < 10; i = i + 2) {//发起请求进行访问,获取页面数据,先访问第一页 String html = this.httpUtils.getHtml(url +i);//解析页面数据,保存数据到数据库中 this.parseHtml(html); } System.out.println("执行完成"); }//解析页面,并把数据保存到数据库中 private void parseHtml(String html) throwsException {//使用jsoup解析页面 Document document =Jsoup.parse(html);//获取商品数据 Elements spus = document.select("divJ_goodsList > ul > li");//遍历商品spu数据 for(Element spuEle : spus) {//获取商品spu String attr = spuEle.attr("data-spu");long spu = Long.parseLong(attr.equals("")?"0":attr);//Long spu = Long.parseLong(spuEle.attr("data-spu"));//获取商品sku数据 Elements skus = spuEle.select("li.ps-item img");for(Element skuEle : skus) {//获取商品sku Long sku = Long.parseLong(skuEle.attr("data-sku"));//判断商品是否被抓取过,可以根据sku判断 Item param = newItem(); param.setSku(sku); List list = this.itemService.findAll(param);//判断是否查询到结果 if (list.size() > 0) {//如果有结果,表示商品已下载,进行下一次遍历 continue; }//保存商品数据,声明商品对象 Item item = newItem();//商品spu item.setSpu(spu);//商品sku item.setSku(sku);//商品url地址 item.setUrl("https://item.jd.com/" + sku + ".html");//创建时间 item.setCreated(newDate());//修改时间 item.setUpdated(item.getCreated());//获取商品标题 String itemHtml = this.httpUtils.getHtml(item.getUrl()); String title= Jsoup.parse(itemHtml).select("div.sku-name").text(); item.setTitle(title);//获取商品价格 String priceUrl = "https://p.3.cn/prices/mgets?skuIds=J_"+sku; String priceJson= this.httpUtils.getHtml(priceUrl);//解析json数据获取商品价格 double price = MAPPER.readTree(priceJson).get(0).get("p").asDouble(); item.setPrice(price);//获取图片地址 String pic = "https:" + skuEle.attr("data-lazy-img").replace("/n9/","/n1/"); System.out.println(pic);//下载图片 String picName = this.httpUtils.getImage(pic); item.setPic(picName);//保存商品数据 this.itemService.save(item); } } } } 分享一下我学习中遇到的问题: 1.爬取数据为null,需要登录京东 看到这段代码应该就明白了吧,就是京东发现并非人为操作,需要登陆账号了。解决办法也很简单,只需要自己模拟浏览器登陆即可 在HttpUttils加上这段,两个方法中的HTTPGet对象都需要设置一下。 //设置请求头模拟浏览器 httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0"); 2.java.lang.NumberFormatException: For input string: "",获取的spu为空串,加上一个前置空串判断即可 解决如下: //获取商品spu String attr = spuEle.attr("data-spu");//判断是否为空串 long spu = Long.parseLong(attr.equals("")?"0":attr); 以上两个bug是我学习遇到的,现已解决,爬取数据如下: 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_32161697/article/details/114506244。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-03-13 10:48:12
103
转载
转载文章
...ext('登录').click() 通过标签中文本的模糊匹配查找driver.find_element_by_partial_link_text('录').click() 获取标签元素常用的一共有8种定位方式,而Selenium实际提供了18种定位方式,还有8种是上面的复数形式,实际种一般用不到,还有2种是这上面16种的底层封装。参数化的一种调用方式。 复数: e=driver.find_elements_by_class_name('classname')[0]e.send_keys(1111)print(e)print(type(e))接受两个参数 形参1 以什么形式定位 形参2 定位value是什么driver.find_element_by_id('i1')driver.find_element('id','i1').send_keys(1111)driver.find_elements('id','i1')[0].send_keys(2222) 一般都直接用driver.find_element_by_css_selector(),因为底层只要符合w3c的都转化为css_selector 窗口操作: 获取当前浏览器的大小driver.get_window_size()通过宽和高对size进行设置driver.set_window_size('100','200') 获取当前窗口针对于Windows的位置的坐标x,ydriver.get_window_position() 设置当前窗口针对Windows的位置,x,ydriver.set_window_position(20,20) 最大化当前窗口,不需要传参driver.maximize_window() 返回当前操作的浏览器句柄driver.current_window_handle 返回所有打开server的浏览器句柄driver.window_handles 截取当前页面: from selenium import webdriverdriver=webdriver.Chrome()driver.get("http://www.baidu.com")driver.get_screenshot_as_file('d.png') 执行JavaScript语句 执行JavaScript语句driver.execute_script('window.scrollTo(0,0);')执行js的api,通过js来操作滚动条,滚动到最上面 关闭与退出: 当开启多个页面时,关闭当前页面driver.close()退出并关闭所有页面驱动driver.quit() from selenium import webdriverdriver=webdriver.Chrome()driver.get("http://ui.imdsx.cn/uitester/")driver.maximize_window()将窗口放大driver.execute_script('window.scrollTo(0,0);')执行js的apidriver.find_element_by_css_selector('[href="/new-index/"]').click()handles=driver.window_handles返回所有打开server的浏览器句柄print(handles)返回listdriver.switch_to.window(handles[1])driver.find_element_by_css_selector('newtag').send_keys(1111)找到新页面上的元素driver.close()关闭当前tab页 from selenium import webdriverdriver=webdriver.Chrome()driver.get("http://ui.imdsx.cn/uitester/")driver.maximize_window()将窗口放大driver.execute_script('window.scrollTo(0,0);')执行js的apidriver.find_element_by_css_selector('[href="/new-index/"]').click()handles=driver.window_handlesprint(handles)driver.switch_to.window(handles[1])driver.find_element_by_css_selector('newtag').send_keys(1111)driver.quit() 关闭所有页面,结束服务 其他 返回页面源码driver.page_source 返回tag标题driver.title 返回当前Urldriver.current_url 获取浏览器名称 如:chromedriver.name ElementApi接口 根据标签属性名称,获取属性valueelement.get_attribute('style') 向输入框输入字符串 如果input的type为file类型 可以输入文件绝对路径上传文件element.send_keys() 清除文本内容element.clear() 鼠标左键点击操作element.click() 通过属性名称获取属性element.get_property('id') 返回元素是否可见 True or Falseelement.is_displayed() 返回元素是否被选中 True or Falseelement.is_selected() 返回标签元素的名字element.tag_name 获取当前标签的宽和高element.size 获取元素的文本内容element.text 模仿回车按钮 提交数据element.submit() 获取当前元素的坐标element.location 截取图片element.screenshot() from selenium import webdriverdriver=webdriver.Chrome()driver.get("http://ui.imdsx.cn/uitester/")driver.maximize_window()将窗口放大driver.execute_script('window.scrollTo(0,0);')执行js的apie=driver.find_element_by_css_selector('i1')e.send_keys(1111)import timetime.sleep(1)e.clear() 清除文本框内内容 转载于:https://www.cnblogs.com/wxcx/p/8934540.html 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_34377065/article/details/94686128。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-03 12:51:11
44
转载
转载文章
...n, hover, click, or related to data (eg. column look if a value is down). The engine will automatically apply the required properties as needed, animating between old and new values smoothly. Create and apply custom states via the API. Multi-type multi-axis support Add any number of axes of any type. Create overlaid comparison of different time scales. Use any mix of dimensional values: numbers, dates, categories, or duration. Adapters “Adapters” functionality allows plugging in custom code to dynamically override just about any setting or data value. Text formatting All text labels – tooltips, axis labels, titles, etc. – now support rich text formatting options, like changing colors, font weight, or applying just about any styling option from the CSS arsenal. In addition to formatting support, labels can now contain in-line placeholders for real data, with the ability to apply custom formatting to values. Accessibility & Interactivity Accessibility Accessibility was riding shotgun when amCharts 5 was being developed. All interactive elements are TAB-selectable, with customizable roles, order, and screen-reader texts. Everything that can be moved by touch or mouse, can be moved by keyboard. Everything that can be clicked or toggled, can be interacted with with keyboard, too. Touch support Charts have been designed to work with touch devices out-of-the-box. They will work not only on phones or tablets, but also touch capable computers. Under the hood Built with TypeScript Supports strong type and error checking in TypeScript applications. Enjoy code completion, error checking and dynamic help popups in major IDEs. Full support for TypeScript and ES6 modules. 100% for JavaScript Can be fully used in any vanilla JavaScript application. amCharts 5 does not use or rely on globals, external frameworks or 3rd party libraries. Universal rendering engine Can be used to build dynamic, interactive Canvas-based interfaces and applications. Add various elements to the screen, make them interactive, with a few lines of code. Make them clickable, draggable, hoverable, using built-in interactivity functionality. Our universal layout engine will place, size and arrange elements according to set rules. 本篇文章为转载内容。原文链接:https://blog.csdn.net/john_dwh/article/details/127460821。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-09-17 18:18:34
350
转载
转载文章
... the user clicks the Log In via Google button, their browser is redirected to the Google authentication service and then redirected back to the GoogleLoginCallback action method once they are authenticated. 这意味着,当用户通过点击Google按钮进行登录时,浏览器被重定向到Google的认证服务,一旦在那里认证之后,便被重定向回GoogleLoginCallback动作方法。 I get details of the external login by calling the GetExternalLoginInfoAsync of the IAuthenticationManager implementation, like this: 我通过调用IAuthenticationManager实现的GetExternalLoginInfoAsync方法,我获得了外部登录的细节,如下所示: ...ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();... The ExternalLoginInfo class defines the properties shown in Table 15-10. ExternalLoginInfo类定义的属性如表15-10所示: Table 15-10. The Properties Defined by the ExternalLoginInfo Class 表15-10. ExternalLoginInfo类所定义的属性 Name 名称 Description 描述 DefaultUserName Returns the username 返回用户名 Email Returns the e-mail address 返回E-mail地址 ExternalIdentity Returns a ClaimsIdentity that identities the user 返回标识该用户的ClaimsIdentity Login Returns a UserLoginInfo that describes the external login 返回描述外部登录的UserLoginInfo I use the FindAsync method defined by the user manager class to locate the user based on the value of the ExternalLoginInfo.Login property, which returns an AppUser object if the user has been authenticated with the application before: 我使用了由用户管理器类所定义的FindAsync方法,以便根据ExternalLoginInfo.Login属性的值对用户进行定位,如果用户之前在应用程序中已经认证,该属性会返回一个AppUser对象: ...AppUser user = await UserManager.FindAsync(loginInfo.Login);... If the FindAsync method doesn’t return an AppUser object, then I know that this is the first time that this user has logged into the application, so I create a new AppUser object, populate it with values, and save it to the database. I also save details of how the user logged in so that I can find them next time: 如果FindAsync方法返回的不是AppUser对象,那么我便知道这是用户首次登录应用程序,于是便创建了一个新的AppUser对象,填充该对象的值,并将其保存到数据库。我还保存了用户如何登录的细节,以便下次能够找到他们: ...result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);... All that remains is to generate an identity the user, copy the claims provided by Google, and create an authentication cookie so that the application knows the user has been authenticated: 剩下的事情只是生成该用户的标识了,拷贝Google提供的声明(Claims),并创建一个认证Cookie,以使应用程序知道此用户已认证: ...ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);... 15.4.2 Testing Google Authentication 15.4.2 测试Google认证 There is one further change that I need to make before I can test Google authentication: I need to change the account verification I set up in Chapter 13 because it prevents accounts from being created with e-mail addresses that are not within the example.com domain. Listing 15-25 shows how I removed the verification from the AppUserManager class. 在测试Google认证之前还需要一处修改:需要修改第13章所建立的账号验证,因为它不允许example.com域之外的E-mail地址创建账号。清单15-25显示了如何在AppUserManager类中删除这种验证。 Listing 15-25. Disabling Account Validation in the AppUserManager.cs File 清单15-25. 在AppUserManager.cs文件中取消账号验证 using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Microsoft.AspNet.Identity.Owin;using Microsoft.Owin;using Users.Models; namespace Users.Infrastructure {public class AppUserManager : UserManager<AppUser> {public AppUserManager(IUserStore<AppUser> store): base(store) {}public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options,IOwinContext context) {AppIdentityDbContext db = context.Get<AppIdentityDbContext>();AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db)); manager.PasswordValidator = new CustomPasswordValidator {RequiredLength = 6,RequireNonLetterOrDigit = false,RequireDigit = false,RequireLowercase = true,RequireUppercase = true}; //manager.UserValidator = new CustomUserValidator(manager) {// AllowOnlyAlphanumericUserNames = true,// RequireUniqueEmail = true//};return manager;} }} Tip you can use validation for externally authenticated accounts, but I am just going to disable the feature for simplicity. 提示:也可以使用外部已认证账号的验证,但这里出于简化,取消了这一特性。 To test authentication, start the application, click the Log In via Google button, and provide the credentials for a valid Google account. When you have completed the authentication process, your browser will be redirected back to the application. If you navigate to the /Claims/Index URL, you will be able to see how claims from the Google system have been added to the user’s identity, as shown in Figure 15-7. 为了测试认证,启动应用程序,通过点击“Log In via Google(通过Google登录)”按钮,并提供有效的Google账号凭据。当你完成了认证过程时,浏览器将被重定向回应用程序。如果导航到/Claims/Index URL,便能够看到来自Google系统的声明(Claims),已被添加到用户的标识中了,如图15-7所示。 Figure 15-7. Claims from Google 图15-7. 来自Google的声明(Claims) 15.5 Summary 15.5 小结 In this chapter, I showed you some of the advanced features that ASP.NET Identity supports. I demonstrated the use of custom user properties and how to use database migrations to preserve data when you upgrade the schema to support them. I explained how claims work and how they can be used to create more flexible ways of authorizing users. I finished the chapter by showing you how to authenticate users via Google, which builds on the ideas behind the use of claims. 本章向你演示了ASP.NET Identity所支持的一些高级特性。演示了自定义用户属性的使用,还演示了在升级数据架构时,如何使用数据库迁移保护数据。我解释了声明(Claims)的工作机制,以及如何将它们用于创建更灵活的用户授权方式。最后演示了如何通过Google进行认证结束了本章,这是建立在使用声明(Claims)的思想基础之上的。 本篇文章为转载内容。原文链接:https://blog.csdn.net/gz19871113/article/details/108591802。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-28 08:49:21
282
转载
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
ncurses-based tools (例如:top, htop)
- 监控系统资源如CPU、内存等。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"