python中 if (i+1)/1000 == 0:是什么意思

从别的代码看到的,没有理解
/代表浮点运算除法,
上面i可以是哪些值?

2个回答

这代码没有什么意义,相当于
i < 999
在python 3.0里,//是整除,/是除法,但是在python 2.0里,/对于整数也是整除。
感觉这代码写错了,很可能作者想要表达 if (i+1)%1000 == 0:
weixin_44831720
weixin_44831720 好的 谢谢 !
7 个月之前 回复

上面的i 只有 i=-1... 判断i=-1 可以直接判断。 和楼上的感觉一样,应该是 (i + 1) % 1000 == 0: 每1000个epoch 输出一次

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
python中 if (i+1)/1000 == 0:是什么意思

从别的代码看到的,没有理解 /代表浮点运算除法, 上面i可以是哪些值?

角度错误:http:// localhost:3000 / login的Http失败响应:404 not found

<div class="post-text" itemprop="text"> <p>I want to get login information that user enters at backend. Here is the backend code :- </p> <pre><code>package main import ( "fmt" "net/http" "github.com/gorilla/mux" "github.com/gorilla/handlers" "encoding/json" "log" ) type LoginDetails struct { Username string `json:"username"` Password string `json:"password"` } func login(w http.ResponseWriter, req *http.Request) { var loginData LoginDetails err := json.NewDecoder(req.Body).Decode(&amp;loginData) if err!=nil{ panic(err) } } func main() { fmt.Println("Starting server at http://localhost:3000...") router := mux.NewRouter() router.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/dist/static"))) router.HandleFunc("/login", login) headersOk := handlers.AllowedHeaders([]string{"Authorization"}) methodsOk := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS"}) log.Fatal(http.ListenAndServe(":3000", handlers.CORS( headersOk, methodsOk)(router))) } </code></pre> <p>Angular code :- </p> <p><strong>login.component.ts</strong> file :- </p> <pre><code>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, FormBuilder } from '@angular/forms'; import { HttpErrorResponse} from '@angular/common/http'; import { LoginService } from './login.service'; import { LoginDetails } from './login'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'], providers : [LoginService, LoginDetails] }) export class LoginComponent implements OnInit { loginForm : FormGroup; constructor(private loginData : LoginDetails, private loginservice: LoginService, private _formBuilder : FormBuilder){} ngOnInit() { this.loginForm = this._formBuilder.group({ username : ['username'], password : ['password'] }) } OnSubmit(){ this.loginData.username = this.loginForm.controls.username.value; this.loginData.password = this.loginForm.controls.password.value; this.loginservice.loginUser(this.loginData).subscribe(response =&gt; { console.log(response) },(err: HttpErrorResponse) =&gt; { console.log(err); }); } } </code></pre> <p><strong>login.service.ts</strong> file :- </p> <pre><code>import { Injectable } from '@angular/core'; import { HttpClient, HttpClientModule, HttpHeaders} from '@angular/common /http'; import { Observable } from 'rxjs'; import { LoginDetails } from './login' @Injectable() export class LoginService{ private _url : string = "http://localhost:3000/login"; constructor( private http : HttpClient){} loginUser(loginData : LoginDetails): Observable &lt;any&gt;{ console.log(loginData) return this.http.post(this._url, loginData, {responseType : 'text'}); } } </code></pre> <p>Error I receive is this :- <code>POST http://localhost:3000/login 404 (Not Found)</code>. </p> </div>

Python中if语句if后面跟函数什么意思?

RT,例如 >>> def fun(): return('ssss') >>> def test(): if fun: return('???') >>> test() '???' >>> if fun: 是什么意思?

获取net / http:TLS握手超时golang

<div class="post-text" itemprop="text"> <p>Need your help with this</p> <pre><code>package main import ( "log" "net/http" ) func main() { client := &amp;http.Client{} _, err := client.Get("https://www.marathonbet.com/en/") if err != nil { log.Fatalf("%s ", err) } } </code></pre> <p>This always return:<code>Get https://www.marathonbet.com/en/: net/http: TLS handshake timeout exit status 1</code> I`m try: <a href="https://stackoverflow.com/a/32524298/5535608">it</a> and use <a href="https://github.com/parnurzeal/gorequest" rel="nofollow noreferrer">this</a> lib and do <a href="https://stackoverflow.com/a/12122718/5535608">it</a> But nothing works for me.. So, please help me.</p> <p>Update: In Python 2.7 with requests this works:</p> <pre><code>s = Session() r = s.get('https://www.marathonbet.com/en/, verify=False) </code></pre> <p>But i need do it with go(</p> <p>UPD: Fixed: Just replase <code>https://www.marathonbet.com/en/</code> to <code>https://87.117.250.213/en/</code> and adding <code>skip verify</code>. thx all for help.</p> </div>

为什么在python使用for循环中在if条件判断,else结果不打印出来?

