小编raf*_*elc的帖子

文件下载 - 负文件长度

我想从我的服务器下载文件(mp3).

我想显示下载进度,但我遇到的问题是整个文件大小-1.

截图: 在此输入图像描述
我的代码:

try {
    URL url = new URL(urls[0]);
    // URLConnection connection = url.openConnection();
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.connect();
    int fileSize = connection.getContentLength();
    if (fileSize == -1)
        fileSize = connection.getHeaderFieldInt("Length", -1);
    InputStream is = new BufferedInputStream(url.openStream());
    OutputStream os = new FileOutputStream(myFile);

    byte data[] = new byte[1024];
    long total = 0;
    int count;
    while ((count = is.read(data)) != -1) {
        total += count;
        Log.d("fileSize", "Lenght of file: " + fileSize);
        Log.d("total", "Lenght of file: …
Run Code Online (Sandbox Code Playgroud)

java android

6
推荐指数
1
解决办法
652
查看次数

如何将测试api的Locust结果写入文件

我通过API调用测试,

locust -f locustfile.py --host=http://localhost --no-web  --hatch-rate=20 --clients=10000
Run Code Online (Sandbox Code Playgroud)

得到了一个结果

 Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
 POST 8000/queries.json                                           137     0(0.00%)       5       2      23  |       5   11.00

--------------------------------------------------------------------------------------------------------------------------------------------
 Total                                                            708     0(0.00%)    
Run Code Online (Sandbox Code Playgroud)

我想把这个结果写成一个文件.谁能帮我这个?

下面是python中的代码

@task(1)
def test_topview(self):
    post_data_topview = """{ "category": "321",   "num": 20,   "genderCat" : ["23"] }"""
    with self.client.request(method="POST", url="http://192.168.1.107:8001/queries.json", headers= {"Content-Type" : "application/json"}, data = post_data_topview, catch_response = True ) as response:
        if not matched(response.content) :
            response.failure("No content")
Run Code Online (Sandbox Code Playgroud)

非常感谢你.

python python-2.7 locust

6
推荐指数
2
解决办法
4267
查看次数

Pandas:如何按一列的日期对数据帧行进行排序

所以我有两个不同的数据框,并将两者连接起来。所有列都相同;但是,日期列具有M/D/YR格式的各种不同日期。

在此输入图像描述 数据帧日期在序列中稍后被打乱

有没有办法保留整个数据框本身,并 根据日期列中的日期对行进行排序。我还想保留日期的格式。

所以基本上

date        people
6/8/2015    1
7/10/2018   2
6/5/2015    0
Run Code Online (Sandbox Code Playgroud)

转换为:

date          people
6/5/2015      0
6/8/2015      1
7/10/2018     2
Run Code Online (Sandbox Code Playgroud)

谢谢你!

PS:我已经尝试过其他帖子中的选项,但它不起作用

python pandas

6
推荐指数
1
解决办法
1774
查看次数

KeyError:将classframe保存到excel时的<class'pandas._libs.tslibs.timestamps.Timestamp'>

早安,我一直在使用python大约一年半,我发现自己面临着一个我无法解决的基本问题.

我有一个简单的数据帧(df),不大(大约12k行和10列),包括一个"datetime64 [ns]"格式的列,一个"float64",所有其他列都是"对象".我调试了,可以说错误来自datetime列.

当我将此df保存到Excel时,我收到以下消息:

在test.to_excel(writer,'test')文件"C:\ Users\renaud.viot\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas \"中的文件"test.py",第16行core\frame.py",第1766行,在to_excel引擎=引擎中)文件"C:\ Users\renaud.viot\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\io\formats\excel .py",第652行,写入freeze_panes = freeze_panes)文件"C:\ Users\renaud.viot\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\io\excel.py",line 1395,在write_cells xcell.value中,fmt = self._value_with_fmt(cell.val)文件"C:\ Users\renaud.viot\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\cell\cell .py",第291行,值为self._bind_value(value)文件"C:\ Users\renaud.viot\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\cell\cell.py" ,第193行,在_bind_value中自我._set_time_format(value)文件"C:\ Users\renaud.viot\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\cell\cell.py",第277行,在_set_time_format self.nu中 mber_format = fmts [type(value)] KeyError:

我正在使用的代码如下:

import pandas as pd
import datetime
from pandas import ExcelWriter

test = pd.read_excel("test_in.xlsx")
test["CaseDate"] = pd.to_datetime(test["CaseDate"])
writer = ExcelWriter("test_out.xlsx")
test.to_excel(writer,'test')
writer.save()
Run Code Online (Sandbox Code Playgroud)

请参阅下面的数据样本:

>    A   CaseDate 
> 0  A 2018-08-30 
> 1  A 2018-08-30 
> 2  A 2018-08-30 
> 3  A 2018-08-30 
> 4  A 2018-08-30 
> 5  A 2018-08-30 
> 6 …
Run Code Online (Sandbox Code Playgroud)

python excel dataframe python-3.x pandas

6
推荐指数
1
解决办法
3248
查看次数

Numpy dtype=int

在下面的代码中。我得到了 x1 的预期结果

import numpy as np 
x1 = np.arange(0.5, 10.4, 0.8)
print(x1)
[ 0.5  1.3  2.1  2.9  3.7  4.5  5.3  6.1  6.9  7.7  8.5  9.3 10.1]
Run Code Online (Sandbox Code Playgroud)

但在下面的代码中,当我设置 dtype=int 时,为什么 x2 的结果不是[ 0 1 2 2 3 4 5 6 6 7 8 9 10],而是我得到 x2 的值,因为[ 0 1 2 3 4 5 6 7 8 9 10 11 12]最后一个值 12 超过了 10.4 的最终值。请澄清我对此的概念。

import numpy as np 
x2 = np.arange(0.5, 10.4, 0.8, dtype=int)
print(x2)
[ …
Run Code Online (Sandbox Code Playgroud)

python numpy numerical-computing python-3.x numpy-ndarray

6
推荐指数
1
解决办法
9059
查看次数

android用渐变创建饼图

有没有办法用这样的渐变创建圆?

在此输入图像描述

我得到的是这样的:

<shape
       android:innerRadiusRatio="3"
       android:thicknessRatio="10"
       android:shape="ring">
     <gradient
               android:endColor="@color/cyan_dark"
               android:startColor="@color/red"
               android:type="radial"
               android:gradientRadius="340"
               android:centerX="50%"
               android:centerY="0" />
</shape>
Run Code Online (Sandbox Code Playgroud)

android radial-gradients android-drawable

5
推荐指数
1
解决办法
3089
查看次数

如何用pythonic方式将元组分成两个

我遇到了一个问题:收到一个包含任何类型对象的元组,并将其分成两个元组:第一个,只有字符串; 第二个,只有数字.

好的.标准算法类似于:

def separate(input_tuple):
    return_tuple = ([],[])
    for value in input_tuple:
        if isinstance(value, str):
            return_tuple[0].append(value)
        if isinstance(value, numbers.Number):
            return_tuple[1].append(value)
    return tuple([tuple(l) for l in return_tuple])
Run Code Online (Sandbox Code Playgroud)

这样,我们只迭代一次.

我的问题是:有没有办法以更加pythonic的方式做到这一点?单线?

我试过了

( tuple([i for i in input_tuple if isinstance(i,str)]), tuple([i for i in input_tuple if isinstance(i,numbers.Number)]))
Run Code Online (Sandbox Code Playgroud)

但它效率较低,因为我们两次迭代输入元组.

也,

tuple([ tuple( [i for i in input_tuple if isinstance(i, k)]) for k in ((float ,int,complex), str) ])
Run Code Online (Sandbox Code Playgroud)

有同样的问题,因为我们做了两次迭代.这是可能只迭代一次仍然得到结果,或者因为我正在处理分离成两个元组,这是不可能的?

谢谢!

python tuples list-comprehension python-2.7

5
推荐指数
1
解决办法
879
查看次数

Pandas/numpy 加权平均 ZeroDivisionError

创建 lambda 函数来计算加权平均值并将其发送到字典。

wm = lambda x: np.average(x, weights=df.loc[x.index, 'WEIGHTS'])

# Define a dictionary with the functions to apply for a given column:
f = {'DRESS_AMT': 'max', 
     'FACE_AMT': 'sum',
     'Other_AMT': {'weighted_mean' : wm}}

# Groupby and aggregate with dictionary:
df2=df.groupby(['ID','COL1'], as_index=False).agg(f)
Run Code Online (Sandbox Code Playgroud)

此代码有效,但如果权重总计为 0 ,则加权平均 lambda 函数会失败ZeroDivisionError。在这些情况下,我希望输出“Other_AMT”仅为 0。

我阅读了有关使用 np.ma.average (屏蔽平均值)的文档,但无法理解如何实现它

python numpy divide-by-zero weighted-average pandas

5
推荐指数
1
解决办法
4162
查看次数

从字符串中提取列表

我正在使用 python 并面临从具有该列表的字符串中提取特定列表对象的问题。

这是我的字符串中的列表对象。

input = "[[1,2,3],[c,4,r]]"
Run Code Online (Sandbox Code Playgroud)

我需要这样的输出。

output = [[1,2,3],[c,4,r]]
Run Code Online (Sandbox Code Playgroud)

有什么办法可以做到这一点吗?

python python-2.7

5
推荐指数
1
解决办法
9306
查看次数

将一组字典解析为单行pandas(Python)

嗨,我有一个类似于下面的熊猫df

information         record
name                apple
size                {'weight':{'gram':300,'oz':10.5},'description':{'height':10,'width':15}}
country             America
partiesrelated      [{'nameOfFarmer':'John Smith'},{'farmerID':'A0001'}]
Run Code Online (Sandbox Code Playgroud)

我想把df转换成另一个像这样的df

information                  record
name                         apple
size_weight_gram             300
size_weight_oz               10.5
size_description_height      10
size_description_width       15 
country                      America
partiesrelated_nameOfFarmer  John Smith
partiesrelated_farmerID      A0001
Run Code Online (Sandbox Code Playgroud)

在这种情况下,字典将解析成单行,其中size_weight_gram包含值.

的代码 df

df = pd.DataFrame({'information': ['name', 'size', 'country', 'partiesrealated'], 
                   'record': ['apple', {'weight':{'gram':300,'oz':10.5},'description':{'height':10,'width':15}}, 'America', [{'nameOfFarmer':'John Smith'},{'farmerID':'A0001'}]]})
df = df.set_index('information')
Run Code Online (Sandbox Code Playgroud)

python dataframe pandas

5
推荐指数
1
解决办法
71
查看次数