生生不灭

文章 评论 浏览 31

生生不灭 2025-01-31 18:34:07

对于用例,您建议您可能要看数据类这使您可以避免大量的锅炉板。它还允许您使用简单的冷冻参数使其仅阅读。您可以将所有属性存储在类的数据类中。

from dataclasses import dataclass

@dataclass(frozen = True)
class MyPropertyContainer():
    property1: str
    property2: float
    # ...

这样的类将允许您将所有读取属性存储在易于访问的单个对象中。唯一的不足之处是您需要通过从类外部的附加点访问这些属性: my_object.my_properties.property1 ,或者可以为每个属性编写属性评估者(如果您想避免)(如果要避免)(我不建议)。

之后,您可以将所有论点视为一个命令。如果需要,可以从中提取列表。只要您定义了上面的数据类,则如下:

my_properties = MyPropertyContainer('aString', 12, ...)  # Instantiate what you want
properties_dict = my_properties.asDict()          # Get the dictionnary
properties_list = list(properties_dict.values())  # Dict to list

基于您提供的示例,解决方案是将类重写如下:


# Make a data class for private properties
@dataclass(frozen = True)
class PropertyContainer():
    func1: str
    func2: str

class A():
    
    # Since we're readonly we set the values on instanciation
    def __init__(self, func1_val, func2_val):
        self.properties = PropertyContainer(func1_val, func2_val)

    # Here we get the values from all readonly
    def func3(self):
         return list(self.properties.asDict().values())

    # You could also have sth like this for retro compatibility
    @property
    def func2(self):
        return self.properties.func1

For the use case you propose you might want to take a look at data classes which allow you to avoid a lot of boiler plate. It also allows you to make it read-only with a simple frozen argument. You could store all of your properties in a data class inside your class.

from dataclasses import dataclass

@dataclass(frozen = True)
class MyPropertyContainer():
    property1: str
    property2: float
    # ...

Such a class would allow you to store all your read only properties in a single object which is easily accessible. The only down side is that you would need to access those properties through an additional dot from outside the class: my_object.my_properties.property1 or you could write properties assessors for each properties if you want to avoid that (which I do not recommend).

Afterwards, you can get all your arguments as a dict. If you need to you can extract a list from that. Provided you defined the data class above, it would look as follow:

my_properties = MyPropertyContainer('aString', 12, ...)  # Instantiate what you want
properties_dict = my_properties.asDict()          # Get the dictionnary
properties_list = list(properties_dict.values())  # Dict to list

Based on the example you provided, a solution would be to rewrite your class as follow:


# Make a data class for private properties
@dataclass(frozen = True)
class PropertyContainer():
    func1: str
    func2: str

class A():
    
    # Since we're readonly we set the values on instanciation
    def __init__(self, func1_val, func2_val):
        self.properties = PropertyContainer(func1_val, func2_val)

    # Here we get the values from all readonly
    def func3(self):
         return list(self.properties.asDict().values())

    # You could also have sth like this for retro compatibility
    @property
    def func2(self):
        return self.properties.func1

大多数将班级所有可读性属性存储在列表中的Pythonic方法

生生不灭 2025-01-31 15:07:20

尝试:

=REGEXREPLACE(A1, "(?i)[a-z \.]", )


更新:

=REGEXREPLACE(A1, "[[:print:]¿àáâãäåæçèéêëìíîïðñòóôõö×øùúûüýþßÿāăąćĉċčďđēĕėęěĝğġģĥħĩīĭįi̇ıijĵķĸĺļľŀłńņňʼnŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷźżžſƀɓƃƅɔƈɖɗƌƍǝəɛƒɠɣƕɩɨƙƚƛɯɲƞɵơƣƥʀƨʃƪƫƭʈưʊʋƴƶʒƹƺƻƽƾƿdžljnjǎǐǒǔǖǘǚǜǟǡǣǥǧǩǫǭǯǰ]", )

try:

=REGEXREPLACE(A1, "(?i)[a-z \.]", )

enter image description here


update:

=REGEXREPLACE(A1, "[[:print:]¿àáâãäåæçèéêëìíîïðñòóôõö×øùúûüýþßÿāăąćĉċčďđēĕėęěĝğġģĥħĩīĭįi̇ıijĵķĸĺļľŀłńņňʼnŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷźżžſƀɓƃƅɔƈɖɗƌƍǝəɛƒɠɣƕɩɨƙƚƛɯɲƞɵơƣƥʀƨʃƪƫƭʈưʊʋƴƶʒƹƺƻƽƾƿdžljnjǎǐǒǔǖǘǚǜǟǡǣǥǧǩǫǭǯǰ]", )

从Google表中的字符串中提取所有表情符号

生生不灭 2025-01-31 12:41:57

python 3.7文档

我还想突出显示以下引用 python 螺纹文档

cpython实现详细信息:在CPYTHON中,由于全局解释器锁定,只有一个线程可以一次执行Python代码(即使某些面向性能的库可能会克服此限制)。如果您的应用程序可以更好地利用多核机的计算资源,建议您使用多处理 concurrent.futures.futures.processpoolexecutor 。但是,如果您想同时运行多个I/O结合任务,则线程仍然是合适的模型。

这链接到 Globsary for gromsy> code> global interage> gode>全局解释器锁定/code> 解释说GIL意味着Python中的螺纹并行性不适合 CPU绑定任务

CPYTHON解释器使用的机制确保仅一个线程一次执行Python字节码。通过使对象模型(包括关键的内置类型(例如DICE))隐含地安全防止并发访问来简化CPYTHON实现。锁定整个解释器使解释器更容易被多线程,而牺牲了多处理器机器提供的许多并行性。

然而,某些扩展模块(标准或第三方都可以)设计为在执行计算密集型任务(例如压缩或哈希)时释放GIL。另外,GIL在执行I/O。

时总是会释放

过去为创建“自由线程”的解释器(将数据锁定在更细的粒度上)的努力并没有成功,因为在常见的单处理器案例中性能受到了影响。人们认为,克服这个绩效问题将使实施更加复杂,因此维护更为昂贵。

该报价还意味着dicts,因此可变分配也可以安全地作为CPYTHON实现细节:

多处理解释如何通过产卵过程来克服GIL,同时公开类似于螺纹的接口:

多处理是一个软件包,该软件包使用类似于螺纹模块的API支持产卵过程。多处理软件包提供本地和远程并发性,通过使用子过程而不是线程有效地侧向全局解释器锁定。因此,多处理模块允许程序员完全利用给定计算机上的多个处理器。它在Unix和Windows上都运行。

说明它使用多处理作为后端:

ProcessPoolExecutor类是一个执行人子类,它使用流程库来异步执行呼叫。 ProcessPoolExecutor使用多处理模块,该模块允许其侧键入全局解释器锁定,但也意味着只能执行并返回可挑选对象。

应与其他基类 threadpoolexecutor 形成鲜明对比,使用线程代替过程

threadpoolexecutor是一个执行程序子类,使用线程池异步执行呼叫。

从中,我们得出结论, threadpoolexecutor 仅适用于I/O绑定的任务,而 ProcessPoolExecutor 也可以处理CPU绑定的任务。

处理与线程实验

我已经对Python中的过程与线程进行了实验分析。

结果快速预览:

”在此处输入图像描述”

在其他语言中

该概念似乎也存在于Python之外,也将其应用于Ruby: https://en.wikipedia.org/wiki/wiki/global_inter_inter_interpreter_lock_lock

它提到了预期:

  • 提高了单程读取程序的速度(提高了单程读取的程序的速度(增加速度)无需分别在所有数据结构上获取或释放锁),
  • 简单地集成通常不是线程安全的C库,
  • 易于实现(拥有一个GIL比无锁的解释器或使用Fine Fine更容易实现 - 锁锁)。

但是JVM似乎没有GIL就可以了,所以我想知道这是否值得。以下问题询问为什么吉尔首先存在:为什么全局解释器锁?

Python 3.7 documentation

I would also like to highlight the following quote from the Python threading documentation:

CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use multiprocessing or concurrent.futures.ProcessPoolExecutor. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously.

This links to the Glossary entry for global interpreter lock which explains that the GIL implies that threaded parallelism in Python is unsuitable for CPU bound tasks:

The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at a time. This simplifies the CPython implementation by making the object model (including critical built-in types such as dict) implicitly safe against concurrent access. Locking the entire interpreter makes it easier for the interpreter to be multi-threaded, at the expense of much of the parallelism afforded by multi-processor machines.