为什么在python使用for循环中在if条件判断,if条件未达成,else里面没有打印出来! 还有之前问题被删了,不知道为什么,下面2图是什么意思,是执行的流程图吗? **终于知道空格的重要性了** ![图片说明](https://img-ask.csdn.net/upload/201712/21/1513842756_856750.png)![图片说明](https://img-ask.csdn.net/upload/201712/21/1513842870_415060.png)

为什么在使用 Perl 执行 Python 脚本时没有遇到任何语法错误?

<div class="post-text" itemprop="text"> <p>I just wrote some testing python code into <code>test.py</code>, and I'm launching it as follows:</p> <pre><code>perl test.py </code></pre> <p>After a while I realized my mistake. I say "after a while", because the Python code gets actually correctly executed, as if in Python interpreter!</p> <p>Why is my Perl interpreting my Python? <code>test.py</code> looks like this:</p> <pre><code>#!/usr/bin/python ...Python code here... </code></pre> <p>Interestingly, if I do the opposite (i.e. call <code>python something.pl</code>) I get a good deal of syntax errors.</p> </div> <p>转载于:https://stackoverflow.com/questions/29563832/why-dont-i-get-any-syntax-errors-when-i-execute-my-python-script-with-perl</p>

Python怎么改变if里面的值并传递到外面去

![图片说明](https://img-ask.csdn.net/upload/201906/25/1561430592_800873.jpg) for i in range(1,10): a=[1] b=0 if i%3==0: c=a[b]+1 a.append(c) b=b+1 print(a,b,c) 这样子的结果是: [1, 2] 1 2 [1, 2] 1 2 [1, 2] 1 2 我是想当i=3,6,9的时候,a列表每次都加上一个新的元素c,b是a的下标, b也在每次当if成立时候加1,请问要怎么才能让if外面的值随着if里面的 语句执行改变

Python, 请问得出素数2的逻辑是什么?

for n in range(2, 10): for x in range(2, n): if n % x ==0: break else: print(n, '是素数。') 答案是2,3,5,7。其他好理解,请问得出素数2的逻辑是什么? n为2时,for x in range(2,2)没道理啊。

Python if语句不输出

下面是我的代码,主要在于points函数,它不执行if里面的内容,但也没有报错 ``` # -*- coding:utf-8 -*- import random import time import sys playerPoints = 100 playerWon = False playerChoice = None playerGuess = None def easy(): ## 简单难度的踩雷,在 1 ~ 100 之间随机选择雷号 global playerWon rbnList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36, 37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69, 70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100] rbn = random.sample(rbnList,3) if playerGuess == rbn[0] or playerGuess == rbn[1] or playerGuess == rbn[2]: sys.stdout.write("你踩到地雷了!") playerWon = False points() else: sys.stdout.write("你躲开了地雷!") playerWon = True points() def normal(): ## 正常难度的踩雷,在 1 ~ 50 之间随机选择雷号 global playerWon rbnList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36, 37,38,39,40,41,42,43,44,45,46,47,48,49,50] rbn = random.sample(rbnList,3) if playerGuess == rbn[0] or playerGuess == rbn[1] or playerGuess == rbn[2]: sys.stdout.write("你踩到地雷了!") playerWon = False else: sys.stdout.write("你躲开了地雷!") playerWon = True points() def hard(): ## 困难难度的踩雷,在 1 ~ 20 之间随机选择雷号 global playerWon rbnList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] rbn = random.sample(rbnList, 3) if playerGuess == rbn[0] or playerGuess == rbn[1] or playerGuess == rbn[2]: sys.stdout.write("你踩到地雷了!") playerWon = False else: sys.stdout.write("你躲开了地雷!") playerWon = True points() def points(): ## 玩家分数,踩雷游戏分数系统 global playerPoints if playerWon == True: if playerChoice == "简单难度": playerPoints += 5 sys.stdout.write("当前分数加5, 当前分数: %s" % playerPoints) elif playerChoice == "正常难度": playerPoints += 10 sys.stdout.write("当前分数加10, 当前分数: %s" % playerPoints) elif playerChoice == "困难难度": playerPoints += 20 sys.stdout.write("当前分数加20, 当前分数: %s" % playerPoints) elif playerWon == False: if playerChoice == "简单难度": playerPoints -= 5 sys.stdout.write("当前分数减5, 当前分数: %s" % playerPoints) if playerPoints < 0: sys.stdout.write("分数过少,不能进行减分,请等待分数重置") playerPoints = 0 resetPoints() elif playerChoice == "正常难度": playerPoints -= 7 sys.stdout.write("当前分数减7, 当前分数: %s" % playerPoints) if playerPoints < 0: sys.stdout.write("分数过少,不能进行减分,请等待分数重置") playerPoints = 0 resetPoints() elif playerChoice == "困难难度": playerPoints -= 10 sys.stdout.write("当前分数减10, 当前分数: %s" % playerPoints) if playerPoints < 0: sys.stdout.write("分数过少,不能进行减分,请等待分数重置") playerPoints = 0 resetPoints() def resetPoints(): resetPointsTimes = 300 for i in range(resetPointsTimes): sys.stdout.write("分数将在 {} 秒后重置为100".format(resetPointsTimes - i)) sys.stdout.flush() time.sleep(1) sys.stdout.write("分数成功重置为100") GameBody() def rules(): sys.stdout.write("==================== *游戏规则* ====================") sys.stdout.write("本游戏分3个模式:简单模式,正常模式和困难模式") sys.stdout.write("简单模式: 赢了得5分, 输了扣5分") sys.stdout.write("正常模式: 赢了得10分, 输了扣7分") sys.stdout.write("困难模式: 赢了得20分, 输了扣10分") sys.stdout.write("祝您游戏愉快!") def GameBody(): global playerChoice global playerGuess playerChoice = input("简单模式请输入'简单模式',正常模式请输入'正常模式'," + "困难模式请输入'困难模式',查看游戏规则请输入'规则':") if playerChoice == "简单模式": playerGuess = int(input("请输入一个 1 ~ 100 的数字")) easy() elif playerChoice == "正常模式": playerGuess = int(input("请输入一个 1 ~ 50 的数字")) normal() elif playerChoice == "困难模式": playerGuess = int(input("请输入一个 1 ~ 20 的数字")) hard() elif playerChoice == "规则": rules() else: sys.stdout.write("输入错误, 请重新输入") GameBody() GameBody() ```

通过终端和PHP调用python脚本之间的区别? 错误在哪里?

<div class="post-text" itemprop="text"> <p>I have a PHP script, that calls a python script by</p> <pre><code>$call_python = "python ../python/lp_3.py ".$author; $python_output = Null; $mystring = exec($call_python, $output_python); </code></pre> <p>This produces me an error in the log:</p> <pre><code>$ vi logs/error_log shows .... Traceback (most recent call last): File "../python/lp_3.py", line 14, in &lt;module&gt; import MySQLdb ImportError: No module named MySQLdb </code></pre> <p>If I do <code>python python/lp_3.py</code> in the terminal everything is fine. What do I miss?</p> <h2>Edit:</h2> <p>After the suggestion of @S.Lott I had a look at the variables <code>PATH</code> and <code>PYTHONPATH</code> both in the terminal and in PHP.</p> <p>In the terminal:</p> <pre><code>$ echo $PYTHONPATH $ echo $PATH /opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/usr/texbin:/usr/X11/bin </code></pre> <p>As you can see, <code>PYTHONPATH</code> is empty.</p> <p>In PHP:</p> <pre><code>echo getenv("PYTHONPATH"); // NOTHING echo getenv("PATH"); // /usr/bin:/bin:/usr/sbin:/sbin </code></pre> <p>Perhaps I should mention that the first two lines in my python script are</p> <pre><code>#!/usr/bin/env python # encoding: utf-8 </code></pre> <p>I am open for suggestions. =)</p> <h2>Edit2:</h2> <p>I checked every installed python version on my mac. I found out, that python2.7 has no MySQLdb installed. Is there a way to tell PHP <strong>not</strong> to use python2.7 and to use e.g. python2.6 instead? I tryed toying with <code>setenv()</code> in PHP but I couldn't figure out how to use it properly, and I don't even know if this is the right approach.</p> </div>

目前学习python,在if判断这里有点问题,望大佬指点一下

问题: 1.从控制台输入要出的拳--石头(1)/剪刀(2)/布(3) 2.电脑随机出拳--先假定电脑只会出石头、完成整体代码功能 3.比较胜负 比赛规则: 石头胜剪刀 剪刀胜布 布胜石头 ``` player = int(input("从控制台输入要出的拳--石头(1)/剪刀(2)/布(3):")) computer = int(input("从控制台输入要出的拳--石头(1)/剪刀(2)/布(3):")) if ((player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1)): print("玩家赢了") elif player == computer: print("平局") else: print("玩家输了") ``` 这是我写的代码,可以正常运行,但是我现在考虑别的情况: 1.在游戏里过程中玩家如果出的不是1、2、3而电脑是123其中的一个,则判定为玩家不会玩。 2.在游戏里过程中电脑如果出的不是1、2、3而玩家是123其中的一个,则判定为电脑不会玩。 3.在游戏里过程中电脑和玩家出的都不是123,则判定电脑玩家都不会玩。 4.平局的情况,如果电脑玩家出的数字超过了123且是相同的,也判定为电脑玩家不会玩,而不是判定为平局。 以上4条问题,望大佬指定迷津 ---------来自小白的迷茫

python运行有错误:这是对数据进行分析生成可视化界面的程序(我是小白,请说下解决方法)

运行错误: C:\Users\Administrator\PycharmProjects\untitled\venv\Scripts\python.exe C:/Users/Administrator/PycharmProjects/untitled/dianying/src/analysis_data.py 一共有:16590个 Building prefix dict from the default dictionary ... Loading model from cache C:\Users\ADMINI~1\AppData\Local\Temp\jieba.cache Loading model cost 0.808 seconds. Prefix dict has been built succesfully. Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled/dianying/src/analysis_data.py", line 252, in <module> jiebaclearText(content) File "C:/Users/Administrator/PycharmProjects/untitled/dianying/src/analysis_data.py", line 97, in jiebaclearText f_stop_text = f_stop.read() File "D:\python111\lib\codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa1 in position 3: invalid start byte Process finished with exit code 1 代码如下: ''' data : 2019.3.28 goal : 可视化分析获取到的数据 ''' import csv time = [] nickName = [] gender = [] cityName = [] userLevel = [] score = [] content = '' # 读数据 def read_csv(): content = '' # 读取文件内容 with open(r'D:\maoyan.csv', 'r', encoding='utf_8_sig', newline='') as file_test: # 读文件 reader = csv.reader(file_test) i = 0 for row in reader: if i != 0: time.append(row[0]) nickName.append(row[1]) gender.append(row[2]) cityName.append(row[3]) userLevel.append(row[4]) score.append(row[5]) content = content + row[6] # print(row) i = i + 1 print('一共有:' + str(i - 1) + '个') return content import re, jieba # 词云生成工具 from wordcloud import WordCloud, ImageColorGenerator # 需要对中文进行处理 import matplotlib.font_manager as fm from pylab import * mpl.rcParams['font.sans-serif'] = ['SimHei'] from os import path d = path.dirname(__file__) stopwords_path = 'D:\ku\chineseStopWords.txt' # 评论词云分析 def word_cloud(content): import jieba, re, numpy from pyecharts import WordCloud import pandas as pd # 去除所有评论里多余的字符 content = content.replace(" ", ",") content = content.replace(" ", "、") content = re.sub('[,,。. \r\n]', '', content) segment = jieba.lcut(content) words_df = pd.DataFrame({'segment': segment}) # quoting=3 表示stopwords.txt里的内容全部不引用 stopwords = pd.read_csv(stopwords_path, index_col=False, quoting=3, sep="\t", names=['stopword'], encoding='utf-8') words_df = words_df[~words_df.segment.isin(stopwords.stopword)] words_stat = words_df.groupby(by=['segment'])['segment'].agg({"计数": numpy.size}) words_stat = words_stat.reset_index().sort_values(by=["计数"], ascending=False) test = words_stat.head(500).values codes = [test[i][0] for i in range(0, len(test))] counts = [test[i][1] for i in range(0, len(test))] wordcloud = WordCloud(width=1300, height=620) wordcloud.add("影评词云", codes, counts, word_size_range=[20, 100]) wordcloud.render(d + "\picture\c_wordcloud.html") # 定义个函数式用于分词 def jiebaclearText(text): # 定义一个空的列表,将去除的停用词的分词保存 mywordList = [] text = re.sub('[,,。. \r\n]', '', text) # 进行分词 seg_list = jieba.cut(text, cut_all=False) # 将一个generator的内容用/连接 listStr = '/'.join(seg_list) listStr = listStr.replace("class", "") listStr = listStr.replace("span", "") listStr = listStr.replace("悲伤逆流成河", "") # 打开停用词表 f_stop = open(stopwords_path, encoding="utf8") # 读取 try: f_stop_text = f_stop.read() finally: f_stop.close() # 关闭资源 # 将停用词格式化,用\n分开,返回一个列表 f_stop_seg_list = f_stop_text.split("\n") # 对默认模式分词的进行遍历,去除停用词 for myword in listStr.split('/'): # 去除停用词 if not (myword.split()) in f_stop_seg_list and len(myword.strip()) > 1: mywordList.append(myword) return ' '.join(mywordList) # 生成词云图 def make_wordcloud(text1): text1 = text1.replace("悲伤逆流成河", "") bg = plt.imread(d + "/static/znn1.jpg") # 生成 wc = WordCloud( # FFFAE3 background_color="white", # 设置背景为白色,默认为黑色 width=890, # 设置图片的宽度 height=600, # 设置图片的高度 mask=bg, # margin=10, # 设置图片的边缘 max_font_size=150, # 显示的最大的字体大小 random_state=50, # 为每个单词返回一个PIL颜色 font_path=d + '/static/simkai.ttf' # 中文处理,用系统自带的字体 ).generate_from_text(text1) # 为图片设置字体 my_font = fm.FontProperties(fname=d + '/static/simkai.ttf') # 图片背景 bg_color = ImageColorGenerator(bg) # 开始画图 plt.imshow(wc.recolor(color_func=bg_color)) # 为云图去掉坐标轴 plt.axis("off") # 画云图,显示 # 保存云图 wc.to_file(d + r"/picture/word_cloud.png") # 评论者性别分布可视化 def sex_distribution(gender): # print(gender) from pyecharts import Pie list_num = [] list_num.append(gender.count('0')) # 未知 list_num.append(gender.count('1')) # 男 list_num.append(gender.count('2')) # 女 attr = ["其他", "男", "女"] pie = Pie("性别饼图") pie.add("", attr, list_num, is_label_show=True) pie.render(d + r"\picture\sex_pie.html") # 评论者所在城市分布可视化 def city_distribution(cityName): city_list = list(set(cityName)) city_dict = {city_list[i]: 0 for i in range(len(city_list))} for i in range(len(city_list)): city_dict[city_list[i]] = cityName.count(city_list[i]) # 根据数量(字典的键值)排序 sort_dict = sorted(city_dict.items(), key=lambda d: d[1], reverse=True) city_name = [] city_num = [] for i in range(len(sort_dict)): city_name.append(sort_dict[i][0]) city_num.append(sort_dict[i][1]) import random from pyecharts import Bar bar = Bar("评论者城市分布") bar.add("", city_name, city_num, is_label_show=True, is_datazoom_show=True) bar.render(d + r"\picture\city_bar.html") # 每日评论总数可视化分析 def time_num_visualization(time): from pyecharts import Line time_list = list(set(time)) time_dict = {time_list[i]: 0 for i in range(len(time_list))} time_num = [] for i in range(len(time_list)): time_dict[time_list[i]] = time.count(time_list[i]) # 根据数量(字典的键值)排序 sort_dict = sorted(time_dict.items(), key=lambda d: d[0], reverse=False) time_name = [] time_num = [] print(sort_dict) for i in range(len(sort_dict)): time_name.append(sort_dict[i][0]) time_num.append(sort_dict[i][1]) line = Line("评论数量日期折线图") line.add( "日期-评论数", time_name, time_num, is_fill=True, area_color="#000", area_opacity=0.3, is_smooth=True, ) line.render(d + r"\picture\c_num_line.html") # 评论者猫眼等级、评分可视化 def level_score_visualization(userLevel, score): from pyecharts import Pie userLevel_list = list(set(userLevel)) userLevel_num = [] for i in range(len(userLevel_list)): userLevel_num.append(userLevel.count(userLevel_list[i])) score_list = list(set(score)) score_num = [] for i in range(len(score_list)): score_num.append(score.count(score_list[i])) pie01 = Pie("等级环状饼图", title_pos='center', width=900) pie01.add( "等级", userLevel_list, userLevel_num, radius=[40, 75], label_text_color=None, is_label_show=True, legend_orient="vertical", legend_pos="left", ) pie01.render(d + r"\picture\level_pie.html") pie02 = Pie("评分玫瑰饼图", title_pos='center', width=900) pie02.add( "评分", score_list, score_num, center=[50, 50], is_random=True, radius=[30, 75], rosetype="area", is_legend_show=False, is_label_show=True, ) pie02.render(d + r"\picture\score_pie.html") time = [] nickName = [] gender = [] cityName = [] userLevel = [] score = [] content = '' content = read_csv() # 1 词云 jiebaclearText(content) make_wordcloud(content) # pyecharts词云 # word_cloud(content) # 2 性别分布 sex_distribution(gender) # 3 城市分布 city_distribution(cityName) # 4 评论数 time_num_visualization(time) # 5 等级,评分 level_score_visualization(userLevel, score)

无法使用symfony进程从laravel运行python脚本(退出代码:-1073740791(未知错误))

<div class="post-text" itemprop="text"> <p>i am trying to run python script from laravel using symfony process. here is my controller </p> <pre><code>public function test() { $process = new Process("C:/Users/faraz/Anaconda3/python C:/xampp/htdocs/fyp_final1/public/temp.py"); $process-&gt;run(); if (!$process-&gt;isSuccessful()) { throw new ProcessFailedException($process); } dump(json_decode($process-&gt;getOutput(), true)); } </code></pre> <p>here is my python script, i placed it in public folder of my project. </p> <pre><code>import json data='abc' print(json.dumps(data)) </code></pre> <p><strong>Error</strong></p> <blockquote> <p>The command "C:/Users/faraz/Anaconda3/python C:/xampp/htdocs/fyp_final1/public/temp.py" failed. Exit Code: -1073740791(Unknown error) Working directory: C:\xampp\htdocs\fyp_final1\public Output: ================ Error Output: ================ Fatal Python error: failed to get random numbers to initialize Python</p> </blockquote> <p>how ever when i run it on terminal it works fine.</p> </div>

我可以依赖php扩展存储在/ usr / lib / php5 / 20121212中

<div class="post-text" itemprop="text"> <p>I'm creating an ansible role that installs a pear module (pam). I want the role to check if the module is already installed using a creates= clause.</p> <p>This module installs itself in /usr/lib/php5/20121212/pam.so but it feels a bit shaky to rely on that. What is a better way to find out where the php extension modules are stored?</p> </div>

高山ctypes loadlibrary()上的python失败,并出现OSError:重定位./cc.so:时出错::initial-exec TLS解析为./cc.so中的动态定义

<div class="post-text" itemprop="text"> <p>I working on using golang builded shared library in python script(ctypes loadlibrary) on alpine based container.</p> <h2>But it is failed as follows,</h2> <blockquote> <p>/usr/src/app # <strong>go build -o cc.so -buildmode=c-shared main.go</strong></p> <p>/usr/src/app # <strong>readelf -d cc.so</strong></p> <p>Dynamic section at offset 0x10cd10 contains 22 entries: Tag Type Name/Value 0x0000000000000001 (NEEDED) Shared library: [libc.musl-x86_64.so.1] 0x0000000000000010 (SYMBOLIC) 0x0 0x000000000000000c (INIT) 0x42000 0x000000000000000d (FINI) 0x92ed9 0x0000000000000019 (INIT_ARRAY) 0xa2078 0x000000000000001b (INIT_ARRAYSZ) 8 (bytes) 0x000000006ffffef5 (GNU_HASH) 0x270 0x0000000000000005 (STRTAB) 0xa50 0x0000000000000006 (SYMTAB) 0x378 0x000000000000000a (STRSZ) 1026 (bytes) 0x000000000000000b (SYMENT) 24 (bytes) 0x0000000000000003 (PLTGOT) 0x10deb0 0x0000000000000002 (PLTRELSZ) 720 (bytes) 0x0000000000000014 (PLTREL) RELA 0x0000000000000017 (JMPREL) 0x41a00 0x0000000000000007 (RELA) 0xe58 0x0000000000000008 (RELASZ) 265128 (bytes) 0x0000000000000009 (RELAENT) 24 (bytes) 0x000000000000001e (FLAGS) SYMBOLIC BIND_NOW STATIC_TLS 0x000000006ffffffb (FLAGS_1) Flags: NOW NODELETE 0x000000006ffffff9 (RELACOUNT) 11040 0x0000000000000000 (NULL) 0x0</p> <p>/usr/src/app # <strong>python test.py</strong> Traceback (most recent call last): File "test.py", line 2, in lib = ctypes.cdll.LoadLibrary('./cc.so') File "/usr/lib/python2.7/ctypes/init.py", line 444, in LoadLibrary return self._dlltype(name) File "/usr/lib/python2.7/ctypes/init.py", line 366, in init self._handle = _dlopen(self._name, mode) OSError: Error relocating ./cc.so: : initial-exec TLS resolves to dynamic definition in ./cc.so</p> </blockquote> <h2>I have tried the following docker images</h2> <ol> <li><p>Alpine 3.9 install go and python 2.7 on it</p></li> <li><p>go1.12:alpine and python2.7:alpine run go build to create shared library(go build -o cc.so -buildmode=c-shared main.go) then copy cc.so to python2.7:alpine container, run python test.py</p></li> </ol> <p>The same problem.</p> <p><strong>But if I use ubuntu16.04 image and install go and python to do the same test, it works.</strong></p> <h2>The main.go and test.py are as follows,</h2> <pre><code>//main.go package main import "C" //export add func add(left, right int) int { return left + right } //export minus func minus(left, right int) int { return left - right } //export multiply func multiply(left, right int) int { return left * right } //export divide func divide(left, right int) int { return left / right } //export testPrint func testPrint(){ print("test") } func main() { } // test.py import ctypes lib = ctypes.cdll.LoadLibrary('./cc.so') if lib is not None: print ("can load so") </code></pre> </div>

python用代码下载文件文件大小为0或只有2KB怎么解决?

[](https://www.zhihu.com/question/375476720/answer/1045096119 "") [](https://segmentfault.com/q/1010000021869084 "") ``` #!/usr/bin/env python # coding=utf-8 #import importlib,sys #import sys #sys.setdefaultencoding('gbk') '''import sys import imp import sys reload(sys) sys.setdefaultencoding('utf8') ''' ''' import sys sys.setdefaultencoding('utf-8') import jieba import json''' from bs4 import BeautifulSoup import urllib.request import urllib.parse as parse import ssl import re import os,os.path import codecs import requests def getHtml(url): global html page = urllib.request.urlopen(url) html = page.read() return html def file(url1,file_name,name): print(url1) headers = {'Host': 'download.lfd.uci.edu','User-Agent':'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER','Referer': 'https://www.lfd.uci.edu/~gohlke/pythonlibs/', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'zh-CN,zh;q=0.8'} #req = urllib.urlretrieve(download_url,headers=headers) #urllib.request.urlopen('https://www.lfd.uci.edu/~gohlke/pythonlibs/') #req = urllib.request.Request(url=url,headers=header) request = requests.get(url=url1,headers=headers) #response = urllib.request.urlopen(request) global i i += 1 file = open(name ,'wb+') file.write(request.content) file.close() print(file_name) print("Completed : .... %d ..." % x) save_path = os.getcwd() url = 'https://www.lfd.uci.edu/' html = getHtml(url) html=''' <li><a href="javascript:;" onclick=" javascript:dl([101,105,52,56,106,100,50,118,54,95,110,53,119,47,116,99,51,104,113,108,45,112,115,97,46,49,109], &quot;E53AD6:=&lt;F4?C5G5GHC&gt;D?2C&gt;D?2C;098FI471G;@B&quot;); &quot;javascript: dl(&quot;" title="[614 KB] [Oct 17, 2019]">ad3‑2.2.1‑cp38‑cp38‑win_amd64.whl</a></li> <li><a href="javascript:;" onclick=" javascript:dl([101,108,116,49,47,105,53,99,50,104,97,119,46,115,100,113,51,110,112,118,56,106,45], &quot;&lt;7D&gt;AB5139=?E7;7;2E6A?CE6A?CE:4@?7;:80&quot;); &quot;javascript: dl(&quot;" title="[544 KB] [Oct 17, 2019]">ad3‑2.2.1‑cp38‑cp38‑win32.whl</a></li> <li><a href="javascript:;" onclick=" javascript:dl([101,52,108,119,95,116,104,109,45,100,47,50,55,51,99,105,46,49,53,97,106,115,113,112,110,54,118], &quot;D:CEFIA49B8&lt;7:?:?@7=F&lt;;7=F&lt;;672&gt;G3B68H0?251&quot;); &quot;javascript: dl(&quot;" title="[609 KB] [Oct 02, 2018]">ad3‑2.2.1‑cp37‑cp37m‑win_amd64.whl</a></li> <li><a href="javascript:;" onclick=" javascript:dl([101,100,50,106,53,51,116,105,115,49,108,46,97,45,104,118,47,119,113,55,112,110,109,99], &quot;712AC&gt;35?;04&lt;1:1:8&lt;FC4B&lt;FC4BE&lt;@6D41:@=9&quot;); &quot;javascript: dl(&quot;" title="[540 KB] [Oct 02, 2018]">ad3‑2.2.1‑cp37‑cp37m‑win32.whl</a></li> <li><a href="javascript:;" onclick=" javascript:dl([101,119,50,116,49,54,115,112,106,104,99,51,100,46,108,109,95,97,53,110,118,113,105,47,45,52], &quot;517D6CA2F@;:G1&lt;1&lt;3G96:4G96:4&gt;G0EB?@&gt;;4H&lt;08=&quot;); &quot;javascript: dl(&quot;" title="[598 KB] [Oct 02, 2018]">ad3‑2.2.1‑cp36‑cp36m‑win_amd64.whl</a></li> <li><a href="javascript:;" onclick=" javascript:dl([101,110,54,49,113,104,45,108,99,53,116,46,106,115,51,112,50,109,97,118,119,105,47,100], &quot;&lt;?;3&gt;B89EAF=5?:?:257&gt;=157&gt;=1@5CD0=?:C46&quot;); &quot;javascript: dl(&quot;" title="[534 KB] [Oct 02, 2018]">ad3‑2.2.1‑cp36‑cp36m‑win32.whl</a></li> <li><a href="javascript:;" onclick=" javascript:dl([101,53,119,105,112,46,51,104,106,108,95,49,97,47,118,54,109,45,52,99,110,116,113,115,100,50], &quot;FH7E3=0D&lt;B350&lt;;G5@H4H4:@B350@B350?@12C9;?G&gt;A4168&quot;); &quot;javascript: dl(&quot;" title="[596 KB] [Oct 02, 2018]">ad3‑2.2.1‑cp35‑cp35m‑win_amd64.whl</a></li> <li><a href="javascript:;" onclick=" javascript:dl([101,46,104,53,109,47,99,106,115,50,110,119,100,49,113,118,108,51,45,116,112,97,105], &quot;786=C&gt;2B45C@24D;@A8080&lt;A5C@2A5C@23A:E9@80:1?&quot;); &quot;javascript: dl(&quot;" title="[533 KB] [Oct 02, 2018]">ad3‑2.2.1‑cp35‑cp35m‑win32.whl</a></li> <li><a href="javascript:;" onclick=" javascript:dl([101,106,45,105,47,112,95,115,104,119,49,109,116,52,51,53,108,118,97,99,110,113,50,46,100,54], &quot;6E0D4@&gt;;3B4=&lt;3AG=1EFEF91B4=&lt;1B4=&lt;:182C5A:GH&lt;F87?&quot;); &quot;javascript: dl(&quot;" title="[599 KB] [Oct 02, 2018]">ad3‑2.2.1‑cp34‑cp34m‑win_amd64.whl</a></li> <li><a href="javascript:;" onclick=" javascript:dl([101,97,119,113,51,109,49,118,47,110,100,104,50,53,106,112,45,99,108,52,115,46,116,105], &quot;C;=2&gt;6&lt;E7@&gt;3B7093?;D;D5?@&gt;3B?@&gt;3B4?1F83;D1:A&quot;); &quot;javascript: dl(&quot;" title="[539 KB] [Oct 02, 2018]">ad3‑2.2.1‑cp34‑cp34m‑win32.whl</a></li> <li><a href="javascript:;" onclick=" javascript:dl([101,52,49,116,45,53,100,51,97,109,118,54,113,105,46,50,106,95,112,119,47,55,108,115,110,104,99], &quot;F&gt;?;A942CIA&gt;DC7563&gt;=&gt;=13IA&gt;D3IA&gt;D83B&lt;G@785:0=BHE&quot;); &quot;javascript: dl(&quot;" title="[642 KB] [Oct 02, 2018]">ad3‑2.2.1‑cp27‑cp27m‑win_amd64.whl</a></li> <li><a href="javascript:;" onclick=" javascript:dl([101,46,53,49,106,110,108,47,50,99,118,105,112,109,116,119,51,97,100,113,45,115,104,55], &quot;D73B;91=68;7F6@A?C70702C8;7FC8;7F&lt;C&gt;:4?70&gt;E5&quot;); &quot;javascript: dl(&quot;" title="[556 KB] [Oct 02, 2018]">ad3‑2.2.1‑cp27‑cp27m‑win32.whl</a></li> </ul> ''' print('html done') #html.decode('utf-8') #print(html) '''headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1)AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'} r = requests.get(url, headers = headers) r.encoding = "utf-8" soup = BeautifulSoup(r.text, "html.parser") #html_mod=re.sub(pattern=".",repl=".",string=html.decode('utf-8')) for link in soup.find_all('a'): #soup.find_all返回的为列表 print(link.get('href')) #name_list+=link ''' name_list = html#soup.find_all('a')#re.findall(r']">*-cp38-win_amd64.whl',html.decode('utf-8')) x=1 files=os.listdir(save_path) print(files) print(type(name_list)) name_list=str(name_list) name_list1=[] #print(name_list) #for name in name_list: k=0 # name[k]=str(name1[k]) for i in range(len(name_list)): j=0 if name_list[i-2:i+1]==']">': name_list1.append(name_list[i+1:i+60]) global m if k<len(name_list1): for l in range(len(name_list1[k])): if l-9>=0: if name_list1[k][l-4:l]=='.whl' or name_list1[k][l-3:l]=='.gz' or name_list1[k][l-4:l]=='.zip': j=1 m=l if j==1: name_list1[k]=name_list1[k][0:m] k+=1 '''if j==0: name_list.remove(name)''' #file_name = os.path.join(save_path ,name) i=0 #print(name) print(name_list1) for name in name_list1: j=0 for l in range(len(name)): if l-9>=0: if name[l-4:l]=='.whl' or name[l-3:l]=='.gz' or name[l-4:l]=='.zip': j=1 m=l if j==1: name=name[0:m] k+=1 if name in files: continue '''if name=='Delny‑0.4.1‑cp27‑none‑win_amd64.whl</a></li>\n<li>' or name==Delny‑0.4.1‑cp27‑none‑win32.whl</a></li> </ul> </: continue ''' print('no:'+str(x)) print('\ndownload '+name) # importlib.reload(sys) #imp.reload(sys) for l in range(len(name)): if l-9>=0: if name[l-4:l]=='.whl' or name[l-3:l]=='.gz' or name[l-4:l]=='.zip': j=1 m=l if j==1: name=name[0:m] k+=1 string='https://download.lfd.uci.edu/pythonlibs/s2jqpv5t/' + name#[0:4+name.find('.whl')]#https://download.lfd.uci.edu/pythonlibs/s2jqpv5t/ print('00'+save_path) file(string,save_path,name) x=x+1 print('09'+name_list) print('finished') ``` ``` #!/usr/bin/env python # coding=utf-8 #import importlib,sys #import sys #sys.setdefaultencoding('gbk') '''import sys import imp import sys reload(sys) sys.setdefaultencoding('utf8') ''' ''' import sys sys.setdefaultencoding('utf-8') import jieba import json''' #from bs4 import BeautifulSoup import urllib.request import urllib.parse as parse import ssl import re import os,os.path import codecs import requests def getText(html): '''headers = {'Host': 'https://pypi.org','User-Agent':'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER','Referer': 'https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'zh-CN,zh;q=0.8'} #req = urllib.urlretrieve(download_url,headers=headers) ''' #urllib.request.urlopen('https://www.lfd.uci.edu/~gohlke/pythonlibs/') #req = urllib.request.Request(url=url,headers=header) #headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} #import requests res = requests.get(html) res.encoding = 'utf-8' #print(res.text) words=res.text ''' soup = BeautifulSoup(res.text, "html.parser") words = "" for a1 in soup.find_all("a"): words = words + str(a1.string) ''' return words def file(url1,file_name,name): print(url1) headers = {'Host': 'https://files.pythonhosted.org/packages/','User-Agent':'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER','Referer': 'https://pypi.org/', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'zh-CN,zh;q=0.8'} #req = urllib.urlretrieve(download_url,headers=headers) #urllib.request.urlopen('https://www.lfd.uci.edu/~gohlke/pythonlibs/') #req = urllib.request.Request(url=url,headers=header) request = requests.get(url=url1,headers=headers) #response = urllib.request.urlopen(request) global i i += 1 file = open(name ,'wb+') file.write(request.content) file.close() print(file_name) print("Completed : .... %d ..." % x) '''for i in range(len(name_list)): j=0 if name_list[i-24:i+1]=='https://pypi.org/project/': name_list1.append(name_list[i+1:i+60])''' def get(url): global name_list1 res=getText(url) #print('\n\n\n\n\n\nok\n\n\n\n\n\n\n\n\n\n') #name_list = getText(url) #print(res) print('html done,page:'+str(count)+'\n') for i in range(len(res)): #j=0 if (res[i-8:i+1]=='/project/')==True: name_list1.append('https://pypi.org'+res[i-8:i+20]) #print(name_list1) def trim(list1): k=0 list2=[] for i in list1: j=25 while j<len(list1[k]): if list1[k][j]=='/': list2.append(list1[k][0:j]) break j+=1 k+=1 return list2 def get1(url): """o=0 for n in len(url): if url[n]=='"': url=url[0:n-1]+'#files' """ global namelist url=url+'#files' #import requests res = requests.get(url) res.encoding = 'utf-8' #print(res.text) html=res.text for p in range(len(html)): stri='https://files' if html[p-len(stri):p]==stri: namelist.append(html[p-len(stri):p+170]) save_path = os.getcwd() ''' url = 'https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3' name_list = getText(url) print(name_list) print('html done') #html.decode('utf-8') print(name_list)''' x=1 files=os.listdir(save_path) #print(files) #print(type(name_list)) name_list1=[] #print(name_list) #for name in name_list: k=0 # name[k]=str(name1[k]) '''for i in range(len(name_list)): j=0 if name_list[i-25:i+1]=='https://pypi.org/project/': name_list1.append(name_list[i-25:i+20]) for u in range(len(name_list1[len(name_list1)])): if name_list1[len(name_list1)][u]==' ': name_list1[len(name_list1)]=name_list1[len(name_list1)][0:u-1] ''' global count count=2 name_list1=[] for count in range(1): get('https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3&page='+str(count)) """ global m if k<len(name_list1): for l in range(len(name_list1[k])): if l-9>=0: if name_list1[k][l-4:l]=='.whl' or name_list1[k][l-3:l]=='.gz' or name_list1[k][l-4:l]=='.zip': j=1 m=l if j==1: name_list1[k]=name_list1[k][0:m] k+=1""" '''if j==0: name_list.remove(name)''' #file_name = os.path.join(save_path ,name) #i=0 #print(name) #print(name_list1) namelist=[] h=0 for y in trim(name_list1): get1(y) print(namelist) if h==3: break h+=1 i=0 for name in namelist: j=0 for l in range(len(name)): if l-9>=0: if name[l-4:l]=='.whl' or name[l-3:l]=='.gz' or name[l-4:l]=='.zip': j=1 m=l break if j==1: name=name[0:m] k+=1 while m>0: if m<len(name): if name[m]=='/': filename=name[m+1:len(name)]#p] break m-=1 if filename in files: continue '''if name=='Delny‑0.4.1‑cp27‑none‑win_amd64.whl</a></li>\n<li>' or name==Delny‑0.4.1‑cp27‑none‑win32.whl</a></li> </ul> </: continue ''' print('no:'+str(x)) print('\ndownload '+name) # importlib.reload(sys) #imp.reload(sys) for l in range(len(name)): if l-9>=0: if name[l-4:l]=='.whl' or name[l-3:l]=='.gz' or name[l-4:l]=='.zip': j=1 m=l break if j==1: name=name[0:m] k+=1 p=m #string='https://download.lfd.uci.edu/pythonlibs/s2jqpv5t/' + name#[0:4+name.find('.whl')]#https://download.lfd.uci.edu/pythonlibs/s2jqpv5t/ print('00'+save_path) file(name,save_path,filename) print('\n........'+filename+'..........complete\n') x=x+1 print('09') print('finished') ``` 求高手解决

使用Golang Docker引擎创建容器时出错

<div class="post-text" itemprop="text"> <p>I am creating a project in Go and I am using both "github.com/docker/docker/client" and "github.com/docker/docker/api/types", but when I try and create a container I get the following error:</p> <blockquote> <p>ERROR: 2016/10/03 22:39:26 containers.go:84: error during connect: Post <a href="https://%2Fvar%2Frun%2Fdocker.sock/v1.23/containers/create" rel="nofollow noreferrer">https://%2Fvar%2Frun%2Fdocker.sock/v1.23/containers/create</a>: http: server gave HTTP response to HTTPS client</p> </blockquote> <p>I can't understand why this is happening and it only happened after using the new golang docker engine(the old "github.com/docker/engine-api" is now deprecated).</p> <p>The code isn't anything complicated, so I wonder if I am missing something:</p> <pre><code> resp, err := cli.Pcli.ContainerCreate(context.Background(), initConfig(), nil, nil, "") if err != nil { return err } </code></pre> <p>And the initConfig that is called does the following:</p> <pre><code>func initConfig() (config *container.Config) { mount := map[string]struct{}{"/root/host": {}} return &amp;container.Config{Image: "leadis_image", Volumes: mount, Cmd: strslice.StrSlice{"/root/server.py"}, AttachStdout: true}} </code></pre> <p>Also here is my dockerfile</p> <blockquote> <p>FROM debian</p> <p>MAINTAINER Leadis Journey</p> <p>LABEL Description="This docker image is used to compile and execute user's program."</p> <p>LABEL Version="0.1"</p> <p>VOLUME /root/host/</p> <p>RUN apt-get update &amp;&amp; yes | apt-get upgrade</p> <p>RUN yes | apt-get install gcc g++ python3 make</p> <p>COPY container.py /root/server.py</p> </blockquote> <p><strong>EDIT</strong></p> <p>Just tried to test it with a simpler program</p> <pre><code>package main import ( "fmt" "os" "io/ioutil" "github.com/docker/docker/client" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/strslice" "golang.org/x/net/context" ) func initConfig() (config *container.Config) { mount := map[string]struct{}{"/root/host": {}} return &amp;container.Config{Image: "leadis_image", Volumes: mount, Cmd: strslice.StrSlice{"/root/server.py"}, AttachStdout: true} } func main() { client, _ := client.NewEnvClient() cwd, _ := os.Getwd() ctx, err := os.Open(cwd+"/Dockerfile.tar.gz") if err != nil { fmt.Println(err) return } build, err := client.ImageBuild(context.Background(), ctx, types.ImageBuildOptions{Tags: []string{"leadis_image"}, Context: ctx, SuppressOutput: false}) if err != nil { fmt.Println(err) return } b, _ := ioutil.ReadAll(build.Body) fmt.Println(string(b)) _, err = client.ContainerCreate(context.Background(), initConfig(), nil, nil, "") if err != nil { fmt.Println(err) } } </code></pre> <p>Same dockerfile, but I still get the same error:</p> <blockquote> <p>error during connect: Post <a href="https://%2Fvar%2Frun%2Fdocker.sock/v1.23/containers/create" rel="nofollow noreferrer">https://%2Fvar%2Frun%2Fdocker.sock/v1.23/containers/create</a>: http: server gave HTTP response to HTTPS client</p> </blockquote> </div>

python 2.7.5 random.randint(0,1) 错误

Traceback (most recent call last): File "E:/code/python/pycharm/wangyi_5.py", line 43, in <module> simFlips(100,100) File "E:/code/python/pycharm/wangyi_5.py", line 20, in simFlips heads,tails=flipTrial(numFlips) File "E:/code/python/pycharm/wangyi_5.py", line 12, in flipTrial coin=random.randint(0,1) AttributeError: 'builtin_function_or_method' object has no attribute 'randint' import random import math from pylab import * def flipTrial(numFlips): heads,tails=0,0 for i in xrange(0,numFlips):#xrange进行示例时不用建表,依次执行结果,比rang节省空间 coin=random.randint(0,1) if coin==0:heads +=1 else:tails+=1 return heads,tails

python 爬虫 出现IOError错误

# -*- coding:utf-8 -*- #! /usr/bin/env python import urllib import urllib2 import re page = 1 url = 'http://www.qiushibaike.com/hot/page/' + str(page) user_agent = 'Mozilla/4.0(compatible;MSIE 5.5;Windows NT)' headers = {'User-Agent':user_agent} try: request = urllib2.Request(url,headers = headers) response = urllib2.urlopen(request) content = response.read().decode('utf-8','ignore') pattern = re.compile(r'<div.*?author.*?>*?<img.*?>.*?<a.*?title="(.*?)">.*?<div.*?>.*?(.*?)</div>', re.S) items = re.findall(pattern,content) for item in items: print item[0],item[1] except urllib2.URLError, e: if hasattr(e,"code"): print e.code if hasattr(e,"reason"): print e.reason ```![图片说明](https://img-ask.csdn.net/upload/201604/29/1461898513_494366.png) ```这是出现错误的信息,在powershell中设置chcp 65001就会出现IOError错误,设置成chcp 437或者936就会出现下面的乱码,请问是什么原因? ``` ```

python3:为什么列表遍历跳过了7

n = int(input()) num_list = [int(i) for i in input().split()] print(num_list) for i in num_list: num = i print(i) while (num != 1): print(num, end=' ') if(num % 2 == 1): num = (num * 3 + 1) // 2 else: num = num // 2 if(num in num_list): num_list.remove(num) print() new_list = sorted(num_list, reverse=True) print(new_list) ![图片说明](https://img-ask.csdn.net/upload/201909/08/1567907578_473487.png)

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

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

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

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

和黑客斗争的 6 天!

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

点沙成金:英特尔芯片制造全过程揭密

“亚马逊丛林里的蝴蝶扇动几下翅膀就可能引起两周后美国德州的一次飓风……” 这句人人皆知的话最初用来描述非线性系统中微小参数的变化所引起的系统极大变化。 而在更长的时间尺度内,我们所生活的这个世界就是这样一个异常复杂的非线性系统…… 水泥、穹顶、透视——关于时间与技艺的蝴蝶效应 公元前3000年,古埃及人将尼罗河中挖出的泥浆与纳特龙盐湖中的矿物盐混合,再掺入煅烧石灰石制成的石灰,由此得来了人...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

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

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

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

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

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

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

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

C++11:一些微小的变化(新的数据类型、template表达式内的空格、nullptr、std::nullptr_t)

本文介绍一些C++的两个新特性,它们虽然微小,但对你的编程十分重要 一、Template表达式内的空格 C++11标准之前建议在“在两个template表达式的闭符之间放一个空格”的要求已经过时了 例如: vector&lt;list&lt;int&gt; &gt;; //C++11之前 vector&lt;list&lt;int&gt;&gt;; //C++11 二、nullptr ...

优雅的替换if-else语句

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

深入剖析Springboot启动原理的底层源码,再也不怕面试官问了!

大家现在应该都对Springboot很熟悉,但是你对他的启动原理了解吗?

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

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

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

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

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

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

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

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

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

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

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

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

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

【阿里P6面经】二本,curd两年,疯狂复习,拿下阿里offer

二本的读者,在老东家不断学习,最后逆袭

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

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

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

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

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

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

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

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

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

微软为一人收购一公司?破解索尼程序、写黑客小说,看他彪悍的程序人生!...

作者 | 伍杏玲出品 | CSDN(ID:CSDNnews)格子衬衫、常掉发、双肩包、修电脑、加班多……这些似乎成了大众给程序员的固定标签。近几年流行的“跨界风”开始刷新人们对程序员的...

终于,月薪过5万了!

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

我说我懂多线程,面试官立马给我发了offer

不小心拿了几个offer,有点烦

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

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

立即提问
相关内容推荐