天生の放荡

文章 评论 浏览 30

天生の放荡 2025-02-20 20:23:21

对于第一个问题,只需添加bottom参数的值即可。我还使用Annotate

import matplotlib.pyplot as plt

ausgaben = 130386
einnahmen = 147233
profit = einnahmen-ausgaben

titles = ["Ausgaben", "Profit", "Einnahmen"]
euros = [ausgaben, profit, einnahmen]

colors = ['#6F8CA7', '#F6BC06', '#59908F']
dummysum1 = []
dummysum2 = []

for i in range(len(euros)):
    dummysum1.append(euros[i]+4000)
    dummysum2.append(max(euros)+15000)
if euros[1] > 0:
    dummysum1[1] = euros[1]+4000
if euros[1] <= 0:
    dummysum1[1] = 4000

position1 = (euros[0]+euros[2])/2

percentile = (euros[2]-euros[0])/euros[0]*100

if percentile > 0:
    label0 = '+{:.1f}%'.format(percentile)
else:
    label0 = '{:.1f}%'.format(percentile)

fig, ax = plt.subplots(figsize=(7, 5))
fig.set_facecolor('#D0A210')
fig.patch.set_alpha(0.2)
ax.bar(titles[0], euros[0], alpha=0.6, color=colors[0])
ax.bar(titles[1], euros[1], alpha=0.6, color=colors[1], bottom=ausgaben)
ax.bar(titles[2], euros[2], alpha=0.6, color=colors[2])
plt.axhline(y=euros[0], color='#BCBCBC')
plt.axhline(y=euros[2], color='#BCBCBC')

ax.set_facecolor('#D0A210')
ax.patch.set_alpha(0.02)

ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)

ax.spines.right.set_visible(False)
ax.spines.left.set_visible(False)
ax.spines.top.set_visible(False)
ax.spines.bottom.set_visible(False)

ax.text(titles[0], dummysum1[0], '{} €'.format(euros[0]), horizontalalignment='center')
ax.text(titles[1], dummysum1[1]+ausgaben, '{} €'.format(euros[1]), horizontalalignment='center')
ax.text(titles[2], dummysum1[2], '{} €'.format(euros[2]), horizontalalignment='center')
ax.text(2.58, position1-1000, label0)

ax.text(titles[0], dummysum2[0], titles[0], horizontalalignment='center')
ax.text(titles[1], dummysum2[1], titles[1], horizontalalignment='center')
ax.text(titles[2], dummysum2[2], titles[2], horizontalalignment='center')

ax.annotate("", xy=(2.5, ausgaben+profit*1.05), xytext=(2.5, ausgaben), arrowprops=dict(arrowstyle="->", color="orange", lw=2.0))

plt.show()

”在此处输入图像说明”

For the first question, just add a value for the bottom parameter. I have also added the arrow using annotate:

import matplotlib.pyplot as plt

ausgaben = 130386
einnahmen = 147233
profit = einnahmen-ausgaben

titles = ["Ausgaben", "Profit", "Einnahmen"]
euros = [ausgaben, profit, einnahmen]

colors = ['#6F8CA7', '#F6BC06', '#59908F']
dummysum1 = []
dummysum2 = []

for i in range(len(euros)):
    dummysum1.append(euros[i]+4000)
    dummysum2.append(max(euros)+15000)
if euros[1] > 0:
    dummysum1[1] = euros[1]+4000
if euros[1] <= 0:
    dummysum1[1] = 4000

position1 = (euros[0]+euros[2])/2

percentile = (euros[2]-euros[0])/euros[0]*100

if percentile > 0:
    label0 = '+{:.1f}%'.format(percentile)
else:
    label0 = '{:.1f}%'.format(percentile)

fig, ax = plt.subplots(figsize=(7, 5))
fig.set_facecolor('#D0A210')
fig.patch.set_alpha(0.2)
ax.bar(titles[0], euros[0], alpha=0.6, color=colors[0])
ax.bar(titles[1], euros[1], alpha=0.6, color=colors[1], bottom=ausgaben)
ax.bar(titles[2], euros[2], alpha=0.6, color=colors[2])
plt.axhline(y=euros[0], color='#BCBCBC')
plt.axhline(y=euros[2], color='#BCBCBC')