However, some extension modules, either standard or third-party, are designed so as to release the GIL when doing computationally-intensive tasks such as compression or hashing. Also, the GIL is always released when doing I/O.

Past efforts to create a “free-threaded” interpreter (one which locks shared data at a much finer granularity) have not been successful because performance suffered in the common single-processor case. It is believed that overcoming this performance issue would make the implementation much more complicated and therefore costlier to maintain.

This quote also implies that dicts and thus variable assignment are also thread safe as a CPython implementation detail:

Next, the docs for the multiprocessing package explain how it overcomes the GIL by spawning process while exposing an interface similar to that of threading:

multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows.

And the docs for concurrent.futures.ProcessPoolExecutor explain that it uses multiprocessing as a backend:

The ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously. ProcessPoolExecutor uses the multiprocessing module, which allows it to side-step the Global Interpreter Lock but also means that only picklable objects can be executed and returned.

which should be contrasted to the other base class ThreadPoolExecutor that uses threads instead of processes

ThreadPoolExecutor is an Executor subclass that uses a pool of threads to execute calls asynchronously.

from which we conclude that ThreadPoolExecutor is only suitable for I/O bound tasks, while ProcessPoolExecutor can also handle CPU bound tasks.

Process vs thread experiments

At Multiprocessing vs Threading Python I've done an experimental analysis of process vs threads in Python.

Quick preview of the results:

enter image description here

In other languages

The concept seems to exist outside of Python as well, applying just as well to Ruby for example: https://en.wikipedia.org/wiki/Global_interpreter_lock

It mentions the advantages:

  • increased speed of single-threaded programs (no necessity to acquire or release locks on all data structures separately),
  • easy integration of C libraries that usually are not thread-safe,
  • ease of implementation (having a single GIL is much simpler to implement than a lock-free interpreter or one using fine-grained locks).

but the JVM seems to do just fine without the GIL, so I wonder if it is worth it. The following question asks why the GIL exists in the first place: Why the Global Interpreter Lock?

Cpython中的全球口译员锁(GIL)是什么?

生生不灭 2025-01-31 06:24:52

您必须在按钮中获取密码输入值,请单击“侦听器”功能。

function verifyPassword(){
    var pw1 = document.getElementById("password1");
    var pw2 = document.getElementById("password2");

    // Get the modal
    var modal = document.getElementById("myModal");

    // Get the button that opens the modal
    var btn1 = document.getElementById("myBtn");
    
    var confirm = document.getElementById("confirm");
    
    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];


    btn1.onclick = function () {
        
        modal.style.display = "block";

        //check empty password field

        if(pw1.value == "") {
            document.getElementById("message1").innerHTML = "*Please put your new password!";
            return false;
        }

        //minimum password length validation
        if(pw1.value.length < 8) {
            document.getElementById("message1").innerHTML = "**Password length must be atleast 8 characters";
            return false;
        }

        //maximum length of password validation
        if(pw1.value.length > 15) {
           document.getElementById("message1").innerHTML = "*Password length must not exceed 15 characters";
           return false;
        } else {
           if(pw1.value == pw2.value){
               document.getElementById("message1").innerHTML=  "Passwords match!";
           }
        
           else {
               document.getElementById("message1").innerHTML=  "Passwords not match!";
           }
        }

    }
    
    confirm.onclick = function () {
        modal.style.display = "none";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        modal.style.display = "none";
      }
  
      // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
          modal.style.display = "none";
    }
    }
} 

you have to fetch the password input value in the button click listener function.

function verifyPassword(){
    var pw1 = document.getElementById("password1");
    var pw2 = document.getElementById("password2");

    // Get the modal
    var modal = document.getElementById("myModal");

    // Get the button that opens the modal
    var btn1 = document.getElementById("myBtn");
    
    var confirm = document.getElementById("confirm");
    
    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];


    btn1.onclick = function () {
        
        modal.style.display = "block";

        //check empty password field

        if(pw1.value == "") {
            document.getElementById("message1").innerHTML = "*Please put your new password!";
            return false;
        }

        //minimum password length validation
        if(pw1.value.length < 8) {
            document.getElementById("message1").innerHTML = "**Password length must be atleast 8 characters";
            return false;
        }

        //maximum length of password validation
        if(pw1.value.length > 15) {
           document.getElementById("message1").innerHTML = "*Password length must not exceed 15 characters";
           return false;
        } else {
           if(pw1.value == pw2.value){
               document.getElementById("message1").innerHTML=  "Passwords match!";
           }
        
           else {
               document.getElementById("message1").innerHTML=  "Passwords not match!";
           }
        }

    }
    
    confirm.onclick = function () {
        modal.style.display = "none";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        modal.style.display = "none";
      }
  
      // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
          modal.style.display = "none";
    }
    }
} 

