社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Chris  »  全部回复
回复总数  41
3 年前
回复了 Chris 创建的主题 » uvicorn[fastapi]python同时运行HTTP和HTTPS

使用 HTTPSRedirectMiddleware 。这将强制重定向到 https 在收到任何请求时。

from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
app.add_middleware(HTTPSRedirectMiddleware)

您正在将会话保存到数据库中,这在Heroku上是一个合理的选择,但您正在使用SQLite作为数据库。

赫罗库的 ephemeral filesystem 使SQLite成为一个糟糕的数据库选择。数据不会在dyno之间共享,并且会在dyno重新启动时丢失。 This happens frequently (每天至少一次)。

无论您选择如何处理会话,如果您想继续使用Heroku,都应该从SQLite迁移到PostgreSQL这样的客户机服务器数据库。简单地这样做可能会解决你的会话问题,这是一个副作用。

3 年前
回复了 Chris 创建的主题 » 将Python列表字段一分为二,并将其保留在原位

列出对救援的理解。

data = ['Intel', 'Core', 'i5-4210Y', '@', '1.50GHz', '(20%)', '998', 'N']
result = [y for x in data for y in x.split('-')]
# ['Intel', 'Core', 'i5', '4210Y', '@', '1.50GHz', '(20%)', '998', 'N']
3 年前
回复了 Chris 创建的主题 » 在Python上合并数组而不求其重叠单元格的和

除非我遗漏了什么,否则这和用A2然后A3迭代替换A1 nan值有什么不同?因为你没有求和,你可以从其他数组中任意选取一个非空值。

A1 = np.array([[[1, 1, 1],[np.nan, np.nan, np.nan], [1, np.nan, 1]],[[1, 1, 1],[np.nan, np.nan, np.nan], [1, np.nan, 1]]])
A2 = np.array([[[1, np.nan, 1],[1, np.nan, np.nan], [1, np.nan, 1]],[[1, 1, 1],[np.nan, np.nan, 1], [np.nan, 1, 1]]])
A3 = np.array([[[1, 1, 1],[np.nan, np.nan, 1], [np.nan, 1, 1]],[[1, np.nan, 1],[1, np.nan, np.nan], [1, np.nan, 1]]])


A1[np.isnan(A1)] = A2[np.isnan(A1)]
A1[np.isnan(A1)] = A3[np.isnan(A1)]
print(A1)

输出

[[[ 1.  1.  1.]
  [ 1. nan  1.]
  [ 1.  1.  1.]]

 [[ 1.  1.  1.]
  [ 1. nan  1.]
  [ 1.  1.  1.]]]
3 年前
回复了 Chris 创建的主题 » 是否有python库允许从标记转换为html(包括列表)?[闭门]

这是一个相当标准的功能。

问题可能在于你的投入。在列表上方添加一个空行:

###Stepped
The translation will pause if:

- There are no translations for this word
- There are multiple translations for this word

And will ask you how to continue

我还建议在标题后添加一个空行,以及一个空格,将哈希与标题文本分隔开来:

### Stepped

The translation will pause if:

- There are no translations for this word
- There are multiple translations for this word

And will ask you how to continue

这有助于源代码的可读性,而源代码是 explicit design consideration :

标记格式语法的首要设计目标是使其尽可能可读。其想法是,标记格式的文档应该可以按原样以纯文本的形式发布,而不会看起来像是被标记了标签或格式说明。

之间的空间 ### Stepped 在许多规范和实施中也需要, including CommonMark ,它正在迅速获得吸引力:

开头的顺序 # 字符后面必须跟空格或制表符,或在行尾。

3 年前
回复了 Chris 创建的主题 » Python中的数据转换/格式化

单向使用 itertools.combinations :

from itertools import combinations

def comb_df(ser):
    return pd.DataFrame(list(combinations(ser, 2)), columns=["from", "to"])

new_df = df.groupby("ID_1")["ID_2"].apply(comb_df).reset_index(drop=True)

输出:

  from to
0    a  b
1    a  c
2    b  c
3    f  g
4    v  x
5    v  y
6    v  z
7    x  y
8    x  z
9    y  z
3 年前
回复了 Chris 创建的主题 » Python日期时间转换器

strTime的字符串表示形式似乎不支持您的时区。您可以使用带有时区的dateutil解析器来解决这个问题。

from dateutil import parser, tz