ax.set_facecolor('#D0A210')
ax.patch.set_alpha(0.02)

ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)

ax.spines.right.set_visible(False)
ax.spines.left.set_visible(False)
ax.spines.top.set_visible(False)
ax.spines.bottom.set_visible(False)

ax.text(titles[0], dummysum1[0], '{} €'.format(euros[0]), horizontalalignment='center')
ax.text(titles[1], dummysum1[1]+ausgaben, '{} €'.format(euros[1]), horizontalalignment='center')
ax.text(titles[2], dummysum1[2], '{} €'.format(euros[2]), horizontalalignment='center')
ax.text(2.58, position1-1000, label0)

ax.text(titles[0], dummysum2[0], titles[0], horizontalalignment='center')
ax.text(titles[1], dummysum2[1], titles[1], horizontalalignment='center')
ax.text(titles[2], dummysum2[2], titles[2], horizontalalignment='center')

ax.annotate("", xy=(2.5, ausgaben+profit*1.05), xytext=(2.5, ausgaben), arrowprops=dict(arrowstyle="->", color="orange", lw=2.0))

plt.show()

enter image description here

条形图从Python中的轴开始

天生の放荡 2025-02-20 20:16:23

实际上,您需要结合数量和截然不同的东西,类似的东西:

select productcompanyID, count(distinct yearName) as distinctYears
from mydatabase
group by productcompanyID

You actually need to combine count and distinct, something like this:

select productcompanyID, count(distinct yearName) as distinctYears
from mydatabase
group by productcompanyID

SQL查询计数有条件

天生の放荡 2025-02-20 19:07:55

不支持将新字段添加到现有合同中。允许的完整列表在此处 https://docs.onflow.org/cadence/cadence/语言/合同通用性

我建议仅创建一个新的TestNet帐户并将新合同部署到该新地址。

Adding new fields to an existing contract is not supported. The full list of changes allowed are here https://docs.onflow.org/cadence/language/contract-updatability

I would recommend just creating a new Testnet account and deploy the new contracts to that new address.

我已经在TestNet中部署了智能合同,如何更新或删除它们?

天生の放荡 2025-02-20 15:57:58

根据@ToolMakerSteve的指南,我将this.requestfocus()添加到OnElementChanged Block中,现在我的dispatchKeyEvent事件处理程序即使在页面上没有输入控件,也会被击中。

this.Focusable = true;
this.FocusableInTouchMode = true;
this.RequestFocus();
bool f = IsFocused;  // now this is true because of RequestFocus()

Based on @ToolmakerSteve 's guidance I added this.RequestFocus() to the OnElementChanged block, and now my DispatchKeyEvent event handler gets hit even if there is no Entry control on the page.

this.Focusable = true;
this.FocusableInTouchMode = true;
this.RequestFocus();
bool f = IsFocused;  // now this is true because of RequestFocus()

当没有控制焦点时,在Xamarin表单中处理dispatchKeyevent Android平台

天生の放荡 2025-02-20 13:09:43
  div {
    --width: 16;
    --height: 9;
    aspect-ratio: var(--width) / var(--height);
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: deeppink;
    color: dodgerblue;
    font: 6rem monospace;
  }
<div>16∶9</div>

https://developer.mozilla.orgla.org/en-en-us/ DOCS/WEB/CSS/FECTACT-RATIO

  div {
    --width: 16;
    --height: 9;
    aspect-ratio: var(--width) / var(--height);
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: deeppink;
    color: dodgerblue;
    font: 6rem monospace;
  }
<div>16∶9</div>

https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio

维持使用CSS的DIV的纵横比

天生の放荡 2025-02-20 04:54:23

假设您包含提供的html选择包含您的信息的元素并迭代resultset以刮擦信息。避免多个列表,尝试一次刮擦所有信息并以更结构化的方式保存:

...
data = []

