我有一个包含约210万个日志字符串的切片,我想创建一个切片,其中字符串尽可能均匀分布.
这是我到目前为止:
// logs is a slice with ~2.1 million strings in it.
var divided = make([][]string, 0)
NumCPU := runtime.NumCPU()
ChunkSize := len(logs) / NumCPU
for i := 0; i < NumCPU; i++ {
temp := make([]string, 0)
idx := i * ChunkSize
end := i * ChunkSize + ChunkSize
for x := range logs[idx:end] {
temp = append(temp, logs[x])
}
if i == NumCPU {
for x := range logs[idx:] {
temp = append(temp, logs[x])
}
}
divided …Run Code Online (Sandbox Code Playgroud) 我正在使用SQLAlchemy 1.1.0b将大量数据批量上传到PostgreSQL中,并且遇到了重复的关键错误。
from sqlalchemy import *
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.automap import automap_base
import pg
engine = create_engine("postgresql+pygresql://" + uname + ":" + passw + "@" + url)
# reflectively load the database.
metadata = MetaData()
metadata.reflect(bind=engine)
session = sessionmaker(autocommit=True, autoflush=True)
session.configure(bind=engine)
session = session()
base = automap_base(metadata=metadata)
base.prepare(engine, reflect=True)
table_name = "arbitrary_table_name" # this will always be arbitrary
mapped_table = getattr(base.classses, table_name)
# col and col2 exist in the table.
chunks = [[{"col":"val"},{"col2":"val2"}],[{"col":"val"},{"col2":"val3"}]]
for chunk in chunks:
session.bulk_insert_mappings(mapped_table, …Run Code Online (Sandbox Code Playgroud) 我想生成最近 3 年内的随机时间戳,并使用以下格式打印出来:%d/%b/%Y:%H:%M:%S %z
这是我现在所拥有的:
package main
import (
"strconv"
"time"
"math/rand"
"fmt"
)
func randomTimestamp() time.Time {
randomTime := rand.Int63n(time.Now().Unix() - 94608000) + 94608000
randomNow, err := time.Parse("10/Oct/2000:13:55:36 -0700", strconv.FormatInt(randomTime, 10))
if err != nil {
panic(err)
}
return randomNow
}
func main() {
fmt.Println(randomTimestamp().String())
}
Run Code Online (Sandbox Code Playgroud)
这总是抛出:panic: parsing time "...": month out of range。如何生成给定范围的随机时间戳,然后使用标准库将其转换为我想要的字符串格式?
我有一本要发送到 API 的字典,不幸的是,该 API 要求字典按非常特定的顺序排列。我正在从文件加载字典。
现在json.load(fh, object_pairs_hook=OrderedDict)完全按照它应该做的,并按字母顺序排列顶级键,但我需要以不同的方式对字典进行排序。
具体顺序:
{
"kind": "string",
"apiVersion": "string",
"metadata": {...},
"spec": {
"subKey": "string"
}
}
Run Code Online (Sandbox Code Playgroud)
如何使用从文件加载的字典指定顶级和子级键的字典顺序?
我正在从AWS S3下载带有boto3的文件,它是一个基本的JSON文件.
{
"Counter": 0,
"NumOfReset": 0,
"Highest": 0
}
Run Code Online (Sandbox Code Playgroud)
我可以打开JSON文件,但是当我在更改某些值后将其转储回同一个文件时,我得到了IOError: [Errno 9] Bad file descriptor.
with open("/tmp/data.json", "rw") as fh:
data = json.load(fh)
i = data["Counter"]
i = i + 1
if i >= data["Highest"]:
data["Highest"] = i
json.dump(data, fh)
fh.close()
Run Code Online (Sandbox Code Playgroud)
我只是使用了错误的文件模式,还是我做错了?
我使用 Flask 路由作为代理来下载文件,如下所示:
@esa_handler.route("/data/<int:series>/<int:file_num>", methods=["GET"])
def DownloadRemote(series, file_num):
"""
Downloads the remote files from the ESA.
:param series: 0-20.
:param file_num: File within the series, 0-255
:return: Compressed CSV file.
"""
# if the file is bad.
if series >= 20 and file_num > 110:
return jsonify({"error": "file does not exist."})
url = "http://cdn.gea.esac.esa.int/Gaia/gaia_source/csv/GaiaSource_000-{:03d}-{:03d}.csv.gz".format(series,
file_num)
req = requests.get(url, stream=True)
return Response(stream_with_context(req.iter_content(chunk_size=2048)), content_type=req.headers["content-type"])
Run Code Online (Sandbox Code Playgroud)
它工作正常,但是,呈现给客户端的文件名是传递到端点的文件号。例如,如果我http://127.0.0.1:5000/esa/data/0/0下载第一个文件,它会下载,但 Chrome/Firefox/IE/Edge 会提供将文件保存为文件名“0”的功能。虽然这没有什么问题,但我想要更好的用户体验。
如何拦截响应以根据请求的 URL 提供文件名?
我有一个我正在使用的结构,我不确定如何正确地循环它.我想访问字段名称,但它所做的只是在每个循环中递增计数.
这是我的结构:
type ImgurJson struct {
Status int16 `json:"status"`
Success bool `json:"success"`
Data []struct {
Width int16 `json:"width"`
Points int32 `json:"points"`
CommentCount int32 `json:"comment_count"`
TopicId int32 `json:"topic_id"`
AccountId int32 `json:"account_id"`
Ups int32 `json:"ups"`
Downs int32 `json:"downs"`
Bandwidth int64 `json:"bandwidth"`
Datetime int64 `json:"datetime"`
Score int64 `json:"score"`
Account_Url string `json:"account_url"`
Topic string `json:"topic"`
Link string `json:"link"`
Id string `json:"id"`
Description string`json:"description"`
CommentPreview string `json:"comment_preview"`
Vote string `json:"vote"`
Title string `json:"title"`
Section string `json:"section"`
Favorite bool `json:"favorite"`
Is_Album bool `json:"is_album"`
Nsfw bool `json:"nsfw"` …Run Code Online (Sandbox Code Playgroud) 我有一个基本的Dockerfile:
FROM ubuntu:xenial
USER test
ENTRYPOINT ["/bin/bash"]
Run Code Online (Sandbox Code Playgroud)
对于这个Dockerfile,我希望能够在没有密码的情况下创建用户,并且在运行Docker容器时,我希望使用该用户而不是root用户.当我尝试运行容器时docker run -it test:1,我收到此错误:
docker: Error response from daemon: linux spec user: unable to find user test: no matching entries in passwd file.
Run Code Online (Sandbox Code Playgroud)
如何在Dockerfile中创建用户并在交互式运行容器时让该用户成为默认用户?
python ×4
go ×3
json ×3
chunking ×1
dictionary ×1
docker ×1
dockerfile ×1
file ×1
flask ×1
postgresql ×1
proxy ×1
random ×1
slice ×1
sqlalchemy ×1
struct ×1
time ×1
upsert ×1