尐籹人

文章 评论 浏览 32

尐籹人 2025-02-10 13:36:44

您要确保使用分配操作员而不是比较操作员。

尝试 document.getElementById('res')。值= rab; 而不是。

You want to make sure you're using the assignment operator, instead of the comparison operator.

Try document.getElementById('res').value = rab; instead.

如何使用JavaScript使用在文本框上进行计算器进行输入值,并使用按钮执行和减去添加和减去

尐籹人 2025-02-10 09:42:57

目前尚不清楚显示的代码如何导致该错误。

这种代码应为“表驱动”,从而导致较少的代码和更多的可扩展性。

这样的事情:

from glob import glob
from os.path import join, isfile
from shutil import move
from pathlib import Path

BASE = 'C:\\Users\\CLEMENT.LAPORTE'
DEFAULT = 'Other'

CONTROL = {('gif', 'jfif', 'jpg', 'jpeg', 'png'): 'Pictures\\Pictures',
           ('mp4', 'mkv', 'avi'): 'Videos\\Videos',
           ('mp3', 'wav', 'm4a'): 'Music\\Songs',
           ('exe',): 'App',
           ('txt', 'docx', 'pptx', 'pdf'): 'Work',
           ('py', 'c', 'cpp', 'java', 'js', 'html', 'css'): 'Code'}