for e in soup.select('.ergov3-txtannonce'):
    data.append({
        'title':e.span.get_text(strip=True),
        'city':e.cite.get_text(strip=True)
    })
...

注意: 如果汤中不存在元素,则网站的内容可能会通过javascript - 这将是问一个新问题的预定

from bs4 import BeautifulSoup

html='''
<div class="ergov3-txtannonce">
 <div class="ergov3-h3"><span>
 House 3 pièces, 74 m²
 </span>
 <cite>
 New York (11111)
 </cite>
 </div>
</div>,
 <div class="ergov3-txtannonce">
 <div class="ergov3-h3"><span>
 Appartement 3 pièces, 64 m²
 </span>
 <cite>
 Los Angeles (22222)
 </cite>
 </div>
 <div class="ergov3-txtannonce">
 <div class="ergov3-h3"><span>
 House 4 pièces, 81 m²
 </span>
 <cite>
 Chicago (33333)
 </cite>
 </div>
'''
soup = BeautifulSoup(html)

data = []

for e in soup.select('.ergov3-txtannonce'):
    data.append({
        'title':e.span.get_text(strip=True),
        'city':e.cite.get_text(strip=True)
    })

data
输出
[{'title': 'House 3 pièces, 74 m²', 'city': 'New York (11111)'},
 {'title': 'Appartement 3 pièces, 64 m²', 'city': 'Los Angeles (22222)'},
 {'title': 'House 4 pièces, 81 m²', 'city': 'Chicago (33333)'}]

Assuming you soup contains the provided HTML select the elements that holds your information and iterate over the ResultSet to scrape the information. avoid multiple lists, try to scrape all information in one go and save it in a more structured way:

...
data = []

for e in soup.select('.ergov3-txtannonce'):
    data.append({
        'title':e.span.get_text(strip=True),
        'city':e.cite.get_text(strip=True)
    })
...

Note: If the elements are not present in your soup, content of website may provided dynamically by JavaScript - This would be predestined for asking a new question with exact this focus

Example
from bs4 import BeautifulSoup

html='''
<div class="ergov3-txtannonce">
 <div class="ergov3-h3"><span>
 House 3 pièces, 74 m²
 </span>
 <cite>
 New York (11111)
 </cite>
 </div>
</div>,
 <div class="ergov3-txtannonce">
 <div class="ergov3-h3"><span>
 Appartement 3 pièces, 64 m²
 </span>
 <cite>
 Los Angeles (22222)
 </cite>
 </div>
 <div class="ergov3-txtannonce">
 <div class="ergov3-h3"><span>
 House 4 pièces, 81 m²
 </span>
 <cite>
 Chicago (33333)
 </cite>
 </div>
'''
soup = BeautifulSoup(html)

data = []

for e in soup.select('.ergov3-txtannonce'):
    data.append({
        'title':e.span.get_text(strip=True),
        'city':e.cite.get_text(strip=True)
    })

data
Output
[{'title': 'House 3 pièces, 74 m²', 'city': 'New York (11111)'},
 {'title': 'Appartement 3 pièces, 64 m²', 'city': 'Los Angeles (22222)'},
 {'title': 'House 4 pièces, 81 m²', 'city': 'Chicago (33333)'}]

获取子标签的信息

天生の放荡 2025-02-20 04:41:23

如果要处理多个文件而不手动打开每个文件,则将所有文件放在同一文件夹中,然后编写一个for loop是很方便的。

这是ImageJ宏语言中的一个示例,基于您提供的代码:

// Edit these variables to have your folder paths
inputfolder = "MY_INPUT_FOLDER";
imagefolder = "MY_IMAGE_FOLDER";
outputfolder = "MY_OUTPUT_FOLDER";

// Find out how many files are in the folder
list = getFileList(inputfolder + imagefolder);
num2process = list.length;