密码验证模式JavaScript

生生不灭 2025-01-31 05:18:41

因此,在这种情况下,只要AccountIds是一个数组,它就可以添加其他任何内容。

解决方案

.findAll({
  where: {
    accountId: accountIds
  }
})

So in this case as long as accountIds is an array then it will work no need to add anything else.

Solution

.findAll({
  where: {
    accountId: accountIds
  }
})

NPM续集,其中:[列表]

生生不灭 2025-01-30 20:09:59

您是在更改事件上设置固定值 10 ,要拥有一个动态值,您可以从 event 对象读取该值,该值将传递给事件侦听器从> event.target.value

id1.oninput = e => id2.value = e.target.value;
id3.oninput = e =>
id1.value = id2.value = e.target.value
<input type="range" name="n1" id="id1" value="5" step="2" min="1" max="100" />
</br>
<input type="range" name="n2" id="id2" value="2" step="2" min="1" max="100" />
<input type="number" name="n3" id="id3" />

You are setting a fixed value 10 on change event, to have a dynamic value you can read the value from the event object that is passed to event listener callback from event.target.value:

id1.oninput = e => id2.value = e.target.value;
id3.oninput = e =>
id1.value = id2.value = e.target.value
<input type="range" name="n1" id="id1" value="5" step="2" min="1" max="100" />
</br>
<input type="range" name="n2" id="id2" value="2" step="2" min="1" max="100" />
<input type="number" name="n3" id="id3" />

HTML范围仅使用JavaScript更新一次

生生不灭 2025-01-29 20:10:32

iiuc,您可以将false替换为na(在此处假设布尔值false,因为字符串使用“ false”),然后 stack 删除该值并使用 groupby.agg 汇总在转换为字典之前的列表:

dic = (df
 .set_index('image')
 .replace({False: pd.NA})
 .stack()
 .reset_index(1)
 .groupby(level='image', sort=False)['level_1'].agg(list)
 .to_dict()
)

输出:

{'039.png': ['finding1'],
 '006.png': ['finding1', 'finding2'],
 '012.png': ['nofinding']}

IIUC, you could replace the False to NA (assuming boolean False here, for strings use 'false'), then stack to remove the values and use groupby.agg to aggregate as list before converting to dictionary:

dic = (df
 .set_index('image')
 .replace({False: pd.NA})
 .stack()
 .reset_index(1)
 .groupby(level='image', sort=False)['level_1'].agg(list)
 .to_dict()
)

output:

{'039.png': ['finding1'],
 '006.png': ['finding1', 'finding2'],
 '012.png': ['nofinding']}

将带有true/false的大熊猫数据框转换为词典

生生不灭 2025-01-29 17:29:33

sed“ s/\” \'// g“ 的问题是,您正在尝试匹配”,然后是'。您应该将它们放在括号表达式中,或匹配任何引号。

假设这是您的输入:

user_download_dir_folder="abc\"1'23'foo\"bla"

echo "$user_download_dir_folder"

abc"1'23'foo"bla

您可以使用 sed 作为:

sed "s/[\"']//g" <<< "$user_download_dir_folder"

abc123foobla

或在bash中:

echo "${user_download_dir_folder//[\'\"]/}"

abc123foobla

Problem with sed "s/\"\'//g" is that you're trying to match a " followed by a '. You should put them in bracket expression or match either of the quotes.

Let's say this is your input:

user_download_dir_folder="abc\"1'23'foo\"bla"

echo "$user_download_dir_folder"

abc"1'23'foo"bla

You may use sed as this:

sed "s/[\"']//g" <<< "$user_download_dir_folder"

abc123foobla

Or in bash:

echo "${user_download_dir_folder//[\'\"]/}"

abc123foobla

如何替换所有报价&#x27; &quot在狂欢中

生生不灭 2025-01-29 04:59:57

考虑下面的方法,