def moveFiles(path):
    for file in glob(join(path, '*.*'):
        suffix = Path(file).suffix[1:]
        for k, v in CONTROL.items():
            if suffix in k:
                p = v
                break
        else:
            p = DEFAULT
        try:
            move(file, join(BASE, p))
            print(f"Moved: {file} -> {p}")
        except Exception as e:
            print(f'Failed to move {file} -> {p} due to {e}')


path = input("Enter the path you want to sort: ")

moveFiles(path)

It's unclear how the code shown can result in that error.

This kind of code should be "table driven" which results in less code and more extensibility.

Something like this:

from glob import glob
from os.path import join, isfile
from shutil import move
from pathlib import Path

BASE = 'C:\\Users\\CLEMENT.LAPORTE'
DEFAULT = 'Other'

CONTROL = {('gif', 'jfif', 'jpg', 'jpeg', 'png'): 'Pictures\\Pictures',
           ('mp4', 'mkv', 'avi'): 'Videos\\Videos',
           ('mp3', 'wav', 'm4a'): 'Music\\Songs',
           ('exe',): 'App',
           ('txt', 'docx', 'pptx', 'pdf'): 'Work',
           ('py', 'c', 'cpp', 'java', 'js', 'html', 'css'): 'Code'}


def moveFiles(path):
    for file in glob(join(path, '*.*'):
        suffix = Path(file).suffix[1:]
        for k, v in CONTROL.items():
            if suffix in k:
                p = v
                break
        else:
            p = DEFAULT
        try:
            move(file, join(BASE, p))
            print(f"Moved: {file} -> {p}")
        except Exception as e:
            print(f'Failed to move {file} -> {p} due to {e}')


path = input("Enter the path you want to sort: ")

moveFiles(path)

有人可以告诉我为什么我的文件分子不起作用吗?

尐籹人 2025-02-10 03:50:28

好的,我编写的代码要简单得多。我将尝试解释:

html:

    <p id="txtInput">Speak this text</p> // change to paragraph element but keep the same ID
    <button id='btnSpeak'>Speak!</button>

javascript:

        var txtInput = document.querySelector('#txtInput');
        var btnSpeak = document.querySelector('#btnSpeak');
        var synth = window.speechSynthesis;
        var voices = [];

        PopulateVoices();
        if(speechSynthesis !== undefined){
            speechSynthesis.onvoiceschanged = PopulateVoices;
        }

        btnSpeak.addEventListener('click', ()=> {
            var toSpeak = new SpeechSynthesisUtterance(txtInput.textContent);
            toSpeak.voice = voices[7]; // Spanish
            synth.speak(toSpeak);
        });

        function PopulateVoices(){
            voices = synth.getVoices();
            voices.forEach((item, index) => console.log(item.name, index));
        }

要注意的主要内容,我将输入更改为段落元素,但将其分配给了相同的ID(这意味着ID和元素的名称不再真正有意义 txtinput < /代码>段落等,但这是学术的)。 DOM中只有一个ID应该存在,因此请确保您删除另一个元素,如果它是重复的,则可以更改元素的ID并像

<p id="foo">Text</a>

var elementID = document.querySelector('#foo');

以前的功能中更新 JS选择器一样更新JS选择器。输入文本的值使用:

var toSpeak = new SpeechSynthesisUtterance(txtInput.value);

由于段落元素没有值属性,因此我们将其更改为:

var toSpeak = new SpeechSynthesisUtterance(txtInput.textContent);

它将返回内部文本内容。

我从API中获得了一系列的声音,为了调试目的,我是控制所有语音名称和索引:

voices.forEach((item, index) => console.log(item.name, index));

例如:它返回:

Microsoft David - English (United States) 0
Microsoft Mark - English (United States) 1
Microsoft Zira - English (United States) 2
...

这显示了我的每个声音,因为现在我已经设置了索引7(这是GoogleEspañol)作为预设的声音。您将必须更新所需的声音索引:

toSpeak.voice = voices[7]; // Spanish

我希望这是有道理的,现在代码将ES5样式语法(及较旧的)与更现代的版本混合在一起,这不是我的喜好,但这应该按预期工作。

还有一个 jsfiddle 您可以尝试实验

OK, the code I have written is much simpler. I will try to explain:

HTML:

    <p id="txtInput">Speak this text</p> // change to paragraph element but keep the same ID
    <button id='btnSpeak'>Speak!</button>

JavaScript:

        var txtInput = document.querySelector('#txtInput');
        var btnSpeak = document.querySelector('#btnSpeak');
        var synth = window.speechSynthesis;
        var voices = [];

        PopulateVoices();
        if(speechSynthesis !== undefined){
            speechSynthesis.onvoiceschanged = PopulateVoices;
        }

        btnSpeak.addEventListener('click', ()=> {
            var toSpeak = new SpeechSynthesisUtterance(txtInput.textContent);
            toSpeak.voice = voices[7]; // Spanish
            synth.speak(toSpeak);
        });

        function PopulateVoices(){
            voices = synth.getVoices();
            voices.forEach((item, index) => console.log(item.name, index));
        }

Main things to note, I changed the input to a paragraph element but assigned it the same ID (this means that the name of the ID and element no longer really make sense txtInput for a paragraph etc, but that is academic). Only one ID should exist in the DOM at any one time, so make sure you remove the other element if it is a duplicate or you can change the ID of the element and update the js selector like so

<p id="foo">Text</a>

var elementID = document.querySelector('#foo');

In the previous function you are getting the value of the input text using:

var toSpeak = new SpeechSynthesisUtterance(txtInput.value);

Because the paragraph element does not have a value attribute we change this to:

var toSpeak = new SpeechSynthesisUtterance(txtInput.textContent);

Which will return the inner text content.

I get the array of voices from the API, and for debugging purposes I am console logging all the the voice names and indices:

voices.forEach((item, index) => console.log(item.name, index));

Which returns for example:

Microsoft David - English (United States) 0
Microsoft Mark - English (United States) 1
Microsoft Zira - English (United States) 2
...

This shows me each voice in the console, for now I have set index 7 (which is Google español) as the preset voice. You will have to update the index for the voice that you want in:

toSpeak.voice = voices[7]; // Spanish

I hope this makes sense, the code is now mixing ES5 style syntax (and older) with more modern versions, which is not my preference, but this should work as expected.

There is also a jsfiddle you can experiment with

与JavaScript演讲的文字?

尐籹人 2025-02-09 16:38:31

您需要将逻辑移到应用外。当它说时,请确保将组件包裹在A&lt; Provider&gt; 中,这意味着您使用的 useselector In的组件需要在&lt下;提供者&gt; 在这种情况下意味着app.js。

因此,app.js仅包含

export default function App() {
  return (
    <Provider store={store}>
      <NewComponent .../>
    </Provider>
  );
}

,newcomponent.js应包含其余逻辑。

You need to move your logic outside of App. When it says please ensure the component is wrapped in a <Provider> it means that the component you are using the useSelector in, needs to be under <Provider> which in this case means App.js.

So App.js should contain only

export default function App() {
  return (
    <Provider store={store}>
      <NewComponent .../>
    </Provider>
  );
}

And NewComponent.js should contain rest of the logic.

当使用useselector()时,找不到react-redux上下文值

尐籹人 2025-02-08 16:42:06

按课堂选择效果很好:

soup.find('div',attrs={'class':'List-results-items'})

soup.find_all('div',attrs={'class':'List-results-items'})
示例
from bs4 import BeautifulSoup
soup='''
<div _ngcontent-ijy-c117 class="List-results-items">some text</div>'''

soup=BeautifulSoup(soup)

soup.find('div',attrs={'class':'List-results-items'})
输出
<div _ngcontent-ijy-c117="" class="List-results-items">some text</div>

以防万一您必须迭代 Resultset 以获取每篇文章。示例 - &gt;

from bs4 import BeautifulSoup
soup='''
<div _ngcontent-ijy-c117 class="List-results-items">
    <a>Article One<a/>
    <a>Article Two<a/>
    <a>Article Three<a/>
</div>'''

soup=BeautifulSoup(soup)

for e in soup.find('div',attrs={'class':'List-results-items'}).find_all('a'):
    print(e.text)

Selecting by class works well:

soup.find('div',attrs={'class':'List-results-items'})

or

soup.find_all('div',attrs={'class':'List-results-items'})
Example
from bs4 import BeautifulSoup
soup='''
<div _ngcontent-ijy-c117 class="List-results-items">some text</div>'''

soup=BeautifulSoup(soup)

soup.find('div',attrs={'class':'List-results-items'})
Output
<div _ngcontent-ijy-c117="" class="List-results-items">some text</div>

Just in case it looks like you have to iterate your ResultSet to get each of your articles. Example->

from bs4 import BeautifulSoup
soup='''
<div _ngcontent-ijy-c117 class="List-results-items">
    <a>Article One<a/>
    <a>Article Two<a/>
    <a>Article Three<a/>
</div>'''

soup=BeautifulSoup(soup)

for e in soup.find('div',attrs={'class':'List-results-items'}).find_all('a'):
    print(e.text)

如果“ div name”,我该如何刮擦数据。像这样的“ _ngcontent-jiy-c118”

尐籹人 2025-02-08 12:55:29

更改代码,您需要添加项目的 countarray (如果项目为数组)项目本身(如果不是数组)总和。

const array = [1, [2, [3,4]], [5,6], 7];

var countArray = function(array) {
  let sum = 0
  for (let i = 0; i < array.length; i++) {
    if (Array.isArray(array[i])) {
      sum = sum + countArray(array[i])
    } else {
      sum = sum + array[i]
    }
  }
  return sum
}

console.log(countArray(array));

Changing as little as possible about your code, you need add either the countArray of the item (if the item is an array) or the item itself (if it's not an array) to the sum.

const array = [1, [2, [3,4]], [5,6], 7];

var countArray = function(array) {
  let sum = 0
  for (let i = 0; i < array.length; i++) {
    if (Array.isArray(array[i])) {
      sum = sum + countArray(array[i])
    } else {
      sum = sum + array[i]
    }
  }
  return sum
}

console.log(countArray(array));

在JavaScript中计数数组值

尐籹人 2025-02-08 03:57:20

async 是“病毒”,因为如果您调用 async 方法,您的调用代码也必须是 async ,并且必须等待您正在调用的方法的结果。因此,一个 async 使用倾向于强制许多其他因代码也为 async ,这又可能导致其他代码为 async ,它可以侵扰整个代码基础。

它在表单的按钮点击事件中起作用,因为Visual Studio足够聪明,可以看到事件处理程序方法为 async ,并在提出事件时适当地将其称为。

Async is "viral", in that if you call an Async method your calling code must also be Async, and it must Await the result of the method you are calling. Thus one Async use tends to force a lot of other dependant code to also be Async, which in turn can cause other code to be Async, and it can infest an entire code base.

It works in the Form's button click event because Visual Studio is smart enough to see the event handler method is Async and call it appropriately when the event is raised.

为什么RESTSHAR调用在VB.NET表单代码模块中工作,而在VB.NET类模块中不使用相同代码

尐籹人 2025-02-07 19:24:30

您需要声明函数历史记录()和列表,

last_calculation = []

def history():
  global last_calculation
  if last_calculation == []:
    print("No past calculations to show")
  else:
    for i in last_calculation:
        print(*i)  #for single line

然后在if循环中添加以下代码到操作的末尾,

last_calculation.append(result)

然后触发histort()函数,使用“继续”以在呼叫历史记录之后进行操作()

if choice=='?':
    history()
    continue

You need to declare function history() and list,

last_calculation = []

def history():
  global last_calculation
  if last_calculation == []:
    print("No past calculations to show")
  else:
    for i in last_calculation:
        print(*i)  #for single line

Then in the if loop add below code to end of the operations,

last_calculation.append(result)

Then trigger history() function, use 'continue' to make operation after the call history()

if choice=='?':
    history()
    continue

保存和显示Python计算器的计算历史记录

尐籹人 2025-02-07 19:06:23

我正在使用的最后一个工作。此外,似乎更简单,更完整

https://mongoplayground.net/pp/p/ku2clkxcpm0

db.collection.aggregate([
  {
    $match: {
      userId: {
        $in: [
          "6288ceea279219e36338b5bc"
        ]
      }
    }
  },
  {
    $sort: {
      _id: -1
    }
  },
  {
    $group: {
      _id: {
        userId: "$userId"
      },
      docs: {
        $first: "$ROOT"
      }
    }
  },
  {
    $project: {
      _id: 0
    }
  },
  {
    $replaceRoot: {
      newRoot: "$docs"
    }
  }
])

Final one that i am using that works.Also seems simpler and more complete

https://mongoplayground.net/p/ku2ClKXCpm0

db.collection.aggregate([
  {
    $match: {
      userId: {
        $in: [
          "6288ceea279219e36338b5bc"
        ]
      }
    }
  },
  {
    $sort: {
      _id: -1
    }
  },
  {
    $group: {
      _id: {
        userId: "$userId"
      },
      docs: {
        $first: "$ROOT"
      }
    }
  },
  {
    $project: {
      _id: 0
    }
  },
  {
    $replaceRoot: {
      newRoot: "$docs"
    }
  }
])

MongoDB:通过用户ID的最后插入行汇总

尐籹人 2025-02-07 18:07:07

我认为您不需要精确确定相机1的坐标中心1

使用相机1在任何任意点获得相机2的坐标。在已知距离上线性移动摄像头,然后再次获得坐标。有两个坐标后,您可以在以下文档中的第2.9节中使用坐标转换矩阵

I don't think you need to precisely determine center of coordinate system of camera 1

Use camera 1 to get the coordinates for camera 2 at any arbitrary point. Move the camera linearly over a known distance and get the coordinates again. Once you have two coordinates you can use coordinate transformation matrix in section 2.9 in the following document

http://motion.cs.illinois.edu/RoboticSystems/CoordinateTransformations.html

如何在Python的立体声相机设置中找到相机位置?

尐籹人 2025-02-07 17:40:28

当我最初编写此情况时,我不会添加参数,例如:

@allure.story("测试test_b")
def test_b(self):
    """
    description of test_b
    """
    logging.info("我是test_b的logging")
    assert 1 in [0, 1]

运行它。
Allure Report从“ Allure-results”文件夹中读取测试结果数据,其中没有参数测试结果的test_b被保留,而未被新测试替换。这就是test_b在报告中的位置。
我可以删除两个“诱人的重学”和“ Allure-Report”文件夹来清洁测试结果数据。这样,将不会显示原始的“ test_b”。

When I originally write this case, I don't add the parameters, like:

@allure.story("测试test_b")
def test_b(self):
    """
    description of test_b
    """
    logging.info("我是test_b的logging")
    assert 1 in [0, 1]

and run it.
allure report read the test result data from 'allure-results' folder, where the test_b without parameter test result is kept and not replaced by new test. That's where the test_b from in report.
I can delete both 'allure-results' and 'allure-report' folders to clean the test result data. By this way, original 'test_b' will not be shown.

pytest参数化运行一个比我设置参数组多的测试

尐籹人 2025-02-07 08:26:53

要提取 entityID ,请:

print(resp2['entityId'])

提取 dentedname ,做:

print(resp2['properties']['detectedName'])

To extract entityId, do:

print(resp2['entityId'])

To extract detectedName, do:

print(resp2['properties']['detectedName'])

使用Python从JSON文件中提取数据

尐籹人 2025-02-07 05:03:58

对于 sql-server ,请尝试以下操作:

-- mockup data
declare @Raw table (
    id nvarchar(max),
    group_id nvarchar(max),
    user_id nvarchar(max)
                   )

insert into @Raw values ('p001', 'aaa', 'ava001'), ('p002', 'aaa', 'ava001'), ('p003', 'bbb', 'ava001'), ('p004', 'bbb', 'ava001');

-- check this query
with A as (
    select id, ROW_NUMBER() over(partition by group_id, user_id order by id) as RN 
from @Raw)
delete from @Raw where id in (select id from A where A.RN > 1)

-- verify table
select * from @Raw

In case of sql-server, try this:

-- mockup data
declare @Raw table (
    id nvarchar(max),
    group_id nvarchar(max),
    user_id nvarchar(max)
                   )

insert into @Raw values ('p001', 'aaa', 'ava001'), ('p002', 'aaa', 'ava001'), ('p003', 'bbb', 'ava001'), ('p004', 'bbb', 'ava001');

-- check this query
with A as (
    select id, ROW_NUMBER() over(partition by group_id, user_id order by id) as RN 
from @Raw)
delete from @Raw where id in (select id from A where A.RN > 1)

-- verify table
select * from @Raw

如何查询从表中删除相同的数据?

尐籹人 2025-02-07 03:28:11

我在gnu手册(扩展 - ass)中发现“ h” in'%h1'表示'the''sud'添加8个字节到一个倒数记忆参考'。

该模板修饰符是x86仅有的。它不适用于手臂。

不幸的是,不幸的是,手臂的模板修饰符未记录在GCC手册中(虽然它们适用于aarch64 ),但它们是在 armclang手册和GCC符合这些定义,据我所知。因此, h 模板修饰符的正确含义是:

操作数必须使用R约束,并且必须是64位整数或浮点类型。该操作数被打印为最高的寄存器,持有该值的一半。

现在这是有道理的。操作数1到Inline ASM是 oldVal ,该是无符号的长长,64位,因此编译器将为其分配两个连续的32位通用寄存器。假设它们是 r4 r5 ,如此编译的输出。然后,%1 将展开 R4 %H1 将扩展到 R5 ,这正是<代码> ldrexd 指令需求。同样,%4,%h4 扩展到 r2,r3 %5,%h5 扩展到 fp,ip ,替代名称 r11,r12 。

Frant的答案解释了应该做什么比较交换。 (拼写 cmpxchg 可能来自X86比较交换指令的助记符。)如果您现在阅读了代码,则应该看到它确实可以做到这一点。 teq; teqeq; ldrexd 和 strexd 之间的bne 如果 *ptr 不平等,则将中止商店。和 teq; strexd 之后的bne ,如果独家商店失败,则会导致重试,如果有中间访问*ptr (通过另一个核心,中断处理程序, ETC)。这就是确保原子性的方式。

I find in gnu manual(extend extended-asm) that 'H' in '%H1' means 'Add 8 bytes to an offsettable memory reference'.

That table of template modifiers is for x86 only. It is not applicable to ARM.

The template modifiers for ARM are unfortunately not documented in the GCC manual (though they are for AArch64), but they are defined in the armclang manual and GCC conforms to those definitions as far as I can tell. So the correct meaning of the H template modifier here is:

The operand must use the r constraint, and must be a 64-bit integer or floating-point type. The operand is printed as the highest-numbered register holding half of the value.

Now this makes sense. Operand 1 to the inline asm is oldval which is of type unsigned long long, 64 bits, so the compiler will allocate two consecutive 32-bit general purpose registers for it. Let's say they are r4 and r5 as in this compiled output. Then %1 will expand to r4, and %H1 will expand to r5, which is exactly what the ldrexd instruction needs. Likewise, %4, %H4 expanded to r2, r3, and %5, %H5 expanded to fp, ip, which are alternative names for r11, r12.

The answer by frant explains what a compare-exchange is supposed to do. (The spelling cmpxchg might come from the mnemonic for the x86 compare-exchange instruction.) And if you read through the code now, you should see that it does exactly that. The teq; teqeq; bne between ldrexd and strexd will abort the store if old and *ptr were unequal. And the teq; bne after strexd will cause a retry if the exclusive store failed, which happens if there was an intervening access to *ptr (by another core, interrupt handler, etc). That is how atomicity is ensured.

此比较交换函数中的内线组件如何起作用? (手臂上%H修饰符)

尐籹人 2025-02-06 12:16:05

您正在尝试在这里做两件事。

  1. 找到每个卖家的总销售额。
  2. 对每个卖家的总销售额进行排序。

在我的排序功能内部,您可以看到我正在卖方过滤所有销售。

一旦我只有一个卖家的销售,我就会使用“简化方法”将其销售量汇总到易于使用的数字中。

然后,我将以前的卖家数量与当前卖方数量进行比较,以使用排序方法重新排序它们。

我鼓励您阅读所使用方法的文档,以便您了解每个步骤正在发生的事情。

使用的方法:
sort
filter
减少

const sellers = [{
  id: 1,
  name: 'juan',
  age: 23
}, {
  id: 2,
  name: 'adrian',
  age: 32
}, {
  id: 3,
  name: 'apolo',
  age: 45
}];

const sales = [{
  equipo: 'frances',
  sellerId: 2,
  quantity: 234
}, {
  equipo: 'italiano',
  sellerId: 3,
  quantity: 24
}, {
  equipo: 'polaco',
  sellerId: 1,
  quantity: 534
}, {
  equipo: 'frances',
  sellerId: 2,
  quantity: 1234
}, {
  equipo: 'frances',
  sellerId: 3,
  quantity: 2342
}];

const expected = [{
  id: 3,
  name: 'apolo',
  age: 45
}, {
  id: 2,
  name: 'adrian',
  age: 32
}, {
  id: 1,
  name: 'juan',
  age: 23
}]

const result = sellers.sort((a, b) => {
  totalA = sales.filter(sale => sale.sellerId === a.id).reduce((acc, val) => acc + val.quantity, 0)
  totalB = sales.filter(sale => sale.sellerId === b.id).reduce((acc, val) => acc + val.quantity, 0)
  return totalB - totalA
})

// Check we get what we expect
console.log(JSON.stringify(expected) === JSON.stringify(result))

You're trying to do two things here.

  1. Find the total sales for each seller.
  2. Sort the total sales for each seller.

Inside my sort function you can see I am filtering all of the sales by the seller.

Once I have just the sales for one seller I use the reduce method to sum the quantity of their sales into an easy to use number.

Then I'm comparing the previous sellers quantity to the current sellers quantity to re-order them using the sort method.

I encourage you to read the documentation of the methods used so you understand what is happening at each step.

Methods used:
Sort
Filter
Reduce

const sellers = [{
  id: 1,
  name: 'juan',
  age: 23
}, {
  id: 2,
  name: 'adrian',
  age: 32
}, {
  id: 3,
  name: 'apolo',
  age: 45
}];

const sales = [{
  equipo: 'frances',
  sellerId: 2,
  quantity: 234
}, {
  equipo: 'italiano',
  sellerId: 3,
  quantity: 24
}, {
  equipo: 'polaco',
  sellerId: 1,
  quantity: 534
}, {
  equipo: 'frances',
  sellerId: 2,
  quantity: 1234
}, {
  equipo: 'frances',
  sellerId: 3,
  quantity: 2342
}];

const expected = [{
  id: 3,
  name: 'apolo',
  age: 45
}, {
  id: 2,
  name: 'adrian',
  age: 32
}, {
  id: 1,
  name: 'juan',
  age: 23
}]

const result = sellers.sort((a, b) => {
  totalA = sales.filter(sale => sale.sellerId === a.id).reduce((acc, val) => acc + val.quantity, 0)
  totalB = sales.filter(sale => sale.sellerId === b.id).reduce((acc, val) => acc + val.quantity, 0)
  return totalB - totalA
})

// Check we get what we expect
console.log(JSON.stringify(expected) === JSON.stringify(result))

如何根据其属性的总和组织一系列对象?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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