// Loop through all files in the folder
for (l = 0; l < num2process; l++) 
{
    open(inputfolder + imagefolder + list[l]);
    
    // After opening, the image is in focus, so get its properties
    filename = getInfo("image.filename");
    current_title = getTitle(); 
    current_image = getImageID();
    selectImage(current_image);   // this puts the image in focus
    
    // With the image selected, process it
    run("Split Channels");
    
    // The channels will have the following names:
    channel1 = "C1-" + current_title; 
    channel2 = "C2-" + current_title; 
    channel3 = "C3-" + current_title;

    // Put them in an array for convenience
    array = newArray(channel1, channel2, channel3); 
    
    // If the processing steps are the same, it's convenient to loop through each channel
    for (channel = 0; channel <=2; channel++) 
    {
        // Select the right channel
        image = array[channel];
        selectWindow(image);
        
        // Apply image processing
        setOption("ScaleConversions", true);
        run("8-bit");
        setAutoThreshold("Default");
        run("Convert to Mask");
        run("Analyze Particles...", "size=20-700 show=Overlay display summarize add composite");    
        run("Close");
    }
    
    // Save the results and name the file appropriately
    string = outputfolder + filename + "_summary.csv";
    saveAs("Results", string);
}

If you want to process several files without manually opening each, it's convenient to put all files in the same folder, and then write a for loop.

Here's an example in the ImageJ macro language, based on the code you provided:

// Edit these variables to have your folder paths
inputfolder = "MY_INPUT_FOLDER";
imagefolder = "MY_IMAGE_FOLDER";
outputfolder = "MY_OUTPUT_FOLDER";

// Find out how many files are in the folder
list = getFileList(inputfolder + imagefolder);
num2process = list.length;

// Loop through all files in the folder
for (l = 0; l < num2process; l++) 
{
    open(inputfolder + imagefolder + list[l]);
    
    // After opening, the image is in focus, so get its properties
    filename = getInfo("image.filename");
    current_title = getTitle(); 
    current_image = getImageID();
    selectImage(current_image);   // this puts the image in focus
    
    // With the image selected, process it
    run("Split Channels");
    
    // The channels will have the following names:
    channel1 = "C1-" + current_title; 
    channel2 = "C2-" + current_title; 
    channel3 = "C3-" + current_title;

    // Put them in an array for convenience
    array = newArray(channel1, channel2, channel3); 
    
    // If the processing steps are the same, it's convenient to loop through each channel
    for (channel = 0; channel <=2; channel++) 
    {
        // Select the right channel
        image = array[channel];
        selectWindow(image);
        
        // Apply image processing
        setOption("ScaleConversions", true);
        run("8-bit");
        setAutoThreshold("Default");
        run("Convert to Mask");
        run("Analyze Particles...", "size=20-700 show=Overlay display summarize add composite");    
        run("Close");
    }
    
    // Save the results and name the file appropriately
    string = outputfolder + filename + "_summary.csv";
    saveAs("Results", string);
}

设置imagej宏到批处理过程实验室图像

天生の放荡 2025-02-19 18:11:08

问题在于返回语句中,因为您正在计算最后一个计数,所以Neo4J必须计算笛卡尔产品。如果您在每个步骤中计算每个节点计数,则将更加最佳。像这样:

MATCH (a:Account{billingCountry: "DE", isDeleted: false})
WHERE a.id IS NOT NULL
MATCH (a)<-[:CREATED]-(u:User)
OPTIONAL MATCH (a) <-[:CONTACT_OF]- (c:Contact{isDeleted: false})
WITH a, u, COUNT(DISTINCT c.id) AS Contact_Count,
OPTIONAL MATCH (a) <-[:OPPORTUNITY_OF]- (o:Opportunity{isDeleted: false, s4sMarked_For_Deletion__C: false})
WITH a, u, Contact_Count, COUNT(DISTINCT o.id) AS Opportunity_Count
OPTIONAL MATCH (a)<-[:OPPORTUNITY_OF]-(open:Opportunity{isClosed: false, isDeleted: false})
WITH a, u, Contact_Count, Opportunity_Count, COUNT(DISTINCT open.id) AS OpenOpp_Count
OPTIONAL MATCH (a) <-[:ATTRIBUTE_OF]- (aa:Attribute_Assignment{isDeleted: false})
WITH a, u, Contact_Count, Opportunity_Count, OpenOpp_Count, COUNT(DISTINCT aa.id) AS Attribute_Count
OPTIONAL MATCH (a) <-[:SALESPLAN_OF]- (s:Sales_Planning)
WITH a, u, Contact_Count, Opportunity_Count, OpenOpp_Count, Attribute_Count,COUNT(DISTINCT s.timeYear) AS Sales_Plan_Count
OPTIONAL MATCH (a) <-[:TASK_OF]- (t:Task{isDeleted: false})
WITH a, u, Contact_Count, Opportunity_Count, OpenOpp_Count, Attribute_Count, Sales_Plan_Count, COUNT(DISTINCT t.id) AS Task_Count
OPTIONAL MATCH (a) <-[:EVENT_OF]- (e:Event{isDeleted: false})
WITH a, u, Contact_Count, Opportunity_Count, OpenOpp_Count, Attribute_Count, Sales_Plan_Count, Task_Count, COUNT(DISTINCT e.id) AS Event_Count
OPTIONAL MATCH (a) <-[:CONTRACT_OF]- (ct:Contract{isDeleted: false})
RETURN
a.id, u.name AS User_Name, u.department AS User_Department, Contact_Count,
Opportunity_Count, OpenOpp_Count, Attribute_Count, Sales_Plan_Count,
Task_Count, Event_Count, COUNT(DISTINCT ct.id) AS Contract_Count

The problem lies, in the RETURN statement, because you are calculating all the counts at the last, neo4j has to calculate the cartesian products. If you calculate each node count at each step, it will be much more optimal. Like this:

MATCH (a:Account{billingCountry: "DE", isDeleted: false})
WHERE a.id IS NOT NULL
MATCH (a)<-[:CREATED]-(u:User)
OPTIONAL MATCH (a) <-[:CONTACT_OF]- (c:Contact{isDeleted: false})
WITH a, u, COUNT(DISTINCT c.id) AS Contact_Count,
OPTIONAL MATCH (a) <-[:OPPORTUNITY_OF]- (o:Opportunity{isDeleted: false, s4sMarked_For_Deletion__C: false})
WITH a, u, Contact_Count, COUNT(DISTINCT o.id) AS Opportunity_Count
OPTIONAL MATCH (a)<-[:OPPORTUNITY_OF]-(open:Opportunity{isClosed: false, isDeleted: false})
WITH a, u, Contact_Count, Opportunity_Count, COUNT(DISTINCT open.id) AS OpenOpp_Count
OPTIONAL MATCH (a) <-[:ATTRIBUTE_OF]- (aa:Attribute_Assignment{isDeleted: false})
WITH a, u, Contact_Count, Opportunity_Count, OpenOpp_Count, COUNT(DISTINCT aa.id) AS Attribute_Count
OPTIONAL MATCH (a) <-[:SALESPLAN_OF]- (s:Sales_Planning)
WITH a, u, Contact_Count, Opportunity_Count, OpenOpp_Count, Attribute_Count,COUNT(DISTINCT s.timeYear) AS Sales_Plan_Count
OPTIONAL MATCH (a) <-[:TASK_OF]- (t:Task{isDeleted: false})
WITH a, u, Contact_Count, Opportunity_Count, OpenOpp_Count, Attribute_Count, Sales_Plan_Count, COUNT(DISTINCT t.id) AS Task_Count
OPTIONAL MATCH (a) <-[:EVENT_OF]- (e:Event{isDeleted: false})
WITH a, u, Contact_Count, Opportunity_Count, OpenOpp_Count, Attribute_Count, Sales_Plan_Count, Task_Count, COUNT(DISTINCT e.id) AS Event_Count
OPTIONAL MATCH (a) <-[:CONTRACT_OF]- (ct:Contract{isDeleted: false})
RETURN
a.id, u.name AS User_Name, u.department AS User_Department, Contact_Count,
Opportunity_Count, OpenOpp_Count, Attribute_Count, Sales_Plan_Count,
Task_Count, Event_Count, COUNT(DISTINCT ct.id) AS Contract_Count