execute immediate ( select '''
select * except(id) from (
  select to_json_string(A) id, * except(A)
  from your_table, unnest(A) value with offset
)
pivot (any_value(value) index for offset in (''' 
|| (select string_agg('' || val order by offset) from unnest(generate_array(0,999)) val with offset) || '))'
)    

如果适用于下面的虚拟数据(使用10个而不是1000个元素)

select [10,11,12,13,14,15,16,17,18,19] as A union all
select [20,21,22,23,24,25,26,27,28,29] as A union all
select [30,31,32,33,34,35,36,37,38,39] as A        

输出为

“在此处输入图像说明”

Consider below approach

execute immediate ( select '''
select * except(id) from (
  select to_json_string(A) id, * except(A)
  from your_table, unnest(A) value with offset
)
pivot (any_value(value) index for offset in (''' 
|| (select string_agg('' || val order by offset) from unnest(generate_array(0,999)) val with offset) || '))'
)    

If to apply to dummy data like below (with 10 instead of 1000 elements)

select [10,11,12,13,14,15,16,17,18,19] as A union all
select [20,21,22,23,24,25,26,27,28,29] as A union all
select [30,31,32,33,34,35,36,37,38,39] as A        

the output is

enter image description here

BigQuery SQL:将数组转换为列

生生不灭 2025-01-29 02:40:33

您可以使用列表理解:

import numpy as np
R=np.array([[1.05567452e+11, 1.51583103e+11, 5.66466172e+08],
       [6.94076420e+09, 1.96129124e+10, 1.11642674e+09],
       [1.88618492e+10, 1.73640817e+10, 4.84980874e+09]])

Remove = [(0, 1),(0,2)] 
b = [[j for i, j in enumerate(m) if (k, i) not in Remove] for k, m in enumerate(R)]
R1 = np.array([i for j in b for i in j]) #Flatten the resulting list

print(R1)

输出来执行此操作

array([1.05567452e+11, 6.94076420e+09, 1.96129124e+10, 1.11642674e+09,
       1.88618492e+10, 1.73640817e+10, 4.84980874e+09])

You can do this with list comprehension:

import numpy as np
R=np.array([[1.05567452e+11, 1.51583103e+11, 5.66466172e+08],
       [6.94076420e+09, 1.96129124e+10, 1.11642674e+09],
       [1.88618492e+10, 1.73640817e+10, 4.84980874e+09]])

Remove = [(0, 1),(0,2)] 
b = [[j for i, j in enumerate(m) if (k, i) not in Remove] for k, m in enumerate(R)]
R1 = np.array([i for j in b for i in j]) #Flatten the resulting list

print(R1)

Output

array([1.05567452e+11, 6.94076420e+09, 1.96129124e+10, 1.11642674e+09,
       1.88618492e+10, 1.73640817e+10, 4.84980874e+09])

删除一些元素并使python的阵列变平

生生不灭 2025-01-28 16:44:55

我也有同样的问题。我已经安装了CLI。

git remote

输出:

heroku
origin

git remote -v

输出:

heroku  https://git.heroku.com/YOUR-APP.git (fetch)
heroku  https://git.heroku.com/YOUR-APP.git (push)
origin  https://github.com/GitUserName/yourRepo.git (fetch)
origin  https://github.com/GitUserName/yourRepo.git (push)

如果您的分支命名为Main,则使用GIT分支验证。例如,您会这样做:

git push heroku main

对我而言,

git push heroku master

现在可以推动您的本地更改

git push heroku master

输出:

To https://git.heroku.com/YOUR-APP.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://git.heroku.com/YOUR-APP.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

我不在乎它与遥控器不同。我一直在本地开发,但没有意识到自动GIT部署已经失败。我关心本地更改:

git push heroku master -f

现在部署的应用程序正在按预期工作。

I had the same issue. I already had cli installed.

git remote

Output:

heroku
origin

git remote -v

Output:

heroku  https://git.heroku.com/YOUR-APP.git (fetch)
heroku  https://git.heroku.com/YOUR-APP.git (push)
origin  https://github.com/GitUserName/yourRepo.git (fetch)
origin  https://github.com/GitUserName/yourRepo.git (push)

Verify using the Git branch, if your branch is named main. For example, you would do:

git push heroku main

For me it is

git push heroku master

