您可以使用将函数作为参数的装饰函数,并以 @称为 @
def DetermineAge(func):
def wrapper(*args, **kwargs):
age = func(*args, **kwargs)
if age < 2:
print("Stage of Life: A Baby")
elif age < 4:
print("Stage of Life: A Toddler")
elif age < 13:
print("Stage of Life: A Kid")
elif age < 20:
print("Stage of Life: A Teenager")
elif age < 65:
print("Stage of Life: An Adult")
elif age >= 65:
print("Stage of Life: An Elder")
else:
print("Mistakes were made, please restart the program and try again.")
return age
return wrapper
@DetermineAge
def GetAge():
age = int(input("Please enter your age: "))
return age
age = GetAge()
这是两个想法如何工作的想法:)
import discord
from discord.ext import commands
class Support(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
if self.client.user.mentioned_in(message):
checkMessage = message.content.split("@")
if checkMessage[0] == "@":
mention = discord.Embed(
title = "The prefix is `,help`",
colour = 0xeeffee
)
await message.channel.send(embed = mention)
def setup(client):
client.add_cog(Support(client))
import discord
from discord.ext import commands
class Support(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
if self.client.user.mentioned_in(message):
if message.content.startswith("@"):
mention = discord.Embed(
title = "The prefix is `,help`",
colour = 0xeeffee
)
await message.channel.send(embed = mention)
def setup(client):
client.add_cog(Support(client))
此查询错误地编写了。您可以首先尝试在每个表上运行“右”查询,而不是从外部使用外部“选择”以获得最终结果,您需要:代码示例:
select state, sum(total) from (
select state, count(id) as total from tablea group by state
union
select state, count(id) as total from tableb group by state) as t3
group by state
是的,您可以通过VPC端点策略实现这一目标。
这是文档)的示例。该政策使特定的IAM角色可以从Amazon ECR中汲取图像:
{
"Statement": [{
"Sid": "AllowPull",
"Principal": {
"AWS": "arn:aws:iam::1234567890:role/role_name"
},
"Action": [
"ecr:BatchGetImage",
"ecr:GetDownloadUrlForLayer",
"ecr:GetAuthorizationToken"
],
"Effect": "Allow",
"Resource": "*"
}]
}
如果您具有N×M矩阵,则将其解释为对N维数据的观察,即输入中的每一列都是输入空间中的向量。由于 UMAP
降低了数据的维度,因此输入中的行必须大于请求数量的输出组件, n_components
,默认为2 and can and can and can' t(此刻)在UMAP.JL中为1
您对二维数据有86个观察结果。由于数据已经是二维,因此您不能使用 umap
来降低维度。
常规概述:
data = pd.DataFrame(data=data_)
n = 2
def function_data(df, n):
data = df.copy()
idx1= [0,2,4]
idx2=[1,3,5]
ids = [idx1, idx2]
for id in ids:
print(data, '\n') # I print before each iteration just to show it's working.
data.loc[id, 'Number_a'] = data.Number_a.mul(n)
data.loc[id, 'Number_b'] = data.Number_b.add(data.Number_c)
return data
data = function_data(data, n)
print(data, '\n')
输出:
Number_a Number_b Number_c
0 12 11 10
1 13 11 5
2 14 11 4
3 15 12 3
4 16 12 2
5 17 12 1
Number_a Number_b Number_c
0 24 21 10
1 13 11 5
2 28 15 4
3 15 12 3
4 32 14 2
5 17 12 1
Number_a Number_b Number_c
0 24 21 10
1 26 16 5
2 28 15 4
3 30 15 3
4 32 14 2
5 34 13 1
要完成所需的操作,您需要将视图分配给颜色-0或1,以便映射正确的颜色。这可以使用地图完成。传说的手柄需要添加自定义文本,以便分配蓝色和红色,并使用正确的标签显示。我已经使用随机数作为数据来绘制所需的图,并将您的代码尽可能多地保留。
代码
import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
size = []
price = []
view = []
for i in range(0,100):
size.append(round(random.random(),3))
price.append(round(random.random(),3))
view.append(int(random.random()*10 % 2))
df = pd.DataFrame({'size':size, 'price':price, 'view':view})
colors = {0:'red', 1:'blue'}
plt.scatter(x=df['size'], y=df['price'], c=df['view'].map(colors))
plt.xlabel("Size", fontsize = 25, c = "green")
plt.ylabel("Price", fontsize = 25, c = "green")
markersize=8) for k, v in colors.items()]
custom = [Line2D([], [], marker='.', color='red', linestyle='None'),
Line2D([], [], marker='.', color='blue', linestyle='None')]
plt.legend(handles = custom, labels=['No View', 'View'], bbox_to_anchor= (1.05, 0.5), loc= "lower left")
plt.show()
输出图
仅使用请求和BS4很难但可能。不完全确定您要解析的信息,但这应该对您有所帮助:
import requests, lxml, re, json
from bs4 import BeautifulSoup
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
# works with different countries, languages
params = {
"q": "mcdonalds",
"gl": "jp",
"hl": "ja", # japanese
}
response = requests.get("https://www.google.com/search", headers=headers, params=params)
soup = BeautifulSoup(response.text, 'lxml')
local_results = []
for result in soup.select('.VkpGBb'):
title = result.select_one('.dbg0pd span').text
try:
website = result.select_one('.yYlJEf.L48Cpd')['href']
except:
website = None
try:
directions = f"https://www.google.com{result.select_one('.yYlJEf.VByer')['data-url']}"
except:
directions = None
address_not_fixed = result.select_one('.lqhpac div').text
# removes phone number from "address_not_fixed" variable
# https://regex101.com/r/cwLdY8/1
address = re.sub(r' · ?.*', '', address_not_fixed)
phone = ''.join(re.findall(r' · ?(.*)', address_not_fixed))
try:
hours = result.select_one('.dXnVAb').previous_element
except:
hours = None
try:
options = result.select_one('.dXnVAb').text.split('·')
except:
options = None
local_results.append({
'title': title,
'phone': phone,
'address': address,
'hours': hours,
'options': options,
'website': website,
'directions': directions,
})
print(json.dumps(local_results, indent=2, ensure_ascii=False))
这是您可以回来的输出,希望这会有所帮助!
# English results:
{
"title": "McDonald's",
"phone": "(620) 251-3330",
"address": "Coffeyville, KS",
"hours": " ⋅ Opens 5AM",
"options": [
"Curbside pickup",
"Delivery"
],
"website": "https://www.mcdonalds.com/us/en-us/location/KS/COFFEYVILLE/302-W-11TH/4581.html?cid=RF:YXT:GMB::Clicks",
"directions": "https://www.google.com/maps/dir//McDonald's,+302+W+11th+St,+Coffeyville,+KS+67337/data=!4m6!4m5!1m1!4e2!1m2!1m1!1s0x87b784f6803e4c81:0xf5af9c9c89f19918?sa=X&hl=en&gl=us"
}
看来您正在尝试在给定范围内打印质数。可以说,混合质数的发现并打印它们是引起问题的原因。通过适当的分解,将不存在此问题:
def generate_primes(low, up):
for num in range(max(low, 2), up+1):
if all(num % i for i in range(2, num)):
yield num
print(*generate_primes(low, up), sep=',')
作为积极的副作用,您现在可以在程序的其他部分重复使用Prime Generator,而该发电机不需要打印。
另请注意,检查所有数字最多 num
是不需要的 - 如果该数字为复合,则其中一个因素将较小或等于SQRT(NUM)。因此,更快的Prime发电机将是类似的:
def generate_primes(low, up):
for num in range(max(low, 2), up+1):
if all(num % i for i in range(2, int(num**0.5 + 1))):
yield num
因此,事实证明,我的问题源于以前设置forge_client_id和forge_client_secret System Systems变量,对FORGE进行了以前的未成功试验。这意味着我创建的Visual Studio解决方案是读取这些值,而不是我在代码中输入的值。感谢Autodesk的Cyrille Fauvel帮助我解决了这一点。
Cyrille说,他将回馈其余的Forge团队,他们应该在控制台上向ID和秘密的细节报告,以防止将来发生这种情况。
模式注册表将仅阻止配置用于使用它的生产商。默认情况下,经纪人不会执行模式。为此,您需要付费。
很难说出您正在显示的图像(您使用的端点是什么),但是如果它是Confluent Kafka Rest代理,请参阅生产和消费avro 。
# Produce a message using Avro embedded data, including the schema which will
# be registered with schema registry and used to validate and serialize
# before storing the data in Kafka
curl -X POST -H "Content-Type: application/vnd.kafka.avro.v2+json" \
-H "Accept: application/vnd.kafka.v2+json" \
--data '{"value_schema": "{\"type\": \"record\", \"name\": \"User\", \"fields\": [{\"name\": \"name\", \"type\": \"string\"}]}", "records": [{"value": {"name": "testUser"}}]}' \
"http://localhost:8082/topics/avrotest"
如果没有这些细节,您只是发送普通文本JSON,这将不做模式检查。
如果您可以直接访问KAFKA群集,那么编写AVRO生产者客户端会更容易,因为您每次要发送事件时都不需要嵌入键和/或值模式。
您可以通过爆炸
来平移每月/总列,如下所示:
val df = Seq(
("Micheal", "Scott", "[email protected]", 4000, 5000, 3400, 50660),
("Dwight", "Schrute", "[email protected]", 1200, 6900, 1000, 35000),
("Kevin", "Malone", "[email protected]", 9000, 6000, 18000, 32000)
).toDF("FName","SName", "Email", "Jan 2021", "Feb 2021", "Mar 2021", "Total 2021")
val moYrCols = Array("Jan 2021", "Feb 2021", "Mar 2021", "Total 2021") // (**)
val otherCols = df.columns diff moYrCols
val structCols = moYrCols.map{ c =>
val moYr = split(lit(c), "\\s+")
struct(moYr(1).as("Year"), moYr(0).as("Month"), col(c).as("Value"))
}
df.
withColumn("flattened", explode(array(structCols: _*))).
select(otherCols.map(col) :+ $"flattened.*": _*).
show
/*
+-------+-------+------------------+----+-----+-----+
| FName| SName| Email|Year|Month|Value|
+-------+-------+------------------+----+-----+-----+
|Micheal| Scott| [email protected]|2021| Jan| 4000|
|Micheal| Scott| [email protected]|2021| Feb| 5000|
|Micheal| Scott| [email protected]|2021| Mar| 3400|
|Micheal| Scott| [email protected]|2021|Total|50660|
| Dwight|Schrute|[email protected]|2021| Jan| 1200|
| Dwight|Schrute|[email protected]|2021| Feb| 6900|
| Dwight|Schrute|[email protected]|2021| Mar| 1000|
| Dwight|Schrute|[email protected]|2021|Total|35000|
| Kevin| Malone| [email protected]|2021| Jan| 9000|
| Kevin| Malone| [email protected]|2021| Feb| 6000|
| Kevin| Malone| [email protected]|2021| Mar|18000|
| Kevin| Malone| [email protected]|2021|Total|32000|
+-------+-------+------------------+----+-----+-----+
*/
(**)使用模式匹配,以防万一列;例如:
val moYrCols = df.columns.filter(_.matches("[A-Za-z]+\\s+\\d{4}"))
”中
在
“ https://stackoverflow.com/a/2334741/1501497
“输出”
:通过这种方式,我看到了即将发生的一切。当我对所看到的东西感到满意时,我将回滚
将其更改为commit
。我通常需要记录我所做的工作,因此在运行滚动式查询时,我使用
“ to text”
选项,并且同时保存脚本和输出的结果。 (当然,如果我更换了太多行,这是不切实际的)In the accepted answer, after the:
I would add:
What I usually do is putting everything in a roll backed transaction and using the
"OUTPUT"
: in this way I see everything that is about to happen. When I am happy with what I see, I change theROLLBACK
intoCOMMIT
.I usually need to document what I did, so I use the
"results to Text"
option when I run the roll-backed query and I save both the script and the result of the OUTPUT. (Of course this is not practical if I changed too many rows)如何从SQL Server中的选择中更新?