ts = [
    '08:27Sun, Dec 19, 2021 IST',
    'Sun, 19 Dec 2021 02:28:56 +0000'
]


def format_ts(ts):
    return [parser.parse(t, tzinfos={'IST':tz.gettz('Asia/Calcutta')}) for t in ts]

format_ts(ts)

输出

[datetime.datetime(2021, 12, 19, 8, 27, tzinfo=tzfile('Asia/Calcutta')),
 datetime.datetime(2021, 12, 19, 2, 28, 56, tzinfo=tzutc())]
3 年前
回复了 Chris 创建的主题 » Python:将列表中的元素相乘

您可以将生成的每个组合相乘 combinations 把它们加起来。

from itertools import combinations
from operator import mul
l = [1, 3, 5, 7]

sum([mul(*x) for x in combinations(l,2)])

输出

86

我怀疑您正在使用SQLite作为数据库。 That won't work as expected on Heroku .

然而,关于这一点的大多数问题都有不同的表现:它们看起来像在工作,但一段时间后,当部署新代码时,或者在dyno重启后的第二天,数据就会丢失。

你没有看到新数据的原因 完全 是吗 workers run on dedicated dynos ,与您的 web 每个dyno都有自己的SQLite数据库。你保存到其中一个的任何数据在另一个上都不可见。

你必须切换到客户端服务器 data store Heroku先生自己的 Postgres service 这通常是一个很好的起点。

5 年前
回复了 Chris 创建的主题 » 将实例“count”合并到连接到字符串的列表中(Python3)

IIUC,你需要 enumerate

temporary_list = ["First item", "Second item", "Third item"]
print("\n".join("> [{}] {}".format(n, i) for n, i in enumerate(temporary_list, start=1)))

输出:

> [1] First item
> [2] Second item
> [3] Third item
5 年前
回复了 Chris 创建的主题 » 用python验证输入

如果以后要与整数进行比较,则需要将输入从字符串转换为整数。如果你想避免一次又一次的重复逻辑,你可以使用一个列表。

user_choice = int(input("Please choose from the following:  \n"
                    " 1 for scissor \n"
                    " 2 for rock \n"
                    " 3 for paper. \n"))

while user_choice not in [1,2,3]
6 年前
回复了 Chris 创建的主题 » 使用python生成1d数组表单txt文件

因为第4行(即0,0,0)有三列,而不是前三行。

相反,您可以将所有行连接起来并将其转换为数组:

with open(path2) as f:
    str_arr = ','.join([l.strip() for l in f])

int_arr = np.asarray(str_arr.split(','), dtype=int)

print(int_arr)
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
6 年前
回复了 Chris 创建的主题 » 我需要替换python空列表中的操作结果

首先, lista

其次, list.insert 更换滤芯。它 插入件 列表中的一个新元素,使您的列表 .

修正上述问题(注:我删除了所有的S):

Nb=10
Bx = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
visc = np.array([1135.7891419, 1135.7891419, 1135.7891419, 1135.7891419, 
1135.7891419, 1135.7891419, 1135.7891419, 1135.7891419, 1135.7891419, 
1135.7891419])
lx= np.array([ 25.5,  50.2,  80.3, 101.6, 130.4, 165.8, 190,  235,  237.9, 300 ])
y=300
z=100 
K= np.array([700, 750, 735, 780, 770, 775, 776, 778, 790, 792])
lista = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 
# Brought to outside of the loop

for i in range(Nb):
    if i <Nb-1:
       T= (1/(visc[i]*Bx[i]))*(2*0.001127/(((lx[i])/(y*z*K[i+1]))+((lx[i+1])/(y*z*K[i+1]))))
       lista[i] = T
    else:
       T=0
       lista[i] = T
       # break << Unnecessary
    i=i+1
    print ("Transmisibilidad", i, "+1/2=", T)
print (lista)

Transmisibilidad 1 +1/2= 0.5898517032138213
Transmisibilidad 2 +1/2= 0.3353160034836823
Transmisibilidad 3 +1/2= 0.25529326492917936
Transmisibilidad 4 +1/2= 0.1975969306243128
Transmisibilidad 5 +1/2= 0.15577368804094915
Transmisibilidad 6 +1/2= 0.12984739206381915
Transmisibilidad 7 +1/2= 0.10898534939638185
Transmisibilidad 8 +1/2= 0.09945697161428392
Transmisibilidad 9 +1/2= 0.08765992428620617
[0.5898517032138213, 0.3353160034836823, 0.25529326492917936, 0.1975969306243128, 0.15577368804094915, 0.12984739206381915, 0.10898534939638185, 0.09945697161428392, 0.08765992428620617, 0]

