我已经x1 = int(data_x1)转成int了,为什么还是报错'str' object has no attribute 'append'?

data-x1是我切割出来的,元素内容是1,我想用data.append(x1)让他成为一个数组,为什么会报错?怎么解决?

2个回答

data 的类型是str ,而不是list

可以先赋值给data一个空数组

加上convrt.试一下。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
openCV_python自带的ANN进行手写字体识别,报错。求助
![图片说明](https://img-ask.csdn.net/upload/202001/31/1580479207_695592.png)![图片说明](https://img-ask.csdn.net/upload/202001/31/1580479217_497206.png) 我用python3.6按照《OpenCV3计算机视觉》书上代码进行手写字识别,识别率很低,运行时还报了错:OpenCV(3.4.1) Error: Assertion failed ((type == 5 || type == 6) && inputs.cols == layer_sizes[0]) in cv::ml::ANN_MLPImpl::predict, file C:\projects\opencv-python\opencv\modules\ml\src\ann_mlp.cpp, line 411 ``` 具体代码如下:求大佬指点下 import cv2 import numpy as np import digits_ann as ANN def inside(r1, r2): x1, y1, w1, h1 = r1 x2, y2, w2, h2 = r2 if (x1 > x2) and (y1 > y2) and (x1 + w1 < x2 + w2) and (y1 + h1 < y2 + h2): return True else: return False def wrap_digit(rect): x, y, w, h = rect padding = 5 hcenter = x + w / 2 vcenter = y + h / 2 if (h > w): w = h x = hcenter - (w / 2) else: h = w y = vcenter - (h / 2) return (int(x - padding), int(y - padding), int(w + padding), int(h + padding)) ''' 注意:首次测试时,建议将使用完整的训练数据集,且进行多次迭代,直到收敛 如:ann, test_data = ANN.train(ANN.create_ANN(100), 50000, 30) ''' ann, test_data = ANN.train(ANN.create_ANN(10), 50000, 1) # 调用所需识别的图片,并处理 path = "C:\\Users\\64601\\PycharmProjects\Ann\\images\\numbers.jpg" img = cv2.imread(path, cv2.IMREAD_UNCHANGED) bw = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) bw = cv2.GaussianBlur(bw, (7, 7), 0) ret, thbw = cv2.threshold(bw, 127, 255, cv2.THRESH_BINARY_INV) thbw = cv2.erode(thbw, np.ones((2, 2), np.uint8), iterations=2) image, cntrs, hier = cv2.findContours(thbw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) rectangles = [] for c in cntrs: r = x, y, w, h = cv2.boundingRect(c) a = cv2.contourArea(c) b = (img.shape[0] - 3) * (img.shape[1] - 3) is_inside = False for q in rectangles: if inside(r, q): is_inside = True break if not is_inside: if not a == b: rectangles.append(r) for r in rectangles: x, y, w, h = wrap_digit(r) cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) roi = thbw[y:y + h, x:x + w] try: digit_class = ANN.predict(ann, roi)[0] except: print("except") continue cv2.putText(img, "%d" % digit_class, (x, y - 1), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0)) cv2.imshow("thbw", thbw) cv2.imshow("contours", img) cv2.waitKey() cv2.destroyAllWindows() ####### import cv2 import pickle import numpy as np import gzip """OpenCV ANN Handwritten digit recognition example Wraps OpenCV's own ANN by automating the loading of data and supplying default paramters, such as 20 hidden layers, 10000 samples and 1 training epoch. The load data code is taken from http://neuralnetworksanddeeplearning.com/chap1.html by Michael Nielsen """ def vectorized_result(j): e = np.zeros((10, 1)) e[j] = 1.0 return e def load_data(): with gzip.open('C:\\Users\\64601\\PycharmProjects\\Ann\\mnist.pkl.gz') as fp: # 注意版本不同,需要添加传入第二个参数encoding='bytes',否则出现编码错误 training_data, valid_data, test_data = pickle.load(fp, encoding='bytes') fp.close() return (training_data, valid_data, test_data) def wrap_data(): # tr_d数组长度为50000,va_d数组长度为10000,te_d数组长度为10000 tr_d, va_d, te_d = load_data() # 训练数据集 training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]] training_results = [vectorized_result(y) for y in tr_d[1]] training_data = list(zip(training_inputs, training_results)) # 校验数据集 validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]] validation_data = list(zip(validation_inputs, va_d[1])) # 测试数据集 test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]] test_data = list(zip(test_inputs, te_d[1])) return (training_data, validation_data, test_data) def create_ANN(hidden=20): ann = cv2.ml.ANN_MLP_create() # 建立模型 ann.setTrainMethod(cv2.ml.ANN_MLP_RPROP | cv2.ml.ANN_MLP_UPDATE_WEIGHTS) # 设置训练方式为反向传播 ann.setActivationFunction( cv2.ml.ANN_MLP_SIGMOID_SYM) # 设置激活函数为SIGMOID,还有cv2.ml.ANN_MLP_IDENTITY,cv2.ml.ANNMLP_GAUSSIAN ann.setLayerSizes(np.array([784, hidden, 10])) # 设置层数,输入784层,输出层10 ann.setTermCriteria((cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 100, 0.1)) # 设置终止条件 return ann def train(ann, samples=10000, epochs=1): # tr:训练数据集; val:校验数据集; test:测试数据集; tr, val, test = wrap_data() for x in range(epochs): counter = 0 for img in tr: if (counter > samples): break if (counter % 1000 == 0): print("Epoch %d: Trained %d/%d" % (x, counter, samples)) counter += 1 data, digit = img ann.train(np.array([data.ravel()], dtype=np.float32), cv2.ml.ROW_SAMPLE, np.array([digit.ravel()], dtype=np.float32)) print("Epoch %d complete" % x) return ann, test def predict(ann, sample): resized = sample.copy() rows, cols = resized.shape if rows != 28 and cols != 28 and rows * cols > 0: resized = cv2.resize(resized, (28, 28), interpolation=cv2.INTER_CUBIC) return ann.predict(np.array([resized.ravel()], dtype=np.float32)) ```
spark运行scala的jar包
![图片说明](https://img-ask.csdn.net/upload/202002/05/1580887545_330719.png) ![图片说明](https://img-ask.csdn.net/upload/202002/05/1580887568_992291.png) ![图片说明](https://img-ask.csdn.net/upload/202002/05/1580887616_449280.png) 有人遇到过类似的问题吗? 我的尝试: 当没Master节点的Worker进程,运行会报错,当开启了Master节点的Worker进程有时不会报错,但是会说内存不够,但是我觉得不是这个问题,也能得出一定的结果,但并不是预期的结果。 执行的命令:bin/spark-submit --master spark://node1:7077 --class cn.itcast.WordCount_Online --executor-memory 1g --total-executor-cores 1 ~/data/spark_chapter02-1.0-SNAPSHOT.jar /spark/test/words.txt /spark/test/out jar包是在idea中打包的,用的是scala语言,主要作用是词频统计 scala代码: ``` package cn.itcast import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} object WordCount_Online { def main(args: Array[String]):Unit={ val sparkConf = new SparkConf().setAppName("WordCount_Online") val sparkContext = new SparkContext(sparkConf) val data : RDD[String] = sparkContext.textFile(args(0)) val words :RDD[String] = data.flatMap(_.split(" ")) val wordAndOne :RDD[(String,Int)] = words.map(x => (x,1)) val result :RDD[(String,Int)] = wordAndOne.reduceByKey(_+_) result.saveAsTextFile(args(1)) sparkContext.stop() } } ``` 我也做了很多尝试,希望懂的人可以交流一下
TensorFlow报错:Shape (44, ?) must have rank at least 3 ?
用TensorFlow执行RNN,报错ValueError: Shape (44, ?) must have rank at least 3,下面是程序的部分代码,请问应该在哪里修改下?谢谢 解析函数: ``` feature = ['feature1',......,'feature44'] label = 'label2' featureNames = list(feature) featureNames.append(label) columns = [tf.FixedLenFeature(shape=[1], dtype=tf.float32) for k in featureNames] featuresDict = dict(zip(featureNames, columns)) def parse_tfrecord(example_proto): parsed_features = tf.parse_single_example(example_proto, featuresDict) labels = parsed_features.pop(label) return parsed_features, tf.cast(labels, tf.int32) ``` 输入函数(原始数据是有44个特征值的数值序列,每个序列为一样本): ``` def tfrecord_input_fn(fileName,numEpochs=None,shuffle=True,batchSize=None): #读取tfrecord数据 dataset = tf.data.TFRecordDataset(fileName, compression_type='GZIP') #执行解析函数 dataset = dataset.map(parse_tfrecord) #打乱数据 if shuffle: dataset = dataset.shuffle(buffer_size=batchSize * 100*numEpochs) #每32个样本作为一个batch dataset = dataset.batch(32) #重复数据 dataset = dataset.repeat(numEpochs) print('features:',features) print('labels:',labels) iterator = dataset.make_one_shot_iterator() features, labels = iterator.get_next() return features, labels ``` 打印返回值结果: ``` features: {'feature1': <tf.Tensor 'IteratorGetNext_21:0' shape=(?, 1) dtype=float32>, 'feature2': <tf.Tensor 'IteratorGetNext_21:1' shape=(?, 1) dtype=float32>,......, 'feature44': <tf.Tensor 'IteratorGetNext_21:43' shape=(?, 1) dtype=float32>} labels: Tensor("IteratorGetNext_21:44", shape=(?, 1), dtype=int32) ``` 执行网络后报错: ``` ValueError: Shape (44, ?) must have rank at least 3 ```
cuda 报错 CUDA_ERROR_LAUNCH_FAILED
template<typename T> __global__ void pooling_max_kernel (T* pooled, const T* data, const T* stochastic_value, const int mode, const int pooledWidth, const int pooledHeight, const int pooledVolume, const int width, const int height, const int poolWidth, const int poolHeight, const int strideX, const int strideY, const int padLeft, const int padTop) { int pooledIndex = threadIdx.x + blockIdx.x * blockDim.x; int stochastic_value_index=0; if (pooledIndex < pooledVolume) { int px = pooledIndex ; int py = px / pooledWidth ; int pz = py / pooledHeight ; px %= pooledWidth ; py %= pooledHeight ; data += pz * (width*height) ; int x1 = px * strideX - padLeft ; int y1 = py * strideY - padTop ; int x2 = min(x1 + poolWidth, width) ; int y2 = min(y1 + poolHeight, height) ; x1 = max(x1, 0) ; y1 = max(y1, 0) ; //T *savedata;T *dataprob; //cudaMalloc((void**)&savedata,sizeof(T)*9);cudaMalloc((void**)&dataprob,sizeof(T)*9);/////////////////////////////////////////////////定义变量分配内存 T savedata[9]={0};T dataprob[10]={0};dataprob[0]=0; T sumdata=0;T weightsum=0;int i=0;/////////////////////////////lyz //T bestValue = data[y1 * width + x1] ; for (int y = y1 ; y < y2 ; ++y) { for (int x = x1 ; x < x2 ; ++x) { //bestValue = max(bestValue, data[y * width + x]) ; savedata[i]=data[y * width + x]; sumdata=sumdata+data[y * width + x]; i=i+1; if (i>8) {i=0;} } } if(mode==0) { T randdata = stochastic_value[pooledIndex]; if (sumdata>0) { for(int j=0;j<poolWidth*poolHeight;++j) { dataprob[j+1]=dataprob[j]+savedata[j]/sumdata; if (randdata<dataprob[j+1]) { stochastic_value_index=j; break; } } pooled[pooledIndex] = savedata[stochastic_value_index] ; } else { pooled[pooledIndex] = 0 ; } } else { if (sumdata>0) { for(int j=0;j<poolWidth*poolHeight;++j) { weightsum=weightsum+savedata[j]*savedata[j]/sumdata; } pooled[pooledIndex] = weightsum ; } else { pooled[pooledIndex] = 0 ; } } //cudaFree(savedata);cudaFree(dataprob); } } 另,在kernel函数中定义变量需要分配内存吗,我之前用注释掉的那个分配内存,编译的时候回报错
tensorflow训练网络报错Invalid argument
##1.问题 程序报错,提示:Invalid argument: You must feed a value for placeholder tensor 'Placeholder_1' with dtype float and shape [?,24] ##2.代码 ``` import time import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt # import dataset input_Dir = 'E:/data/input_H.csv' output_Dir = 'E:/data/output_H.csv' x_data = pd.read_csv(input_Dir, header = None) y_data = pd.read_csv(output_Dir, header = None) x_data = x_data.values y_data = y_data.values x_data = x_data.astype('float32') y_data = y_data.astype('float32') print("DATASET READY") # from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.2, random_state=1) row, column = x_train.shape row = float(row) # define structure of neural network n_hidden_1 = 250 n_hidden_2 = 128 n_input = 250 n_classes = 24 #initialize parameters x = tf.placeholder(tf.float32, [None, n_input]) y = tf.placeholder(tf.float32, [None, n_classes]) keep_prob = tf.placeholder(tf.float32) stddev = 0.1 weights = { 'w1': tf.Variable(tf.random_normal([n_input, n_hidden_1], stddev=stddev)), 'w2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], stddev=stddev)), 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes], stddev=stddev)) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1], stddev=stddev)), 'b2': tf.Variable(tf.random_normal([n_hidden_2], stddev=stddev)), 'out': tf.Variable(tf.random_normal([n_classes], stddev=stddev)) } print("NETWORK READY") # forward propagation def multilayer_perceptron(_X, _weights, _biases): layer_1 = tf.nn.leaky_relu(tf.add(tf.matmul(_X, _weights['w1']), _biases['b1'])) layer_2 = tf.nn.leaky_relu(tf.add(tf.matmul(layer_1, _weights['w2']), _biases['b2'])) return (tf.add(tf.matmul(layer_2, _weights['out']), _biases['out'])) # pred = multilayer_perceptron(x, weights, biases) cost = tf.reduce_mean(tf.square(y - pred)) optm = tf.train.GradientDescentOptimizer(learning_rate=0.03).minimize(cost) init = tf.global_variables_initializer() print("FUNCTIONS READY") n_epochs = 100000 batch_size = 512 n_batches = np.int(np.ceil(row / batch_size)) def fetch_batch(epoch, batch_index, batch_size): # 随机获取小批量数据 np.random.seed(epoch * n_batches + batch_index) indices = np.random.randint(row, size = batch_size) return x_train[indices], y_train[indices] iter = 10000 sess = tf.Session() sess.run(tf.global_variables_initializer()) feeds_test = {x: x_test, y: y_test, keep_prob: 1} for epoch in range(n_epochs): # 总共循环次数 for batch_index in range(n_batches): x_batch, y_batch = fetch_batch(epoch, batch_index, batch_size) feeds_train = {x: x_batch, y: y_batch, keep_prob: 1} sess.run(optm, feed_dict=feeds_train) print("EPOCH %d HAS FINISHED" % (epoch)) print("COST %d :" % (epoch)) print(sess.run(cost),feed_dict=feeds_train) print("\n") sess.close() print("FINISHED") ``` ##3.报错信息 Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1356, in _do_call return fn(*args) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1341, in _run_fn options, feed_dict, fetch_list, target_list, run_metadata) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1429, in _call_tf_sessionrun run_metadata) tensorflow.python.framework.errors_impl.InvalidArgumentError: 2 root error(s) found. (0) Invalid argument: You must feed a value for placeholder tensor 'Placeholder_1' with dtype float and shape [?,24] [[{{node Placeholder_1}}]] [[Mean/_7]] (1) Invalid argument: You must feed a value for placeholder tensor 'Placeholder_1' with dtype float and shape [?,24] [[{{node Placeholder_1}}]] 0 successful operations. 0 derived errors ignored. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\IPython\core\interactiveshell.py", line 3296, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-2-762bc58e4306>", line 1, in <module> runfile('C:/Users/Administrator/Desktop/main/demo3.py', wdir='C:/Users/Administrator/Desktop/main') File "E:\Program Files\PyCharm 2019.1.3\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile #求问问题出在什么地方?
我在用facenet模型中的classifier.py文件中训练自己的数据集的时候配置了相关参数所在的路径,但是却发生了如下报错,请问是什么原因?
作为一个刚入门的小白在这方面的学习还有许多的不懂,我在用facenet模型中的classifier.py文件中训练自己的数据集的时候配置了相关参数所在的路径,但是却发生了如下报错,请问是什么原因? ``` def parse_arguments(argv): parser = argparse.ArgumentParser() parser.add_argument('mode', type=str, choices=['TRAIN', 'CLASSIFY'], help='Indicates if a new classifier should be trained or a classification ' + 'model should be used for classification', default='TRAIN')#训练模型 parser.add_argument('data_dir', type=str, help='Path to the data directory containing aligned LFW face patches.',default='D:/pyCharm/facenet/data_dir/African_convert')#添加数据集文件夹 parser.add_argument('model', type=str, help='Could be either a directory containing the meta_file and ckpt_file or a model protobuf (.pb) file',default='D:/pyCharm/facenet/20170512-110547') parser.add_argument('classifier_filename', help='Classifier model file name as a pickle (.pkl) file. ' + 'For training this is the output and for classification this is an input.' ,default='pick/classifier.pkl') parser.add_argument('--use_split_dataset', help='Indicates that the dataset specified by data_dir should be split into a training and test set. ' + 'Otherwise a separate test set can be specified using the test_data_dir option.', action='store_true') parser.add_argument('--test_data_dir', type=str, help='Path to the test data directory containing aligned images used for testing.') parser.add_argument('--batch_size', type=int, help='Number of images to process in a batch.', default=90) parser.add_argument('--image_size', type=int, help='Image size (height, width) in pixels.', default=160) parser.add_argument('--seed', type=int, help='Random seed.', default=666) parser.add_argument('--min_nrof_images_per_class', type=int, help='Only include classes with at least this number of images in the dataset', default=20) parser.add_argument('--nrof_train_images_per_class', type=int, help='Use this number of images from each class for training and the rest for testing', default=10) return parser.parse_args(argv) if __name__ == '__main__': main(parse_arguments(sys.argv[1:])) ``` 报错信息如下: usage: classifier.py [-h] [--use_split_dataset] [--test_data_dir TEST_DATA_DIR] [--batch_size BATCH_SIZE] [--image_size IMAGE_SIZE] [--seed SEED] [--min_nrof_images_per_class MIN_NROF_IMAGES_PER_CLASS] [--nrof_train_images_per_class NROF_TRAIN_IMAGES_PER_CLASS] {TRAIN,CLASSIFY} data_dir model classifier_filename classifier.py: error: the following arguments are required: mode, data_dir, model, classifier_filename ![图片说明](https://img-ask.csdn.net/upload/201910/12/1570866719_655865.jpg) ![图片说明](https://img-ask.csdn.net/upload/201910/12/1570867095_477948.jpg) 谢谢!!!
python报错:KeyError: 'user_id'
#coding:utf-8 import pandas as pd import numpy as np import time import datetime import gc from sklearn.preprocessing import LabelEncoder,OneHotEncoder def pre_process(data): cols = data.columns.tolist() keys = ['instance_id', 'day'] for k in keys: cols.remove(k) return data, cols def dorollWin(data): data['context_timestamp_str'] = data['context_timestamp'].astype(str) user_time_join = data.groupby(test.user_id)['context_timestamp_str'].agg(lambda x:';'.join(x)).reset_index() user_time_join.rename(columns={'context_timestamp_str':'user_time_join'},inplace = True) data = pd.merge(data,user_time_join,on=[test.user_id],how='left') user_shop_time_join = data.groupby([test.user_id,'shop_id'])['context_timestamp_str'].agg(lambda x:';'.join(x)).reset_index() user_shop_time_join.rename(columns={'context_timestamp_str':'user_shop_time_join'},inplace = True) data = pd.merge(data,user_shop_time_join,on=[test.user_id,'shop_id'],how='left') user_item_time_join = data.groupby([test.user_id,'item_id'])['context_timestamp_str'].agg(lambda x:';'.join(x)).reset_index() user_item_time_join.rename(columns={'context_timestamp_str':'user_item_time_join'},inplace = True) data = pd.merge(data,user_item_time_join,on=[test.user_id,'item_id'],how='left') data['index_']=data.index del user_time_join,user_shop_time_join,user_item_time_join nowtime=data.context_timestamp.values user_time=data.user_time_join.values user_shop_time=data.user_shop_time_join.values user_item_time=data.user_item_time_join.values data_len=data.shape[0] user_time_10_bf=np.zeros(data_len) user_time_10_af=np.zeros(data_len) user_shop_time_10_bf=np.zeros(data_len) user_shop_time_10_af=np.zeros(data_len) user_item_time_10_bf=np.zeros(data_len) user_item_time_10_af=np.zeros(data_len) a=time.time() for i in range(data_len): df1=nowtime[i] df2=user_time[i].split(';') df2_len=len(df2) for j in range(df2_len): if ((int(df2[j])-df1)<600) & ((int(df2[j])-df1)>0): user_time_10_bf[i]+=1 if ((int(df2[j])-df1)>-600) & ((int(df2[j])-df1)<0): user_time_10_af[i]+=1 df3=user_shop_time[i].split(';') df3_len=len(df3) for j in range(df3_len): if ((int(df3[j])-df1)<600) & ((int(df3[j])-df1)>0): user_shop_time_10_bf[i]+=1 if ((int(df3[j])-df1)>-600) & ((int(df3[j])-df1)<0): user_shop_time_10_af[i]+=1 df4=user_item_time[i].split(';') df4_len=len(df4) for j in range(df4_len): if ((int(df4[j])-df1)<600) & ((int(df4[j])-df1)>0): user_item_time_10_bf[i]+=1 if ((int(df4[j])-df1)>-600) & ((int(df4[j])-df1)<0): user_item_time_10_af[i]+=1 print(time.time()-a) data['user_count_10_bf']=user_time_10_bf data['user_count_10_af']=user_time_10_af data['user_shop_count_10_bf']=user_shop_time_10_bf data['user_shop_count_10_af']=user_shop_time_10_af data['user_item_count_10_bf']=user_item_time_10_bf data['user_item_count_10_af']=user_item_time_10_af drops = ['context_timestamp_str', 'user_time_join', 'user_shop_time_join', 'user_item_time_join', 'index_'] data = data.drop(drops, axis=1) return data def doSize(data): add = pd.DataFrame(data.groupby(["shop_id", "day"]).item_id.nunique()).reset_index() add.columns = ["shop_id", "day", "shop_item_unique_day"] data = data.merge(add, on=["shop_id", "day"], how="left") user_query_day = data.groupby(['user_id', 'day']).size().reset_index().rename(columns={0: 'user_id_query_day'}) data = pd.merge(data, user_query_day, how='left', on=['user_id', 'day']) data['min_10'] = data['minute'] // 10 data['min_15'] = data['minute'] // 15 data['min_30'] = data['minute'] // 30 data['min_45'] = data['minute'] // 45 # user 不同时间段点击次数 min10_user_click = data.groupby(['user_id', 'day', 'hour', 'min_10']).size().reset_index().rename(columns={0:'min10_user_click'}) min15_user_click = data.groupby(['user_id', 'day', 'hour', 'min_15']).size().reset_index().rename(columns={0:'min15_user_click'}) min30_user_click = data.groupby(['user_id', 'day', 'hour', 'min_30']).size().reset_index().rename(columns={0:'min30_user_click'}) min45_user_click = data.groupby(['user_id', 'day', 'hour', 'min_45']).size().reset_index().rename(columns={0:'min45_user_click'}) data = pd.merge(data, min10_user_click, 'left', on=['user_id', 'day', 'hour', 'min_10']) data = pd.merge(data, min15_user_click, 'left', on=['user_id', 'day', 'hour', 'min_15']) data = pd.merge(data, min30_user_click, 'left', on=['user_id', 'day', 'hour', 'min_30']) data = pd.merge(data, min45_user_click, 'left', on=['user_id', 'day', 'hour', 'min_45']) del data['min_10'] del data['min_15'] del data['min_30'] del data['min_45'] return data def doElse(data): pass def main(): path = 'F:/18ijcaidata/' train = pd.read_csv(path+'train_day7.csv',encoding='utf-8') test = pd.read_csv(path+'test_day7.csv',encoding='utf-8') data = pd.concat([train, test]) print('初始维度:', data.shape) data, cols = pre_process(data) print('pre_process:', data.shape) ################################## data = dorollWin(data) print('dorollWin:', data.shape) data = doSize(data) print('doSize:', data.shape) ################################## data = data.drop(cols, axis=1) # 得到7号训练集 data = data.loc[data.day == 7] data = data.drop('day', axis=1) print('经过处理后,7号数据集最终维度::',data.shape) print(data.columns.tolist()) data.to_csv(path+'103_statistics_feat.csv', index=False) if __name__ == '__main__': #??????????????运行此行,出现key error:'user_id' main() ``` ```
数据库导入sql报错1215
/* Navicat MySQL Data Transfer Source Server : localhost_3306 Source Server Version : 50521 Source Host : localhost:3306 Source Database : mybatis Target Server Type : MYSQL Target Server Version : 50521 File Encoding : 65001 Date: 2015-04-09 16:03:53 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `orders` -- ---------------------------- DROP TABLE IF EXISTS `orders`; CREATE TABLE `orders` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL COMMENT '下单用户id', `number` varchar(32) NOT NULL COMMENT '订单号', `createtime` datetime NOT NULL COMMENT '创建订单时间', `note` varchar(100) DEFAULT NULL COMMENT '备注', PRIMARY KEY (`id`), KEY `FK_orders_1` (`user_id`), CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of orders -- ---------------------------- INSERT INTO `orders` VALUES ('3', '1', '1000010', '2015-02-04 13:22:35', null); INSERT INTO `orders` VALUES ('4', '1', '1000011', '2015-02-03 13:22:41', null); INSERT INTO `orders` VALUES ('5', '10', '1000012', '2015-02-12 16:13:23', null); -- ---------------------------- -- Table structure for `user` -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(32) NOT NULL COMMENT '用户名称', `birthday` date DEFAULT NULL COMMENT '生日', `sex` char(1) DEFAULT NULL COMMENT '性别', `address` varchar(256) DEFAULT NULL COMMENT '地址', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', '王五', null, '2', null); INSERT INTO `user` VALUES ('10', '张三', '2014-07-10', '1', '北京市'); INSERT INTO `user` VALUES ('16', '张小明', null, '1', '河南郑州'); INSERT INTO `user` VALUES ('22', '陈小明', null, '1', '河南郑州'); INSERT INTO `user` VALUES ('24', '张三丰', null, '1', '河南郑州'); INSERT INTO `user` VALUES ('25', '陈小明', null, '1', '河南郑州'); INSERT INTO `user` VALUES ('26', '王五', null, null, null);
有全部源码,我调用openssl库的RSA和AES算法进行加密。加密字符串太长就会报错,具体如下。
报错信息是这样的: Error encrypting message: error:0406D06E:rsa routines:RSA_padding_add_PKCS1_type_2:data too large for key size Error decrypting message: error:0407106B:rsa routines:RSA_padding_check_PKCS1_type_2:block type is not 02 我用的Linux环境进行开发的,不过也应该没有太大关系啦! 另外代码上有什么问题也可以指出来,万分感谢!!! 具体代码 如下: ``` #include <openssl/rsa.h> #include <openssl/sha.h> #include <openssl/ssl.h> #include <openssl/aes.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/err.h> #include <assert.h> #include <iostream> #include <string.h> #include <stdio.h> #include <string> #include <stdlib.h> #define RSA_KEYLEN 2048 #define AES_KEYLEN 128 #define AES_ROUNDS 6 #define KEY_SERVER_PRI 0 #define KEY_SERVER_PUB 1 #define KEY_CLIENT_PUB 2 #define KEY_AES 3 #define KEY_AES_IV 4 #define KEY_LENGTH 2048 #define PUB_EXP 3 //用AES进行加密 int EncodeAES(unsigned char* password,unsigned int pass_len, unsigned char* data,unsigned int data_len,unsigned char** out_data,unsigned int *out_len) { AES_KEY aes_key; if(AES_set_encrypt_key((const unsigned char*)password, 192, &aes_key) < 0) { assert(false); return -1; } std::string strRet; std::string data_bak((const char*)data); unsigned int data_length = data_len; int padding = 0; if (data_len % AES_BLOCK_SIZE > 0) { padding = AES_BLOCK_SIZE - data_len % AES_BLOCK_SIZE; } data_length += padding; while (padding > 0) { data_bak += '\0'; padding--; } for(unsigned int i = 0; i < data_length/AES_BLOCK_SIZE; i++) { std::string str16 = data_bak.substr(i*AES_BLOCK_SIZE, AES_BLOCK_SIZE); unsigned char out[AES_BLOCK_SIZE]; ::memset(out, 0, AES_BLOCK_SIZE); AES_encrypt((const unsigned char*)str16.c_str(), out, &aes_key); strRet += std::string((const char*)out, AES_BLOCK_SIZE); } *out_len=strRet.length(); *out_data=(unsigned char*)malloc(*out_len); *out_data=(unsigned char*)strRet.c_str(); return 0; } //用aes进行解密 int DecodeAES(unsigned char *password,unsigned int pass_len, unsigned char* data,unsigned int data_len,unsigned char** out_data,unsigned int *out_len ) { AES_KEY aes_key; if(AES_set_decrypt_key((const unsigned char*)password, 192, &aes_key) < 0) { assert(false); return -1; } std::string strRet; std::string strData((const char*)data); try { for(unsigned int i = 0; i < data_len/AES_BLOCK_SIZE; i++) { std::string str16 = strData.substr(i*AES_BLOCK_SIZE, AES_BLOCK_SIZE); unsigned char out[AES_BLOCK_SIZE]; ::memset(out, 0, AES_BLOCK_SIZE); AES_decrypt((const unsigned char*)str16.c_str(), out, &aes_key); strRet += std::string((const char*)out, AES_BLOCK_SIZE); } } catch (std::exception const &exc) { std::cerr << "Exception caught " << exc.what() << "\n"; } catch (...) { std::cerr << "Unknown exception caught\n"; } *out_len=strRet.length(); *out_data=(unsigned char*)malloc(*out_len); *out_data=(unsigned char*)strRet.c_str(); return 0; } //生成RSA需要的公钥和私钥 int generateRSAKeys(char ** pri_key, char ** pub_key) { RSA *keypair = RSA_generate_key(KEY_LENGTH, PUB_EXP, NULL, NULL); // To get the C-string PEM form: BIO *pri = BIO_new(BIO_s_mem()); BIO *pub = BIO_new(BIO_s_mem()); PEM_write_bio_RSAPrivateKey(pri, keypair, NULL, NULL, 0, NULL, NULL); PEM_write_bio_RSAPublicKey(pub, keypair); size_t pri_len = BIO_pending(pri); size_t pub_len = BIO_pending(pub); char* prikey = (char*)malloc(pri_len + 1); char* pubkey = (char*)malloc(pub_len + 1); if (prikey == NULL&&pubkey == NULL) { return -1; } BIO_read(pri, prikey, pri_len); BIO_read(pub, pubkey, pub_len); *pri_key = prikey; *pub_key = pubkey; RSA_free(keypair); BIO_free_all(pri); BIO_free_all(pub); return 0; } //用RSA公钥进行加密 int encryptWithPub(char *pub_key,char* msg, char **encrypt, int* encrypt_len ) { RSA *rsa = NULL; BIO* keybio = BIO_new_mem_buf((void *)pub_key, -1); char *err = (char*)malloc(130); if (keybio == NULL) { printf("failed to create key BIO\n"); return -1; } #ifdef RSAPUBKEY if ((rsa = PEM_read_bio_RSA_PUBKEY(keybio, NULL, NULL, NULL)) == NULL) #else if ((rsa = PEM_read_bio_RSAPublicKey(keybio, NULL, NULL, NULL)) == NULL) #endif if (!rsa){ printf(" rsa is null %s\n", ERR_error_string(ERR_get_error(), NULL)); return -1; } *encrypt_len = RSA_size(rsa); *encrypt = (char *)malloc(1024); if ((RSA_public_encrypt(strlen(msg) + 1, (unsigned char*)msg, (unsigned char*)*encrypt,rsa, RSA_PKCS1_PADDING)) == -1) { ERR_load_crypto_strings(); ERR_error_string(ERR_get_error(), err); fprintf(stderr, "Error encrypting message: %s\n", err); return -1; } RSA_free(rsa); free(err); BIO_free_all(keybio); // *encrypt_len=enstr.length(); return 0; } //用RSA私钥进行解密 int decryptWtihPri(char *pri_key,char* msg,char **decrypt, int encrypt_len){ RSA *rsa = NULL; BIO* keybio = BIO_new_mem_buf(pri_key, -1); if (keybio == NULL) { printf("failed to create key BIO\n"); return -1; } #ifdef RSAPRIVATE if ((rsa = PEM_read_bio_RSA_PRIVATE(keybio, NULL, NULL, NULL)) == NULL) #else if ((rsa = PEM_read_bio_RSAPrivateKey(keybio, NULL, NULL, NULL)) == NULL) #endif if (!rsa){ printf(" rsa null %s\n", ERR_error_string(ERR_get_error(), NULL)); return -1; } char *err = (char*)malloc(130); *decrypt = (char*)malloc(encrypt_len); if (RSA_private_decrypt(encrypt_len, (unsigned char*)msg, (unsigned char*)*decrypt, rsa, RSA_PKCS1_PADDING) == -1) { ERR_load_crypto_strings(); ERR_error_string(ERR_get_error(), err); fprintf(stderr, "Error decrypting message: %s\n", err); return -1; } RSA_free(rsa); free(err); BIO_free_all(keybio); return 0; } /** *测试函数部分 */ int test_aes(); int test_rsa(); int main() { test_rsa(); test_aes(); return 0; } int test_rsa() { printf("\n----------THE RSA TESTING -------- \n"); char * pri_key; char * pub_key; generateRSAKeys(&pri_key, &pub_key); //printf("\n%s\n%s\n", pri_key, pub_key); char *encrypt; char *decrypt; int encrypt_length; encryptWithPub(pub_key,(char *)"i havei have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a key a key",&encrypt, &encrypt_length); decryptWtihPri( pri_key,encrypt, &decrypt,encrypt_length); printf("decrypted message: %s\n", decrypt); return 0; } int test_aes() { printf("\n----------THE AES TESTING --------\n"); char* pass=(char*)"key"; int ret; char* data=(char*)"infocoei have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a key ei have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a key re big tree "; char *output=NULL; unsigned int out_len; char *newoutput=NULL; unsigned int new_len; std::cout<<"the length of key:"<<strlen(pass)<<std::endl; std::cout<<"before encryption:"<<data<<std::endl; ret=EncodeAES((unsigned char*)pass, strlen(pass),(unsigned char *)data,strlen(data),(unsigned char **)&output, &out_len); //std::cout<<"the en len:"<<out_len<<std::endl; ret=DecodeAES((unsigned char*)pass, strlen(pass),(unsigned char *)output,out_len,(unsigned char **)&newoutput, &new_len); //std::cout<<"the deenc len:"<<new_len<<std::endl; std::cout<<"after decryption:"<<newoutput<<std::endl; } ``` 代码的运行结果如下: ``` ----------THE RSA TESTING -------- Error encrypting message: error:0406D06E:rsa routines:RSA_padding_add_PKCS1_type_2:data too large for key size Error decrypting message: error:0407106B:rsa routines:RSA_padding_check_PKCS1_type_2:block type is not 02 decrypted message: 惙l= ----------THE AES TESTING -------- the length of key:3 before encryption:infocoei have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a key ei have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a keyi have a key re big tree Exception caught basic_string::substr after decryption:Ϝż§§<¾yK*. [root@localhost boost_encryption]# ``` 我的邮箱是fubohuauser@163.com 有啥问题也可以一起联系交流。谢谢
data,label=read_img(path)报错
def read_img(path): cate=[path+'/'+x for x in os.listdir(path) if os.path.isdir(path+'/'+x)] imgs=[] labels=[] for idx,folder in enumerate(cate): for im in glob.glob(folder+'/*.png'): print('reading the images:%s'%(im)) img=io.imread(im) img=transform.resize(img,(w,h,c)) imgs.append(img) labels.append(idx) return np.asarray(imgs,np.float32),np.asarray(labels,np.int32) data,label=read_img(path) Traceback (most recent call last): File "D:\anaconda3\anaconda file\CnnFaces\train.py", line 64, in <module> data,label=read_img(path) File "D:\anaconda3\anaconda file\CnnFaces\train.py", line 60, in read_img return np.asarray(imgs,np.float32),np.asarray(labels,np.int32) 有两行报错,为什么
新手请教下简单的mybatis问题
出现了异常是 Exception in thread "main" java.lang.NullPointerException at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:84) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:64) at ch05.Test.test(Test.java:22) at ch05.Test1.main(Test1.java:10) 我是根据mybatis官方中文文档输入的 ,可是报了这个异常错问是什么问题 谢谢。 这是我的全局配置 ``` <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/data"/> <property name="username" value="root"/> <property name="password" value="123456"/> <mappers> <mapper resource="Mapping.xml"/> </mappers> ``` <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/data"/> <property name="username" value="root"/> <property name="password" value="123456"/> <mappers> <mapper resource="Mapping.xml"/> </mappers> 这是我的映射文件 <mapper namespace="Mapping"> <insert id="insertUser" parameterType="com.test.bean.User"> insert into user values(null,#{username},#{password}) </insert> </mapper> 这是我的test测试类 public static int test() throws IOException { String resource = "ch05/src/sqlMapConfig.xml";//配置路径 InputStream inputStream = Resources.class.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); User u=new User(); u.setUsername("cwjj"); u.setPassword("12456"); int insert = sqlSession.insert("Mapping.insertUser",u); return insert;
knn猫狗识别算法中样本为0报错
错误如下: ValueError: With n_samples=0, test_size=0.25 and train_size=None, the resulting train set will be empty. Adjust any of the aforementioned parameters. 代码如下: # import the necessary packages from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from pyimagesearch.preprocessing import SimplePreprocessor from pyimagesearch.datasets import SimpleDatasetLoader from imutils import paths import argparse # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-d", "--datasets", type=str, default="‪H:\\111\\try1\\pyimagesearch\\datasets\\animals\\", help="path to input dataset") ap.add_argument("-k", "--neighbors", type=int, default=1, help="# of nearest neighbors for classification") ap.add_argument("-j", "--jobs", type=int, default=-1, help="# of jobs for k-NN distance (-1 uses all available cores)") args = vars(ap.parse_args()) # grab the list of images that we’ll be describing print("[INFO] loading images...") imagePaths = list(paths.list_images(args["datasets"])) # initialize the image preprocessor, load the dataset from disk, # and reshape the data matrix sp = SimplePreprocessor.SimplePreprocessor(32, 32) sdl = SimpleDatasetLoader.SimpleDatasetLoader(preprocessors=[sp]) (data, labels) = sdl.load(imagePaths, verbose=500) data = data.reshape((data.shape[0], 3072)) # show some information on memory consumption of the images print("[INFO] features matrix: {:.1f}MB".format( data.nbytes / (1024 * 1000.0))) # encode the labels as integers le = LabelEncoder() labels = le.fit_transform(labels) # partition the data into training and testing splits using 75% of # the data for training and the remaining 25% for testing (trainX, testX, trainY, testY) = train_test_split(data, labels, test_size=0.25, random_state=42) # train and evaluate a k-NN classifier on the raw pixel intensities print("[INFO] evaluating k-NN classifier...") model = KNeighborsClassifier(n_neighbors=args["neighbors"], n_jobs=args["jobs"]) model.fit(trainX, trainY) print(classification_report(testY, model.predict(testX), target_names=le.classes_)) ``` ```
java 数组定义,报错:unexpected token: [ 如何解决?
RT,代码如下: class Data { String name; int size; int level; int father; int x = 0; int y = 0; int w = 0; int h = 0; Data(String tname, int tsize, int tlevel, int tfather) { name = tname; size = tsize; level = tlever; father = tfather; } }; Data[] data = new Data[100]; data[0] = new Data("year", 365, 0,-1); data[1] = new Data("s1", 91, 1, 0); 就显示这个报错了,不知道是为何,其中Data是我自己定义的一个类,谷歌之,在data[0]和data[1]之前加了var,无效,请赐教,赶脚作业要写不完了的样子T T。
这是一个关于C++的简单代码问题
``` #include<iostream> using namespace std; struct typedef LNode { int data; LNode *Next; }*List; int main() { return 0; } ``` 这是我写的代码,我就是想写个链表结点结构体 报错如下: --------------------Configuration: 123 - Win32 Debug-------------------- Compiling... 123.cpp F:\C语言程序\123.cpp(4) : error C2239: unexpected token '{' following declaration of 'LNode' F:\C语言程序\123.cpp(8) : error C2501: 'List' : missing storage-class or type specifiers Error executing cl.exe. 123.exe - 2 error(s), 0 warning(s) 求解
数据库存储过程错误 求大佬来帮帮忙看看错误在哪里
这个存储过程的目的是把一张大表根据某一字段拆分成若干小表,比如student表中有stu_no 字段,现在根据学号的不同把每个学号单独放入一张表中 这是我写的存储过程: ``` CREATE PROCEDURE pro_transfer_method_data BEGIN declare v_stu_no INT; declare flag int default 0; declare cur1 cursor for select DISTINCT stu_no from student; declare continue handler for sqlstate '02000' set flag = 1; open cur1; fetch cur1 into v_stu_no; WHILE(flag!= 1) DO call create_table_if_not_exist(CONCAT(v_stu_no, '_mc')); call insert_data_to_table(CONCAT(v_stu_no, '_mc'), v_stu_no); fetch curl into v_stu_no; end WHILE; close curl; END; ``` 报错如下: [Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'BEGIN declare v_stu_no INT; declare flag int default 0; declare cur1 curso' at line 2
请求大佬支援!!!单链表报错
![图片说明](https://img-ask.csdn.net/upload/201912/10/1575965411_534750.jpg) ``` package exercise.LinearTable.impl; import exercise.LinearTable.LinearList; public class SingleList{ Node head = null;//表头 public boolean isEmpty() { int length = size(); if(length==0) { return true; } return false; } public int size() { int length = 0; Node temp = head; while(temp.next!=null) { length++; temp = temp.next; } return length; } public Object get(int index) { Node temp = head; int i = 1; if(index == 0) { return head; } while(temp.next!=null) { if(index==i) { return temp; } temp = temp.next; i++; } return temp; } public int add(Object element) { int i=0; if(head.next==null) { head.next = (Node) element; return i; } //新建一个节点 Node newnode = new Node(element); Node temp = head; //一个移动的指针(把头结点看做一个指向结点的指针) while(temp.next != null){ //遍历单链表,直到遍历到最后一个则跳出循环。 temp = temp.next; //往后移一个结点,指向下一个结点。 } temp.next = (Node) element; //temp为最后一个结点或者是头结点,将其next指向新结点 i++; //链表为空 return i; } public void insert(int index, Node element) { //首先需要判断指定位置是否合法, if(index<1||index>size()){ System.out.println("插入位置不合法。"); return; } Node temp = (Node) get(index); element.next = temp.next; temp.next = element; } @Override public Object remove(int index) { //判断index是否合理 if(index<1 || index>size()){ System.out.println("给定的位置不合理"); return null; } Node temp = (Node) get(index-1); temp = temp.next.next; return temp; } public void tostring() { Node temp = head; while(temp.next!=null) { System.out.print(" "+temp.data); temp = temp.next; } } public static void main(String[] args) { SingleList s = new SingleList(); s.add("1"); s.add("1"); s.add("1"); s.add("1"); s.tostring(); } } class Node{ Node next = null; Object data; public Node(Object data) { this.data = data; } } ```
WPF中Graphics g = this.CreateGraphics();报错
``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Timers; using System.Windows.Threading; using System.Drawing; using System.Drawing.Imaging; namespace _2_3 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { private DispatcherTimer dispatcherTimer = null; int hh, mm, ss; public MainWindow() { InitializeComponent(); dispatcherTimer = new System.Windows.Threading.DispatcherTimer(); dispatcherTimer.Tick += new EventHandler(OnTimedEvent); dispatcherTimer.Interval = new TimeSpan(0, 0, 1); dispatcherTimer.Start(); } private void OnTimedEvent(object sender, EventArgs e) { timelabel.Content = DateTime.Now.ToLongTimeString(); hh = DateTime.Now.Hour; mm = DateTime.Now.Minute; ss = DateTime.Now.Second; MyDrawClock(hh, mm, ss); } private void MyDrawClock(int h, int m, int s) { Graphics g = this.CreateGraphics(); g.Clear(System.Drawing.Color.White); Font font = new Font("黑体", 20, System.Drawing.FontStyle.Bold); System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.Black,1); SolidBrush Brush = new SolidBrush(System.Drawing.Color.Black); g.DrawString("12", font, Brush, 40, 60); g.DrawString("9", font, Brush, 20, 45); g.DrawString("3", font, Brush, 60, 45); g.DrawString("6", font, Brush, 40, 30); System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Black,1); System.Drawing.Point centerPoint = new System.Drawing.Point();//表的中心点 //计算出秒针,时针,分针的另外一个点 System.Drawing.Point secPoint = new System.Drawing.Point((int)(centerPoint.X + (Math.Sin(s * Math.PI / 30) * 140)), (int)(centerPoint.Y - (Math.Cos(s * Math.PI / 30) * 140))); System.Drawing.Point minPoint = new System.Drawing.Point((int)(centerPoint.X + (Math.Sin(m * Math.PI / 30) * 130)), (int)(centerPoint.Y - (Math.Cos(m * Math.PI / 30) * 130))); System.Drawing.Point hourPoint = new System.Drawing.Point((int)(centerPoint.X + (Math.Sin(h * Math.PI / 6) * 120) - m * Math.PI / 360), (int)(centerPoint.Y - (Math.Cos(h * Math.PI / 6) * 120) - m * Math.PI / 360)); //以不同颜色和宽度绘制表针 myPen = new System.Drawing.Pen(System.Drawing.Color.Red,1); g.DrawLine(myPen, centerPoint, secPoint); myPen = new System.Drawing.Pen(System.Drawing.Color.Green,2); g.DrawLine(myPen, centerPoint, minPoint); myPen = new System.Drawing.Pen(System.Drawing.Color.Orange, 1); g.DrawLine(myPen, centerPoint, hourPoint); } } } ``` 报错信息:错误 1 “_2_3.MainWindow”不包含“CreateGraphics”的定义,并且找不到可接受类型为“_2_3.MainWindow”的第一个参数的扩展方法“CreateGraphics”(是否缺少 using 指令或程序集引用 折腾了半天也没搞好,要崩溃了
C# socket客户端接收的数据int.Parse报错
我在做一个黑白棋游戏,想通过服务器转发指令实现客户端落子。在客户端接收数据然后转成int去判断落子的坐标然后报错了,然后服务器收到一堆空格。private void receiveData(object socket) { Socket ortherSocket = (Socket)clientSocket; while (true) { try { String data = Receive(ortherSocket); // 接收客户端发送的信息 if (!data.Equals("")) { s = data; s1 = int.Parse(data); if (s != "") { Sc(s1); } } } catch (Exception ex) { //ortherSocket.Shutdown(SocketShutdown.Both); ortherSocket.Close(); break; } } } ``` ``` ![图片说明](https://img-ask.csdn.net/upload/201903/29/1553788985_905167.png)
帮帮忙吧,急哭了:python实现拉格朗日插值进行缺失值插补时报错,出现Keyerror:0问题?
![图片说明](https://img-ask.csdn.net/upload/201911/13/1573618586_795847.png) 数据截图 ``` import pandas as pd from scipy.interpolate import lagrange inputfile = './test1.xlsx' outputfile = './test1_1.xlsx' def ployinterp_column(s,n,k=6): y = s[list(range(n-k,n)) + list(range(n+1,n+1-k))] y = y[y.notnull()] return lagrange(y.index,list(y))(n) for i in data.columns: for j in range(len(data)): if (data[i].isnull())[j]: data[i][j] = ployinterp_column(data[i],j) ``` 报错 ``` KeyError Traceback (most recent call last) <ipython-input-28-02cf873cddff> in <module>() 1 for i in data.columns: 2 for j in range(len(data)): ----> 3 if (data[i].isnull())[j]: 4 if (data[i].isnull())[j] in data: 5 data[i][j] = ployinterp_column(data[i],j) C:\Anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key) 765 key = com._apply_if_callable(key, self) 766 try: --> 767 result = self.index.get_value(self, key) 768 769 if not is_scalar(result): C:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key) 3116 try: 3117 return self._engine.get_value(s, k, -> 3118 tz=getattr(series.dtype, 'tz', None)) 3119 except KeyError as e1: 3120 if len(self) > 0 and self.inferred_type in ['integer', 'boolean']: pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value() pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value() pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() KeyError: 0 ```
130 个相见恨晚的超实用网站,一次性分享出来
相见恨晚的超实用网站 持续更新中。。。
我花了一夜用数据结构给女朋友写个H5走迷宫游戏
起因 又到深夜了,我按照以往在csdn和公众号写着数据结构!这占用了我大量的时间!我的超越妹妹严重缺乏陪伴而 怨气满满! 而女朋友时常埋怨,认为数据结构这么抽象难懂的东西没啥作用,常会问道:天天写这玩意,有啥作用。而我答道:能干事情多了,比如写个迷宫小游戏啥的! 当我码完字准备睡觉时:写不好别睡觉! 分析 如果用数据结构与算法造出东西来呢? ...
对计算机专业来说学历真的重要吗?
我本科学校是渣渣二本,研究生学校是985,现在毕业五年,校招笔试、面试,社招面试参加了两年了,就我个人的经历来说下这个问题。 这篇文章很长,但绝对是精华,相信我,读完以后,你会知道学历不好的解决方案,记得帮我点赞哦。 先说结论,无论赞不赞同,它本质就是这样:对于技术类工作而言,学历五年以内非常重要,但有办法弥补。五年以后,不重要。 目录: 张雪峰讲述的事实 我看到的事实 为什么会这样 ...
字节跳动视频编解码面经
三四月份投了字节跳动的实习(图形图像岗位),然后hr打电话过来问了一下会不会opengl,c++,shador,当时只会一点c++,其他两个都不会,也就直接被拒了。 七月初内推了字节跳动的提前批,因为内推没有具体的岗位,hr又打电话问要不要考虑一下图形图像岗,我说实习投过这个岗位不合适,不会opengl和shador,然后hr就说秋招更看重基础。我当时想着能进去就不错了,管他哪个岗呢,就同意了面试...
win10系统安装教程(U盘PE+UEFI安装)
一、准备工作 u盘,电脑一台,win10原版镜像(msdn官网) 二、下载wepe工具箱 极力推荐微pe(微pe官方下载) 下载64位的win10 pe,使用工具箱制作启动U盘打开软件, 选择安装到U盘(按照操作无需更改) 三、重启进入pe系统 1、关机后,将U盘插入电脑 2、按下电源后,按住F12进入启动项选择(技嘉主板是F12) 选择需要启...
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
Python——画一棵漂亮的樱花树(不同种樱花+玫瑰+圣诞树喔)
最近翻到一篇知乎,上面有不少用Python(大多是turtle库)绘制的树图,感觉很漂亮,我整理了一下,挑了一些我觉得不错的代码分享给大家(这些我都测试过,确实可以生成) one 樱花树 动态生成樱花 效果图(这个是动态的): 实现代码 import turtle as T import random import time # 画樱花的躯干(60,t) def Tree(branch, ...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小人工智障。 思路可以运用在不同地方,主要介绍的是思路。
致 Python 初学者
欢迎来到“Python进阶”专栏!来到这里的每一位同学,应该大致上学习了很多 Python 的基础知识,正在努力成长的过程中。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 python 这门编程语言,从2009年开始单一使用 python 应对所有的开发工作,直至今天。回顾自己的学习过程,也曾经遇到过无数的困难,也曾经迷茫过、困惑过。开办这个专栏,正是为了帮助像我当年一样困惑的 Python 初学者走出困境、快速成长。希望我的经验能真正帮到你
Ol4网格生成以及优化
概述 先描述一下大致场景:以0.05为单元格大小生成网格,并在地图上绘制,绘制的时候需要区分海陆。本文以此需求为契机,简单描述一下该需求的实现以及如何来优化。 效果 实现 优化前 var source = new ol.source.Vector({ features: [] }); var vector = new ol.layer.Vector({ source...
11月19日科技资讯|华为明日发布鸿蒙整体战略;京东宣告全面向技术转型;Kotlin 1.3.60 发布
「极客头条」—— 技术人员的新闻圈! CSDN 的读者朋友们早上好哇,「极客头条」来啦,快来看今天都有哪些值得我们技术人关注的重要新闻吧。扫描上方二维码进入 CSDN App 可以收听御姐萌妹 Style 的人工版音频哟。 一分钟速览新闻点! 6G 专家组成员:速率是 5G 的 10 至 100 倍,预计 2030 年商用 雷军:很多人多次劝我放弃WPS,能坚持下来并不是纯粹的商业决定 ...
C语言魔塔游戏
很早就很想写这个,今天终于写完了。 游戏截图: 编译环境: VS2017 游戏需要一些图片,如果有想要的或者对游戏有什么看法的可以加我的QQ 2985486630 讨论,如果暂时没有回应,可以在博客下方留言,到时候我会看到。 下面我来介绍一下游戏的主要功能和实现方式 首先是玩家的定义,使用结构体,这个名字是可以自己改变的 struct gamerole { char n...
iOS Bug 太多,苹果终于坐不住了!
开源的 Android 和闭源的 iOS,作为用户的你,更偏向哪一个呢? 整理 | 屠敏 出品 | CSDN(ID:CSDNnews) 毋庸置疑,当前移动设备操作系统市场中,Android 和 iOS 作为两大阵营,在相互竞争的同时不断演进。不过一直以来,开源的 Android 吸引了无数的手机厂商涌入其中,为其生态带来了百花齐放的盛景,但和神秘且闭源的 iOS 系统相比,不少网友...
Python语言高频重点汇总
Python语言高频重点汇总 GitHub面试宝典仓库 回到首页 目录: Python语言高频重点汇总 目录: 1. 函数-传参 2. 元类 3. @staticmethod和@classmethod两个装饰器 4. 类属性和实例属性 5. Python的自省 6. 列表、集合、字典推导式 7. Python中单下划线和双下划线 8. 格式化字符串中的%和format 9. 迭代器和生成器 10...
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观...
Python爬虫爬取淘宝,京东商品信息
小编是一个理科生,不善长说一些废话。简单介绍下原理然后直接上代码。 使用的工具(Python+pycharm2019.3+selenium+xpath+chromedriver)其中要使用pycharm也可以私聊我selenium是一个框架可以通过pip下载 pip installselenium -ihttps://pypi.tuna.tsinghua.edu.cn/simple/ ...
程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
Java工作4年来应聘要16K最后没要,细节如下。。。
前奏: 今天2B哥和大家分享一位前几天面试的一位应聘者,工作4年26岁,统招本科。 以下就是他的简历和面试情况。 基本情况: 专业技能: 1、&nbsp;熟悉Sping了解SpringMVC、SpringBoot、Mybatis等框架、了解SpringCloud微服务 2、&nbsp;熟悉常用项目管理工具:SVN、GIT、MAVEN、Jenkins 3、&nbsp;熟悉Nginx、tomca...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
程序员该看的几部电影
1、骇客帝国(1999) 概念:在线/离线,递归,循环,矩阵等 剧情简介: 不久的将来,网络黑客尼奥对这个看似正常的现实世界产生了怀疑。 他结识了黑客崔妮蒂,并见到了黑客组织的首领墨菲斯。 墨菲斯告诉他,现实世界其实是由一个名叫“母体”的计算机人工智能系统控制,人们就像他们饲养的动物,没有自由和思想,而尼奥就是能够拯救人类的救世主。 可是,救赎之路从来都不会一帆风顺,到底哪里才是真实的世界?如何...
蓝桥杯知识点汇总:基础知识和常用算法
文章目录基础语法部分:算法竞赛常用API:算法部分数据结构部分 此系列包含蓝桥杯绝大部分所考察的知识点,以及真题题解~ 基础语法部分: 备战蓝桥杯java(一):一般输入输出 和 快速输入输(BufferedReader&amp;BufferedWrite) 备战蓝桥杯java(二):java编程规范和常用数据类型 备战蓝桥杯java(三):常用功能符以及循环结构和分支结构 备战蓝桥杯java(四...
作为一个程序员,CPU的这些硬核知识你必须会!
CPU对每个程序员来说,是个既熟悉又陌生的东西? 如果你只知道CPU是中央处理器的话,那可能对你并没有什么用,那么作为程序员的我们,必须要搞懂的就是CPU这家伙是如何运行的,尤其要搞懂它里面的寄存器是怎么一回事,因为这将让你从底层明白程序的运行机制。 随我一起,来好好认识下CPU这货吧 把CPU掰开来看 对于CPU来说,我们首先就要搞明白它是怎么回事,也就是它的内部构造,当然,CPU那么牛的一个东...
@程序员,如何花式构建线程?
作者 |曾建责编 | 郭芮出品 | CSDN(ID:CSDNnews)在项目和业务的开发中,我们难免要经常使用线程来进行业务处理,使用线程可以保证我们的业务在相互处理之间可以保证原子性...
破14亿,Python分析我国存在哪些人口危机!
一、背景 二、爬取数据 三、数据分析 1、总人口 2、男女人口比例 3、人口城镇化 4、人口增长率 5、人口老化(抚养比) 6、各省人口 7、世界人口 四、遇到的问题 遇到的问题 1、数据分页,需要获取从1949-2018年数据,观察到有近20年参数:LAST20,由此推测获取近70年的参数可设置为:LAST70 2、2019年数据没有放上去,可以手动添加上去 3、将数据进行 行列转换 4、列名...
实现简单的轮播图(单张图片、多张图片)
前言 刚学js没多久,这篇博客就当做记录了,以后还会完善的,希望大佬们多多指点。ps:下面出现的都是直接闪动,没有滑动效果的轮播图。 单张图片的替换 · ...
强烈推荐10本程序员在家读的书
很遗憾,这个春节注定是刻骨铭心的,新型冠状病毒让每个人的神经都是紧绷的。那些处在武汉的白衣天使们,尤其值得我们的尊敬。而我们这些窝在家里的程序员,能不外出就不外出,就是对社会做出的最大的贡献。 有些读者私下问我,窝了几天,有点颓丧,能否推荐几本书在家里看看。我花了一天的时间,挑选了 10 本我最喜欢的书,你可以挑选感兴趣的来读一读。读书不仅可以平复恐惧的压力,还可以对未来充满希望,毕竟苦难终将会...
Linux自学篇——linux命令英文全称及解释
man: Manual 意思是手册,可以用这个命令查询其他命令的用法。 pwd:Print working directory 意思是密码。 su:Swith user 切换用户,切换到root用户 cd:Change directory 切换目录 ls:List files 列出目录下的文件 ps:Process Status 进程状态 mkdir:Make directory ...
Python实战:抓肺炎疫情实时数据,画2019-nCoV疫情地图
今天,群里白垩老师问如何用python画武汉肺炎疫情地图。白垩老师是研究海洋生态与地球生物的学者,国家重点实验室成员,于不惑之年学习python,实为我等学习楷模。先前我并没有关注武汉肺炎的具体数据,也没有画过类似的数据分布图。于是就拿了两个小时,专门研究了一下,遂成此文。
疫情数据接口api
返回json示例 { "errcode":0,//0标识接口正常 "data":{ "date":"2020-01-30 07:47:23",//实时更新时间 "diagnosed":7736,//确诊人数 "suspect":12167,//疑是病例人数 "death":170,//死亡人数 "cur...
相关热词 c# 识别回车 c#生成条形码ean13 c#子控制器调用父控制器 c# 写大文件 c# 浏览pdf c#获取桌面图标的句柄 c# list反射 c# 句柄 进程 c# 倒计时 线程 c# 窗体背景色
立即提问