Cypher多选可选匹配 - 模式理解 - 计数不同

天生の放荡 2025-02-19 08:10:02

首先,让我解决您的问题,如标题中所述。

static inline int ror(int num, int count) {
  __asm__ ("ror\t%0, %b1" : "+r"(num) : "c"(count));
  return num;
}

ror(int, int):
        mov     eax, edi
        mov     ecx, esi
        ror     eax, cl
        ret

这就是您的做法,不要忘记-Masm = Intel。我将在下面解释一些详细信息,但基本上,您必须仔细阅读GCC文档。


引用OP,

我真的发现GCC的内联ASM语法比Visual Studio的语法差得多。 GCC几乎试图阻止用户使用汇编...

从某种意义上说,更糟糕的是要学习更多的时间,但是在您知道详细信息之后,它是用于各种低级编程和优化的强大工具。

我在实际程序中使用内联装配的一种情况是使用rcpss指令。它有一个固有的固有,但是当您将其用于单个float时,当前版本的GCC(12.1)会产生非常可怕的代码。

static inline float float_recip(float x) {
  if (__builtin_constant_p(x)) {
    return 1 / x;
  }
  __asm__ ("rcpss\t%0, %0" : "+x"(x));
  return x;
}

这是实际的代码。 __内置_CONSTANT_P在编译时已知X的值时,可以使恒定替换。我故意将两个操作数放在相同的情况下,以避免错误的依赖性问题。

查看将其称为某个地方时如何生成组件。

float f(float x) {
  return float_recip(x) + float_recip(2);
}

f(float):
        rcpss   xmm0, xmm0
        addss   xmm0, DWORD PTR .LC0[rip]
        ret
.LC0:
        .long   1056964608

您可以看到float_recip(2)0.5F常数替换,并且所有不必要的副本都消失了。

您不能使用MSVC内联装配做到这一点,除此之外,它甚至不支持64位。

First, let me solve your problem as stated in the title.

static inline int ror(int num, int count) {
  __asm__ ("ror\t%0, %b1" : "+r"(num) : "c"(count));
  return num;
}

ror(int, int):
        mov     eax, edi
        mov     ecx, esi
        ror     eax, cl
        ret

This is how you do it, and don't forget -masm=intel. I'll explain some details below, but basically, you have to read carefully the GCC docs.


Quoting the OP,

I really find gcc's inline asm syntax much worse than Visual Studio's. It's almost as if GCC is trying to discourage users from using assembly...

It's worse in a sense that it takes more time to learn, but after you know the details, it's a powerful tool for various low level programing and optimization.

One case I use inline assembly in an actual program is to use the rcpss instruction. There is an Intel intrinsic for it, but the current version of GCC (12.1) produces quite horrible code when you use it for a single float.

static inline float float_recip(float x) {
  if (__builtin_constant_p(x)) {
    return 1 / x;
  }
  __asm__ ("rcpss\t%0, %0" : "+x"(x));
  return x;
}

This is the actual code. __builtin_constant_p makes constant substitution possible when the value of x is known at compile-time. I intentionally put both operands the same to avoid the false dependency problem.

See how the assembly is generated when it's called somewhere.

float f(float x) {
  return float_recip(x) + float_recip(2);
}

f(float):
        rcpss   xmm0, xmm0
        addss   xmm0, DWORD PTR .LC0[rip]
        ret
.LC0:
        .long   1056964608

You can see float_recip(2) is replaced with a 0.5f constant, and all the unnecessary copies are gone.

You cannot do this with MSVC inline assembly, apart from that it's not even supported for 64-bit.

如何编写内联装配以刻住旋转

天生の放荡 2025-02-18 17:47:37

Zeromq能够在内部网络上以毫秒延迟。但是,我建议原始的UDP插座。与TCP相比,UDP不会重传丢失的数据包,并且开销非常低(ZMQ使用)。

您可能还需要在网络上进行流量优先级以确保延迟的延迟,但是使用少量数据,您使用的可能不会产生重大影响(这一切都取决于您的特定网络)。我将从实现UDP套接字开始,然后如果您看到不可接受的潜伏期尝试优化网络。