Now push your local changes

git push heroku master

Output:

To https://git.heroku.com/YOUR-APP.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://git.heroku.com/YOUR-APP.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

I do not care that it is different than its remote. I've been developing locally and did not realize the automatic Git deploys had been failing. I care about the local changes:

git push heroku master -f

Now the deployed application is working as expected.

Heroku和github:“无法检索项目,内部服务器错误”

生生不灭 2025-01-28 12:37:54

由于Numpy数组为数组中的值分配内存,因此将您的空字符串分配为 dtype ='&lt; u1',这不足以存储具有长度&gt; = 2的字符串

。使用对象而不是 str ,它将为 pyobject 在数组中分配内存,其中数据类型是一个可以指定为Python对象成为您想要的完整python字符串。

((imgl.shape [0]

matrixk = np.empty((( (

)字符串事先,您还可以使用&lt; u4 分配内存以在每个位置中最多容纳4个字符。

np.empty((((((imgl.shape [0])

matrixk = /code>不起作用,Numpy试图在数组中不使用 pyobject s时要变得聪明,因此元素在内存中是连续的。这是Numpy的行为,因为其主要用例是为了存储数值,其中矩阵操作在存储器中连续而不是必须放置 pyObject pointers(Python的默认行为)时,矩阵操作更有效。但是,由于数组需要为内存分配而具有元素的数据类型,因此numpy从输入中注入,并将其表示为&lt; u1 对于您的空字符串。

在低级语言中,您将面临相同的问题,即必须将指针分配给char数组/字符串或为具有预定义长度的字符串分配。

Since numpy arrays allocate memory for the values in the array, your empty strings are allocated as dtype='<U1', which is not enough to store strings with length >= 2.

You need to use object instead of str, which will allocate memory for PyObject pointers in the array where the data type is a python object that can be dereferenced to be the full python string you intended.

matrixK = np.empty(((imgL.shape[0], imgL.shape[1])), dtype=object)

EDIT

If you know the size of the strings beforehand, you could also use <U4 to allocate memory to hold up to 4 characters in each position.

matrixK = np.empty(((imgL.shape[0], imgL.shape[1])), dtype='<U4')

As for why using dtype=str doesn't work, numpy is trying to be smart in not using PyObjects in the array so the elements are contiguous in memory. This is numpy's behaviour as its primary use case is for storing numerical values where matrix operations are more efficient when values are contiguous in memory instead of having to dereference PyObject pointers (Python's default behavior). But since arrays need to have a data type for the elements for the purpose of memory allocation, numpy infers from the input and represents it as <U1 for your case of empty strings.

In a lower-level language, you'd face the same issue of having to either allocate a pointer to the char array/string or allocate for strings with a predefined length.

问题将字符串添加到2D数组

生生不灭 2025-01-28 07:45:08

使用MAP创建ZOO对象的L列表L,然后使用Merge.ZOO将它们合并到一个动物园对象中。最终将索引转换为Yearmon提供Z.ym Zoo对象。如果您需要数据框架,请选择使用fortify.zoo(z.ym)。

library(tseries)
library(zoo)
  
ticker<-c('AAPL','MSFT','AMZN')
L  <- Map(get.hist.quote, ticker, start="2009-12-01", end="2020-02-01", 
  quote="AdjClose", provider="yahoo", origin="2000-09-01", compression="m", 
  retclass="zoo")
z <- setNames(do.call("merge", L), ticker)
z.ym <- aggregate(z, as.yearmon, c)

head(z.ym)
##              AAPL     MSFT   AMZN
## Dec 2009 6.444381 23.49339 134.52
## Jan 2010 5.873429 21.72060 125.41
## Feb 2010 6.257530 22.09828 118.40
## Mar 2010 7.186586 22.68174 135.77
## Apr 2010 7.984454 23.64972 137.10
## May 2010 7.855704 19.97913 125.46

或者将其作为管道表示:

clean_names <- function(x) setNames(x, sub("Adjusted.", "", names(x)))
out <- ticker |>
  Map(f = get.hist.quote, start="2009-12-01", end="2020-02-01", quote="AdjClose", 
    provider="yahoo", origin="2000-09-01", compression="m", retclass="zoo") |>
  do.call(what = "merge") |>
  clean_names() |>
  aggregate(as.yearmon, c)

Use Map to create the list L of zoo objects and then use merge.zoo to merge them into a single zoo object. Finally convert the index to yearmon giving the z.ym zoo object. Optionally use fortify.zoo(z.ym) if you need a data frame.

library(tseries)
library(zoo)
  
ticker<-c('AAPL','MSFT','AMZN')
L  <- Map(get.hist.quote, ticker, start="2009-12-01", end="2020-02-01", 
  quote="AdjClose", provider="yahoo", origin="2000-09-01", compression="m", 
  retclass="zoo")
z <- setNames(do.call("merge", L), ticker)
z.ym <- aggregate(z, as.yearmon, c)

head(z.ym)
##              AAPL     MSFT   AMZN
## Dec 2009 6.444381 23.49339 134.52
## Jan 2010 5.873429 21.72060 125.41
## Feb 2010 6.257530 22.09828 118.40
## Mar 2010 7.186586 22.68174 135.77
## Apr 2010 7.984454 23.64972 137.10
## May 2010 7.855704 19.97913 125.46

Alternately express this as a pipeline:

clean_names <- function(x) setNames(x, sub("Adjusted.", "", names(x)))
out <- ticker |>
  Map(f = get.hist.quote, start="2009-12-01", end="2020-02-01", quote="AdjClose", 
    provider="yahoo", origin="2000-09-01", compression="m", retclass="zoo") |>
  do.call(what = "merge") |>
  clean_names() |>
  aggregate(as.yearmon, c)

从网站下载数据

生生不灭 2025-01-27 14:56:35

您的代码为XSLT 2.0,您不会说哪种工具给出了该警告,但它可能是针对XSLT 1.0语法检查的工具(其中 as 不存在)。

如果使用XSLT 2或3处理器运行代码,则&lt; XSL的结果:select of select =“ $ array”/&gt; 将是该项目中项目的空间分离列表sequence $ array (是的,变量是一个节点的序列,而不是节点数组;仅在XSLT 3中存在XPATH 3.1和XQUERY 3.1中的数组)。

Your code is XSLT 2.0, you don't say which tool gives that warning but it is probably a tool checking against the XSLT 1.0 syntax (where as doesn't exist).

If you run the code with an XSLT 2 or 3 processor then the result of <xsl:value-of select="$array"/> would be a space separated list of the items in the sequence $array (yes, the variable is a sequence of nodes, not an array of nodes; arrays only exist in XSLT 3 with XPath 3.1 and XQuery 3.1).

警告:属性&#x27; as&#x27;未在XSLT中声明

生生不灭 2025-01-27 10:35:22

您已使用 @MockBean 注释了 AgentService,因此当应该在测试期间调用它时,仅调用模拟并且结果为 null,导致端点返回的页面为 listAgents = null。
因此,两种情况都是 200。您可以将 AgentService 和 AgentMapper 包含在测试的 applicationContext 中,并使用 @Autowired 注释它们,或者您可以指定模拟的行为,但由于您想使用 h2,我想您应该选择第一个。
此外,您还可以为抛出异常时显式返回 404 的情况定义异常处理程序

    @ControllerAdvice
    public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

      @ExceptionHandler(AgencyNotFoundException.class)
      public ResponseEntity<Object> handleAgencyNotFound(AgencyNotFoundException exception, WebRequest request) {
        return handleExceptionInternal(exception, exception.getMessage(),
            new HttpHeaders(), HttpStatus.NOT_FOUND, request);
      }
    }

You have annotated your AgentService with @MockBean so when it is supposed to be called during the test only a mock is called and the result is null resulting in the page returned by your endpoint with listAgents = null.
Therefore the 200 in both cases. You can either include your AgentService and your AgentMapper in the applicationContext of your test and annotate them with @Autowired or you could specify the behavior of the mocks but since you want to use h2 I guess you should go with the first one.
Additionally you could also define an exception handler for the case when your exception is thrown to explicitly return a 404

    @ControllerAdvice
    public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

      @ExceptionHandler(AgencyNotFoundException.class)
      public ResponseEntity<Object> handleAgencyNotFound(AgencyNotFoundException exception, WebRequest request) {
        return handleExceptionInternal(exception, exception.getMessage(),
            new HttpHeaders(), HttpStatus.NOT_FOUND, request);
      }
    }

与H2失败的春季MVC集成测试

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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