如其他答案所述,它是 sublist = sublist.insert(len(sublist), i+1)

但是,您似乎想要创建一个列表列表(基于函数名),而您的代码目前没有这样做。

def make_list_of_lists(n):
      the_list = []
      sublist = []
      for i in range(n):
          the_list.append(sublist)
      return the_list

print(make_list_of_lists(5))

[[], [], [], [], []]
6 年前
回复了 Chris 创建的主题 » Python,numpy如何基于每行中的值复制数组中的行

使用 numpy.repeat 具有 np.arange :

import numpy as np

    arr = np.array([[[3, 1, 3, 1, 2],
  [4, 4, 4, 2, 0],
  [3, 4, 4, 4, 0],
  [1, 4, 3, 3, 0]],
 [[4, 2, 0, 2, 1],
  [2, 1, 2, 0, 3],
  [4, 1, 3, 4, 3],
  [2, 3, 2, 0, 0]]])

arr2d = np.vstack(arr)
dup = arr2d[np.repeat(np.arange(arr2d.shape[0]), arr2d[:,0])]
np.split(dup, np.cumsum(np.sum(np.split(arr2d[:,0], arr.shape[0]), 1)))[:-1]

输出:

[array([[3, 1, 3, 1, 2],
        [3, 1, 3, 1, 2],
        [3, 1, 3, 1, 2],
        [4, 4, 4, 2, 0],
        [4, 4, 4, 2, 0],
        [4, 4, 4, 2, 0],
        [4, 4, 4, 2, 0],
        [3, 4, 4, 4, 0],
        [3, 4, 4, 4, 0],
        [3, 4, 4, 4, 0],
        [1, 4, 3, 3, 0]]), 
 array([[4, 2, 0, 2, 1],
        [4, 2, 0, 2, 1],
        [4, 2, 0, 2, 1],
        [4, 2, 0, 2, 1],
        [2, 1, 2, 0, 3],
        [2, 1, 2, 0, 3],
        [4, 1, 3, 4, 3],
        [4, 1, 3, 4, 3],
        [4, 1, 3, 4, 3],
        [4, 1, 3, 4, 3],
        [2, 3, 2, 0, 0],
        [2, 3, 2, 0, 0]])]

由于2d数组并不总是具有相同的形状,因此在大多数情况下,它将生成数组列表。这样的不一致并没有得到很好的处理 numpy .

在这种情况下,您可以简单地使用 itertools.repeat 具有 list 理解力。(尽管它看起来与@gmds的答案非常相似)

鉴于 l :

import itertools

l = [[[3, 1, 3, 1, 2], [4, 4, 4, 2, 0], [3, 4, 4, 4, 0], [1, 4, 3, 3, 0]],
 [[4, 2, 0, 2, 1], [2, 1, 2, 0, 3], [4, 1, 3, 4, 3], [2, 3, 2, 0, 0]]]

[[j for i in sub for j in itertools.repeat(i, i[0])] for sub in l]

输出:

[[[3, 1, 3, 1, 2],
  [3, 1, 3, 1, 2],
  [3, 1, 3, 1, 2],
  [4, 4, 4, 2, 0],
  [4, 4, 4, 2, 0],
  [4, 4, 4, 2, 0],
  [4, 4, 4, 2, 0],
  [3, 4, 4, 4, 0],
  [3, 4, 4, 4, 0],
  [3, 4, 4, 4, 0],
  [1, 4, 3, 3, 0]],
 [[4, 2, 0, 2, 1],
  [4, 2, 0, 2, 1],
  [4, 2, 0, 2, 1],
  [4, 2, 0, 2, 1],
  [2, 1, 2, 0, 3],
  [2, 1, 2, 0, 3],
  [4, 1, 3, 4, 3],
  [4, 1, 3, 4, 3],
  [4, 1, 3, 4, 3],
  [4, 1, 3, 4, 3],
  [2, 3, 2, 0, 0],
  [2, 3, 2, 0, 0]]]

单向使用 itertools.tee pairwise :

from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

[0, *map(sum, pairwise(l))]

输出:

[0, 6, 11, 13, 9]
5 年前
回复了 Chris 创建的主题 » 如何托管和编辑与github存储库分离的json文件?

不要将文件用作数据库。使用 数据库 作为数据库。

这是一个很好的建议,但是对于Heroku来说尤其重要 ephemeral filesystem 防止对文件的更改长期保留。

Heroku Postgres 是一个相对容易的开始。它的基本计划是免费的。

6 年前
回复了 Chris 创建的主题 » 开发中的Django电子邮件发送

我敦促你不要在生产中使用Gmail发送电子邮件。它不是为这个而设计的,正如你所发现的,有一些措施可以防止它被用作垃圾邮件中继。即使你发送的是合法的电子邮件,Gmail也会给你带来困难。

相反,使用一个设计用于从托管应用程序(如SendGrid或Mailgun)发送邮件的服务。这两个都是 listed among Heroku's addons 两人都有免费的首发计划。挑一个,看一下它的收尾指南。这不仅可以更好地处理少量邮件,而且可以很好地促进增长。

没有必要用地球仪。只需使用文件名:

git rm client server

我想知道是否有任何方法可以使用通配符方法删除它们 * .

平原 * 地球上没有任何 . 会匹配文件,但也会匹配目录中的大多数内容(基本上是任何没有隐藏前缀的内容 . 本身)。

如果您确实需要执行通配符之类的操作,并且您的文件是可执行的,则可以尝试使用 find ,例如:

find . -maxdepth 1 -executable -type f -exec git rm --cached {} +

man find 关于它的许多选择的细节。

6 年前
回复了 Chris 创建的主题 » 编写Python代码以使用条件语句从现有列创建新的CSV列

使用 numpy.where 具有 pandas.Series.str.rsplit :

import numpy as np
import pandas as pd

df['FileName'] = np.where(df['FileType'].eq('f'),df['Path'].str.rsplit('/').str.get(-1), '')

输出:

  FileType                       Path    FileName
0        d                          /            
1        f        /documents/csv/.zip        .zip
2        d          /documents/images            
3        d             /hive/28374849            
4        f  /hadoop/jdjdjd/dnejfn.img  dnejfn.img
6 年前
回复了 Chris 创建的主题 » Drop函数不处理python的数据帧[duplicate]

我相信你 df 是另一个的副本 pandas.DataFrame .

以下复制了 SettingWithCopyWarning .

import pandas as pd

raw = pd.DataFrame({"a": [1,2], "b": [2,3], "c": [3,4]})
df = raw[["a", "b"]]
df.drop(["a"], 1, inplace = True)

设置为复制警告: 试图在数据帧切片的副本上设置值

请参阅文档中的注意事项: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy 错误=错误)

当你再做一个 熊猫.DataFrame 从现有的,从来没有做直接分配像 df = raw[["a", "b"]] . 相反,使用 pandas.DataFrame.copy() .

raw = pd.DataFrame({"a": [1,2], "b": [2,3], "c": [3,4]})
df = raw[["a", "b"]].copy()
df.drop(["a"], 1, inplace = True)

现在警告消失了,因为 数据框 是一个新的对象,因此根据 the official document :

对副本数据或索引的修改不会反映在原始对象中

6 年前
回复了 Chris 创建的主题 » 如何在jquery[duplicate]中获取具有特定数据id的特定div
$('.content[data-id="Java"]') 

将选择所需的元素

$('.content[data-id="Java"] > button').hide()

会把按钮藏在里面

6 年前
回复了 Chris 创建的主题 » 如何在Mac上使用Python打开CSV?

您传递给“open”的路径不是以“/”开头的,因此python将其视为相对路径。如果需要绝对路径,请从前导“/”开始:

with open("/iCloud Drive⁩/Mesa⁩/Mesa⁩/Estudos/Data Science/Applied Data Science with Python Coursera⁩/course1_downloads⁩/mpg.csv") as csvfile:

你可能正在使用 pandas<0.23.0 sort 添加版本 0.23.0 . 然而, requirements.txt 要求 pandas>=0.20.1 问题似乎是这个函数:

 def construct_holiday_dataframe(self, dates):` 

            . . . 

    all_holidays = pd.concat((all_holidays, country_holidays_df), sort=False)

            . . . 

查看 docs .

看起来他们需要将requirements.txt更新为 pandas>=0.23.0

当你跑 git clean -df asked Git to

从工作树中删除未跟踪的文件

including directories . 你也 told Git to ignore its safety net .

如果git知道这些文件(例如 add ED或 stash 预计起飞时间, even if they were never commit ed )那么它们应该是可以恢复的。试试跑步 git fsck --cache --no-reflogs --lost-found --unreachable 然后往里看 .git/lost-found/ 对于已删除的对象。

否则git无法检索它们;您将不得不依赖其他工具,如现有备份、文件系统快照、文件同步工具或文件系统恢复工具。

经过多次测试,我采用了另一种方法。我不是和熊猫一起去的 制表 将整个数据刮除,然后将整个表结构导出为csv。

from tabulate import tabulate
import csv
import datetime ### Import date function to make the files based on date
import requests
from bs4 import BeautifulSoup



 if (DAY_INTEGER <= 31) and (DAY_INTEGER > 0):

    while True:
        try:
            ### Validate the user input
            form_data = {'UserName': USERNAME, 'Password': PASSWORD}
            with requests.Session() as sesh:
                sesh.post(login_post_url, data=form_data)
                response = sesh.get(internal_url)
                html = response.text
                break
        except requests.exceptions.ConnectionError:
            print ("Whoops! This is embarrasing :( ")
            print ("Unable to connect to the address. Looks like the website is down.")

    if(sesh):

        #BeautifulSoup version
        soup = BeautifulSoup(html,'lxml')
        table = soup.find_all("table")[3] # Skip the first two tables as there isn't something useful there
        df = pd.read_html(str(table))


        df2 = (tabulate(df[0], headers='keys', tablefmt='psql', showindex=False))

        myFile = open(filename+'.csv', 'w')
        myFile.write(str(df2))

    else:
        print("Oops. Something went wrong :(")
        print("It looks like authentication failed")

假设 col_list_filter 是列表列表,两者都是 col_list_filter-min(col_list_filter) max(col_list_filter)-min(col_list_filter) list - list 正如错误消息中所述。

相反,您可以使用 for 循环:

res = []
for i in l:
    max_, min_ = max(i), min(i)
    res.append([(j - min_)/(max_ - min_) for j in i])
res

或一个班轮(但效率低得多):

[[(j - min(i))/(max(i) - min(i)) for j in i] for i in l]

输出:

[[0.0,
  0.5884873389626358,
  0.6396995276767564,
  0.7329666273317014,
  0.4842313879485761,
  1.0],
 [0.0,
  0.3198112142984678,
  0.688061628145554,
  0.9057703742992778,
  0.4510016620800218,
  1.0],
 [0.0,
  0.8174664500409363,
  0.6534818573661288,
  0.7434609459640676,
  0.625429283659689,
  1.0]]

The order of your buildpacks is important :

列表中的最后一个构建包将用于确定 process types 为了申请。将忽略从早期构建包定义的任何进程类型。

你可以跑 heroku help buildpacks 获取命令的完整选项列表。

尝试移动 heroku/nodejs 之后 heroku/python :

heroku buildpacks:set heroku/nodejs
heroku buildpacks:add --index 1 heroku/python

使用验证您的构建包 heroku:buildpacks

如果你没有 Procfile . 在那种情况下 your start script will be run automatically 假设 Heroku/Nodejs酒店 是你的最后一个构建包。

必须为数据库创建一个命名卷,如下所示

version: '3'

services:    
  mysql:
    image: mysql:5.7
    volumes:
      - mysql_data:/var/lib/mysql

volumes:
  mysql_data:

现在你可以安全地跑了 docker-compose stop docker-compose down 不会丢失你的数据 mysql_data 体积。只有当你跑的时候 docker-compose down -v 它也将删除卷。

通过运行 docker volume ls

简要说明:Docker Compose是为开发而设计的,不是为生产而设计的。你可能想考虑一个不同的策略。

6 年前
回复了 Chris 创建的主题 » 在python中获取日期介于两个日期之间的周天数

使用 pandas.to_datetime pandas.date_range :

import pandas as pd

start_date = '01-03-2019'
end_date = '15-03-2019'
days = ['Monday', 'Tuesday']

dates = pd.to_datetime([start_date, end_date], format='%d-%m-%Y')
pd.date_range(dates[0],dates[1],freq='1d').day_name().value_counts()[days]
Monday     2
Tuesday    2
dtype: int64