ZeroMQ is capable of sub millisecond latency on an internal network. However, I would recommend raw UDP sockets. UDP doesn't retransmit lost packets and has very low overhead compared to TCP (used by ZMQ).

You may also need to do traffic prioritization on your network to ensure a reasonable latency, but with the small quantity of data you are using it might not have a significant effect (this all depends on your specific network). I would start with implementing a UDP socket then if you are seeing unacceptable latencies try to optimize the network.

网络实时音频传输带有延迟&lt; 100毫秒

天生の放荡 2025-02-18 11:24:30

如果将每个列表元素作为字符串传递,则可以执行这样的操作:

def get_combine(g_combine, g1, g2):
    for i,x in enumerate(g_combine):
        g_combine[i]=eval(x)
    return g_combine

g_combine = ['g1**4', 'g1**3*g2', 'g1**2 * g2**2', 'g1 * g2**3', 'g2**4']
print(get_combine(g_combine, 1, 2))

输出:

[1, 2, 4, 8, 16]

If you pass each list element as string, you can do something like this:

def get_combine(g_combine, g1, g2):
    for i,x in enumerate(g_combine):
        g_combine[i]=eval(x)
    return g_combine

g_combine = ['g1**4', 'g1**3*g2', 'g1**2 * g2**2', 'g1 * g2**3', 'g2**4']
print(get_combine(g_combine, 1, 2))

Output:

[1, 2, 4, 8, 16]

是否有一种方法可以更改列表中不同变量方程的值?

天生の放荡 2025-02-18 08:57:15

注意 /a>,下面的答案可能导致a MOMEMOR泄漏通过反复销毁和重新创建框架。但是,我尚未对自己进行验证。

tkinter中切换帧的一种方法是销毁旧帧,然后用新框架替换。

我已经修改了 Bryan Oakley's 在替换之前,请回答以销毁旧框架。作为额外的奖励,这消除了对容器对象的需求,并允许您使用任何通用frame> frame类。

# Multi-frame tkinter application v2.3
import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.switch_frame(StartPage)

    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()

class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Open page one",
                  command=lambda: master.switch_frame(PageOne)).pack()
        tk.Button(self, text="Open page two",
                  command=lambda: master.switch_frame(PageTwo)).pack()

class PageOne(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Return to start page",
                  command=lambda: master.switch_frame(StartPage)).pack()

class PageTwo(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Return to start page",
                  command=lambda: master.switch_frame(StartPage)).pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

“ ”第2页“

说明

switch_frame()通过接受任何实现

  • 删除旧的_frame如果存在,则将其替换为新帧。
  • 其他添加了.pack()(例如梅纳布尔)的帧将不受影响。
  • 可以与任何实现tkinter.frame的类一起使用。
  • 窗口会自动调整大小以适合新内容

版本历史记录

v2.3

- Pack buttons and labels as they are initialized

v2.2

- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.

v2.1.1

- Remove type-hinting for backwards compatibility with Python 3.4.

v2.1

- Add type-hinting for `frame_class`.

v2.0

- Remove extraneous `container` frame.
    - Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
    - Frame switching is now done with `master.switch_frame()`.

v1.6

- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.

v1.5

  - Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
      - Initializing the frame before calling `.destroy()` results
        in a smoother visual transition.

v1.4

- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
    - Remove `new_frame` variable.

v1.3

- Rename `parent` to `master` for consistency with base `Frame` class.

v1.2

- Remove `main()` function.

v1.1

- Rename `frame` to `_frame`.
    - Naming implies variable should be private.
- Create new frame before destroying old frame.

v1.0

- Initial version.

Note: According to JDN96, the answer below may cause a memory leak by repeatedly destroying and recreating frames. However, I have not tested to verify this myself.

One way to switch frames in tkinter is to destroy the old frame then replace it with your new frame.

I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container object and allows you to use any generic Frame class.

# Multi-frame tkinter application v2.3
import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.switch_frame(StartPage)

    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()

class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Open page one",
                  command=lambda: master.switch_frame(PageOne)).pack()
        tk.Button(self, text="Open page two",
                  command=lambda: master.switch_frame(PageTwo)).pack()

class PageOne(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Return to start page",
                  command=lambda: master.switch_frame(StartPage)).pack()

class PageTwo(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Return to start page",
                  command=lambda: master.switch_frame(StartPage)).pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

Start pagePage onePage two

Explanation

switch_frame() works by accepting any Class object that implements Frame. The function then creates a new frame to replace the old one.

  • Deletes old _frame if it exists, then replaces it with the new frame.
  • Other frames added with .pack(), such as menubars, will be unaffected.
  • Can be used with any class that implements tkinter.Frame.
  • Window automatically resizes to fit new content

Version History

v2.3

- Pack buttons and labels as they are initialized

v2.2

- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.

v2.1.1

- Remove type-hinting for backwards compatibility with Python 3.4.

v2.1

- Add type-hinting for `frame_class`.

v2.0

- Remove extraneous `container` frame.
    - Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
    - Frame switching is now done with `master.switch_frame()`.

v1.6

- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.

v1.5

  - Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
      - Initializing the frame before calling `.destroy()` results
        in a smoother visual transition.

v1.4

- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
    - Remove `new_frame` variable.

v1.3

- Rename `parent` to `master` for consistency with base `Frame` class.

v1.2

- Remove `main()` function.

v1.1

- Rename `frame` to `_frame`.
    - Naming implies variable should be private.
- Create new frame before destroying old frame.

v1.0

- Initial version.

在TKINTER中的两个帧之间切换?

天生の放荡 2025-02-18 05:46:43

每次通过循环创建一个新的black_mask,而不是在与先前迭代相同的掩码上绘制。

    for i in range(len(cnt)):
        blank_mask = np.zeros((thresh.shape[0], thresh.shape[2], 3), np.uint8)
        cv2.drawContours(blank_mask, cnt[i], -1, (0, 255, 0), 1)
        print(cnt[i])
        cv2.imshow('test',blank_mask)
        cv2.waitKey(0)

Create a new blank_mask each time through the loop, rather than drawing on the same mask as the previous iteration.

    for i in range(len(cnt)):
        blank_mask = np.zeros((thresh.shape[0], thresh.shape[2], 3), np.uint8)
        cv2.drawContours(blank_mask, cnt[i], -1, (0, 255, 0), 1)
        print(cnt[i])
        cv2.imshow('test',blank_mask)
        cv2.waitKey(0)

如何一次在列表中打印一个元素,而不是继续前进?

天生の放荡 2025-02-17 17:54:03

static_url in settings.py这样:

STATIC_URL = 'static/'

并且模板文件必须像这样

{% load static %}

<link rel="stylesheet" type="text/css" href="{% static 'app/css/style.css' %}">

define STATIC_URL in settings.py like that:

STATIC_URL = 'static/'

and template file must be like that

{% load static %}

<link rel="stylesheet" type="text/css" href="{% static 'app/css/style.css' %}">

&quot“ get/static/css/stylesheet.css http/1.1” 404 1813

天生の放荡 2025-02-17 14:30:47

这与Azure Devops,Dictached Head,PR或您周围扔的任何其他术语无关。您正在做的事情是完全正常和正确的:您只想在特定的提交中启动一个新的分支。唯一的问题是您使用git“语言”:您的命令是向后的。

git branch -f origin/develop feature/temp

您的意思恰恰相反:

git branch feature/temp origin/develop

但是,由于您已经是 at Origin/开发,因此无论如何您都不需要指定它。只是说

git switch -c feature/temp 

This has nothing to do with azure devops, detached head, PR, or any of the other terms you tossed around. What you're doing is perfectly normal and correct: you just want to start a new branch at a particular commit. The only issue is your use of the Git "language": Your command is backwards.

git branch -f origin/develop feature/temp

What you mean is exactly the opposite:

git branch feature/temp origin/develop

But since you are already at origin/develop, you don't need to specify it anyway. Just say

git switch -c feature/temp 

在封闭的开发环境中独立的头部状态

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文