旧时浪漫

文章 评论 浏览 27

旧时浪漫 2025-02-21 01:20:45

解释Python的切片符号

)(可订阅[subscriptArg] )使切片表示法,其中具有可选的参数 start stop 步骤

sliceable[start:stop:step]

Python切片是一种计算快速的方法,可有条不紊地访问数据的一部分。我认为,即使是中级Python程序员,这是必须熟悉的语言的一个方面。

一开始的重要定义

,让我们定义几个术语:

start slice的开始索引,除非与 stop 相同,否则它将在此索引处包含元素到0,即第一个索引。如果是负的,则意味着从末尾开始 n 项目。

stop 切片的结尾索引,它确实 not 在此索引处包含元素,默认为序列的长度为切成薄片,也就是说结束。

步骤索引增加的数量,默认为1。如果是负数,则您将在相反的情况下切下。

索引的工作原理

您可以使这些正数或负数中的任何一个。正数的含义很简单,但是对于负数,就像python中的索引一样,您从末端倒数 start stop ,而对于< em>步骤,您只需减少索引即可。此示例是从文档的教程中每个索引参考的序列中的哪一项:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5 
  -6  -5  -4  -3  -2  -1

切片的工作原理

以使用支持它的序列使用切片符号,您必须在正方形中至少包含一个结肠遵循序列的括号(实际上 >根据Python数据模型。序列的

sequence[start:stop:step]

方法 start stop 步骤有默认值,因此要访问默认值,只需删除参数即可。

切片符号从列表中获取最后的九个元素(或任何其他支持它的序列,如字符串)看起来像这样:

my_list[-9:]

当我看到此元素时,我将零件读取为“从末端到第9,到结尾。” (实际上,我在心理上缩写为“ -9,on”)

说明:

完整的符号是

my_list[-9:None:None]

并替换默认值(实际上,当 step 为负面时, stop> stop '默认值为 -len(my_list)-1 ,所以 note for stop for stop for Stop for Stop实际上只是意味着它可以转到该端步骤的任何一个步骤)

my_list[-9:len(my_list):1]

colon ,:,是告诉Python您给它一个切片而不是常规索引的原因。这就是为什么在Python 2中制作列表浅副本的惯用方法

list_copy = sequence[:]

与众不同:(

del my_list[:]

Python 3获取 list.copy.copy list.list.clear.clear.clear methot。 )

步骤为负面时, start stop 默认情况

默认为​​默认情况(或),将其分配给 +1

但是您可以通过负整数传递,并且从开始到开始,列表(或大多数其他标准切片)将被切成薄片。

因此,负面切片将更改 start stop 的默认值!

在来源中证实这一点,

我喜欢鼓励用户阅读源以及文档。 slice对象的源代码,此逻辑在这里找到。首先,我们确定步骤是负面的:

  step_is_negative = step_sign&lt; 0;
 

如果是这样,下限为 -1 ,则表示我们一直将其切成序列和包括开始,并且上限是长度为负1,这意味着我们在末尾开始。 (请注意,此 -1 的语义与 -1 的不同是不同的,用户可以在python中传递索引,指示最后一项。)

  if(step_is_negative){
    lower = pylong_fromlong(-1L);
    if(下== null)
        goto错误;

    upper = pynumber_add(长度,下);
    if(upper == null)
        goto错误;
}
 

否则,步骤为正,下边界将为零,上限(我们要延长但不包括在内)切片列表的长度。

  else {
    lower = _pylong_zero;
    py_incref(下);
    上=长度;
    py_incref(上);
}
 

然后,我们可能需要应用 start stop 的默认值 - 当开始时,将默认值计算为时的上限。步骤是负面的:

  if(self&gt; start == py_none){
    start = step_is_negative?鞋面:下;
    py_incref(start);
}
 

停止,下限:

  if(self&gt; stop == py_none){
    stop = step_is_negative?下:上;
    py_incref(stop);
}
 

给您的切片一个描述性的名称!

您可能会发现将切片分开从传递到 list .__ getItem __ method(

但是,您不能仅仅将某些由结肠隔开的整数分配给变量。您需要使用slice对象:

last_nine_slice = slice(-9, None)

需要第二个参数, none ,以便将第一个参数解释为 start> start 参数,否则将是 stop> stop 参数

然后,您可以将切片对象传递给您的顺序:

>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]

有趣的是,范围还需要切片:

>>> range(100)[last_nine_slice]
range(91, 100)

内存注意事项:

由于python列表的切片在内存中创建新对象,因此要注意的另一个重要功能IS itertools.islices.islices.islice 。通常,您需要在切片上迭代,而不仅仅是在内存中静态创建。 islice 是完美的。警告,它不支持 start stop 步骤,因此,如果这是问题,则可能需要计算索引或提前扭转峰值。

length = 100
last_nine_iter = itertools.islice(list(range(length)), length-9, None, 1)
list_last_nine = list(last_nine_iter)

现在:

>>> list_last_nine
[91, 92, 93, 94, 95, 96, 97, 98, 99]

列表切片制作副本的事实是列表本身的功能。如果您将诸如Pandas DataFrame的高级对象切片,则可能会返回原始视图,而不是副本。

Explain Python's slice notation

In short, the colons (:) in subscript notation (subscriptable[subscriptarg]) make slice notation, which has the optional arguments start, stop, and step:

sliceable[start:stop:step]

Python slicing is a computationally fast way to methodically access parts of your data. In my opinion, to be even an intermediate Python programmer, it's one aspect of the language that it is necessary to be familiar with.

Important Definitions

To begin with, let's define a few terms:

start: the beginning index of the slice, it will include the element at this index unless it is the same as stop, defaults to 0, i.e. the first index. If it's negative, it means to start n items from the end.

stop: the ending index of the slice, it does not include the element at this index, defaults to length of the sequence being sliced, that is, up to and including the end.

step: the amount by which the index increases, defaults to 1. If it's negative, you're slicing over the iterable in reverse.

How Indexing Works

You can make any of these positive or negative numbers. The meaning of the positive numbers is straightforward, but for negative numbers, just like indexes in Python, you count backwards from the end for the start and stop, and for the step, you simply decrement your index. This example is from the documentation's tutorial, but I've modified it slightly to indicate which item in a sequence each index references:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5 
  -6  -5  -4  -3  -2  -1

How Slicing Works

To use slice notation with a sequence that supports it, you must include at least one colon in the square brackets that follow the sequence (which actually implement the __getitem__ method of the sequence, according to the Python data model.)

Slice notation works like this:

sequence[start:stop:step]

And recall that there are defaults for start, stop, and step, so to access the defaults, simply leave out the argument.

Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:

my_list[-9:]

When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on")

Explanation:

The full notation is

my_list[-9:None:None]

and to substitute the defaults (actually when step is negative, stop's default is -len(my_list) - 1, so None for stop really just means it goes to whichever end step takes it to):

my_list[-9:len(my_list):1]

The colon, :, is what tells Python you're giving it a slice and not a regular index. That's why the idiomatic way of making a shallow copy of lists in Python 2 is

list_copy = sequence[:]

And clearing them is with:

del my_list[:]

(Python 3 gets a list.copy and list.clear method.)

When step is negative, the defaults for start and stop change

By default, when the step argument is empty (or None), it is assigned to +1.

But you can pass in a negative integer, and the list (or most other standard sliceables) will be sliced from the end to the beginning.

Thus a negative slice will change the defaults for start and stop!

Confirming this in the source

I like to encourage users to read the source as well as the documentation. The source code for slice objects and this logic is found here. First we determine if step is negative:

step_is_negative = step_sign < 0;

If so, the lower bound is -1 meaning we slice all the way up to and including the beginning, and the upper bound is the length minus 1, meaning we start at the end. (Note that the semantics of this -1 is different from a -1 that users may pass indexes in Python indicating the last item.)

if (step_is_negative) {
    lower = PyLong_FromLong(-1L);
    if (lower == NULL)
        goto error;

    upper = PyNumber_Add(length, lower);
    if (upper == NULL)
        goto error;
}

Otherwise step is positive, and the lower bound will be zero and the upper bound (which we go up to but not including) the length of the sliced list.

else {
    lower = _PyLong_Zero;
    Py_INCREF(lower);
    upper = length;
    Py_INCREF(upper);
}

Then, we may need to apply the defaults for start and stop—the default then for start is calculated as the upper bound when step is negative:

if (self->start == Py_None) {
    start = step_is_negative ? upper : lower;
    Py_INCREF(start);
}

and stop, the lower bound:

if (self->stop == Py_None) {
    stop = step_is_negative ? lower : upper;
    Py_INCREF(stop);
}

Give your slices a descriptive name!

You may find it useful to separate forming the slice from passing it to the list.__getitem__ method (that's what the square brackets do). Even if you're not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you're doing.

However, you can't just assign some integers separated by colons to a variable. You need to use the slice object:

last_nine_slice = slice(-9, None)

The second argument, None, is required, so that the first argument is interpreted as the start argument otherwise it would be the stop argument.

You can then pass the slice object to your sequence:

>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]

It's interesting that ranges also take slices:

>>> range(100)[last_nine_slice]
range(91, 100)

Memory Considerations:

Since slices of Python lists create new objects in memory, another important function to be aware of is itertools.islice. Typically you'll want to iterate over a slice, not just have it created statically in memory. islice is perfect for this. A caveat, it doesn't support negative arguments to start, stop, or step, so if that's an issue you may need to calculate indices or reverse the iterable in advance.

length = 100
last_nine_iter = itertools.islice(list(range(length)), length-9, None, 1)
list_last_nine = list(last_nine_iter)

and now:

>>> list_last_nine
[91, 92, 93, 94, 95, 96, 97, 98, 99]

The fact that list slices make a copy is a feature of lists themselves. If you're slicing advanced objects like a Pandas DataFrame, it may return a view on the original, and not a copy.

Python中的切片如何工作

旧时浪漫 2025-02-20 22:18:19

您可以尝试 lstrip 最后三列名称,然后添加第一个列名或 .str.replace

df2.columns = df2.columns[:1].tolist() + df2.columns[1:].str.lstrip("d").tolist()
# or
df2.columns = df2.columns.str.replace('^d(\d.*)', r'\1', regex=True)

You can try lstrip the last three column names then add the first column name or with .str.replace

df2.columns = df2.columns[:1].tolist() + df2.columns[1:].str.lstrip("d").tolist()
# or
df2.columns = df2.columns.str.replace('^d(\d.*)', r'\1', regex=True)

基于LSTRE的大熊猫的条件重命名柱不起作用

旧时浪漫 2025-02-20 14:22:02

这是一个潜在的dplyr解决方案:

library(dplyr)

df <- read.table(text = "ind yyyymm cumperc name
 1 202006   0.196 CHILD 
 2 202006   0.327 WOMAN 
 3 202006   0.401 MAN 
 4 202006   0.461 PET 
 5 202006   0.504 FRIEND
 6 202006   0.604 ENEMY
 7 202006   0.845 PLACE
 8 202006   1.000 ITEM
 9 202007   0.157 CHILD     
 10 202007   0.265 MAN
 11 202007   0.369 WOMAN
 12 202007   0.459 PET
 13 202007  0.494 FRIEND
 14 202007  0.519 ENEMY
 15 202007  0.766 ITEM
 16 202007  1.000 PLACE",
 header = TRUE)

df %>%
  group_by(yyyymm) %>%
  filter(lag(cumperc, default = first(cumperc)) <= .50)
#> # A tibble: 11 × 4
#> # Groups:   yyyymm [2]
#>      ind yyyymm cumperc name  
#>    <int>  <int>   <dbl> <chr> 
#>  1     1 202006   0.196 CHILD 
#>  2     2 202006   0.327 WOMAN 
#>  3     3 202006   0.401 MAN   
#>  4     4 202006   0.461 PET   
#>  5     5 202006   0.504 FRIEND
#>  6     9 202007   0.157 CHILD 
#>  7    10 202007   0.265 MAN   
#>  8    11 202007   0.369 WOMAN 
#>  9    12 202007   0.459 PET   
#> 10    13 202007   0.494 FRIEND
#> 11    14 202007   0.519 ENEMY

那会适合您的用例吗?

Here is a potential dplyr solution:

library(dplyr)

df <- read.table(text = "ind yyyymm cumperc name
 1 202006   0.196 CHILD 
 2 202006   0.327 WOMAN 
 3 202006   0.401 MAN 
 4 202006   0.461 PET 
 5 202006   0.504 FRIEND
 6 202006   0.604 ENEMY
 7 202006   0.845 PLACE
 8 202006   1.000 ITEM
 9 202007   0.157 CHILD     
 10 202007   0.265 MAN
 11 202007   0.369 WOMAN
 12 202007   0.459 PET
 13 202007  0.494 FRIEND
 14 202007  0.519 ENEMY
 15 202007  0.766 ITEM
 16 202007  1.000 PLACE",
 header = TRUE)

df %>%
  group_by(yyyymm) %>%
  filter(lag(cumperc, default = first(cumperc)) <= .50)
#> # A tibble: 11 × 4
#> # Groups:   yyyymm [2]
#>      ind yyyymm cumperc name  
#>    <int>  <int>   <dbl> <chr> 
#>  1     1 202006   0.196 CHILD 
#>  2     2 202006   0.327 WOMAN 
#>  3     3 202006   0.401 MAN   
#>  4     4 202006   0.461 PET   
#>  5     5 202006   0.504 FRIEND
#>  6     9 202007   0.157 CHILD 
#>  7    10 202007   0.265 MAN   
#>  8    11 202007   0.369 WOMAN 
#>  9    12 202007   0.459 PET   
#> 10    13 202007   0.494 FRIEND
#> 11    14 202007   0.519 ENEMY

Created on 2022-07-07 by the reprex package (v2.0.1)

Would that suit your use-case?

r累积百分比的子集,直到并包括一定值

旧时浪漫 2025-02-19 22:05:02

我似乎发现了我的问题。问题在于我的一种产品之一出于某种原因,其中包含它的引号,但是一旦删除了OnClick多次工作,同时将产品名称发送到函数以保持跟踪。

给出的答案的问题还在于我不想在按钮本身内部显示所有名称&lt; button class =“ test”&gt; item&lt;/button&gt; 而不是我需要的&lt; button onClick ='func($ {passname})&gt;&lt;/button&gt; ,因此在尝试时不会工作,但它给了我一个未来参考的一般思想。谢谢!

I seem to have found my problem. The issue was with one of my products having quotations inside of it for some reason but once removed the onclick worked multiple times while sending the product name to a function to keep track.

The problem with the answers given was also that I didnt want to display the name at all inside the button itself <button class=“test”>Item</button> instead this is what I needed <button onclick=‘func(${passname})></button> so that would have not worked when attempted but it gave me a general idea for future references. Thanks!

为什么是“ onclick”仅工作一次并且无法更新?

旧时浪漫 2025-02-19 13:37:15

您也可以使用默认为0的get()

newdict = {x: dict1.get(x, 0) + dict2.get(x, 0) for x in set(dict1) | set(dict2)}

You could also use get() with a default of 0

newdict = {x: dict1.get(x, 0) + dict2.get(x, 0) for x in set(dict1) | set(dict2)}

合并2个字典,如果有共同的键,请尝试更新总和?

旧时浪漫 2025-02-19 04:01:27

我认为您将需要做的一些文档(也许有一些更改以适合您的配置)

httpd docker官方图像文档建议首先导出配置

$ docker run --rm httpd:2.4 cat /usr/local/apache2/conf/httpd.conf > ./apache/my-httpd.conf # Dumping to your apache folder

,然后在编辑后,因为您要复制用于容器的编辑零件。在这种情况下,您将需要告诉Apache包括VHOSTS配置

# Include conf/extra/httpd-vhosts.conf

在您的虚拟主机配置之后,即使不匹配 servername (您都看不到该服务器)(即使您看不到该服务器的任何请求)(您将看不到该请求) htdocs默认值不再)

docker -compose.yml - 示例

services:
  apache:
    image: httpd:alpine # Using the image directly since everything is accessible through the volumes
    container_name: dev_apache
    ports:
      - 80:80
    volumes:
      - ./wordpress:/var/www/html:delegated
      - ./apache/my-httpd.conf:/usr/local/apache2/conf/httpd.conf
      - ./apache/httpd-vhosts.conf:/usr/local/apache2/conf/extra/httpd-vhosts.conf

编辑

您也需要一个目录指令/var/var/www/html 目录中授予许可,因为 my-httpd.conf 是拒绝整个服务器文件系统。这样的事情:

<VirtualHost *:80>
    <...> Your stuff <...>
    <Directory /var/www/html>
        Require all granted
    </Directory>

</VirtualHost>

Looking into some documentations here is what I think you will need to do (maybe with some changes to fit in your configuration)

The httpd docker official image docs recommends to export the configuration first

$ docker run --rm httpd:2.4 cat /usr/local/apache2/conf/httpd.conf > ./apache/my-httpd.conf # Dumping to your apache folder

then after editing as you want copy the edited part for your container. In this case you will need to tell apache to include vhosts configuration uncommenting the line

# Include conf/extra/httpd-vhosts.conf

After that you virtual host configuration will override any request made for the server even if not matching the ServerName (you'll not see the htdocs default anymore)

docker-compose.yml - Example

services:
  apache:
    image: httpd:alpine # Using the image directly since everything is accessible through the volumes
    container_name: dev_apache
    ports:
      - 80:80
    volumes:
      - ./wordpress:/var/www/html:delegated
      - ./apache/my-httpd.conf:/usr/local/apache2/conf/httpd.conf
      - ./apache/httpd-vhosts.conf:/usr/local/apache2/conf/extra/httpd-vhosts.conf

Edit

Also you will want a Directory directive to give permission in /var/www/html directory since the default directive in my-httpd.conf is to deny the entire server filesystem. Something like this:

<VirtualHost *:80>
    <...> Your stuff <...>
    <Directory /var/www/html>
        Require all granted
    </Directory>

</VirtualHost>

docker apache容器服务/usr/local/apache2/htdocs作为documentroot而不是/var/www/html

旧时浪漫 2025-02-17 19:35:43

有时它的图标问题。您需要用其他一些图标替换并尝试。您可以将网站用于图像类型的图像类型。

sometimes its problem with the icon. you need to replace it with some other icon and try. there is site you can use for icon generating and testing the image type.
LINK

如何使用Flutter局部通知更改Android通知托盘上的图标?

旧时浪漫 2025-02-17 16:03:55

看来您在计算机上安装了多个Python版本,并且计算机的默认Python版本应为 Python2 (也许与系统环境变量有关)。您可以使用 py -v 检查版本。

建议您使用虚拟环境,并且在每个虚拟环境中仅保留一个Python版本。当您选择解释器时( ctrl + shift + p - &gt; python:选择解释器),新的终端( ctrl + shift + `)将自动激活虚拟环境。

虚拟环境对您使用解释器和特定软件包的特定版本非常有用。

为了防止这种混乱,开发人员经常为项目创建虚拟环境。虚拟环境是包含特定解释器的副本(或符号链接)的文件夹。当您安装到虚拟环境中时,您安装的任何软件包仅在该子文件夹中安装。然后,当您在该环境中运行Python程序时,您就会知道它仅针对那些特定的软件包。

如何创建虚拟环境:

  1. 创建虚拟环境

      python -m venv&lt; name_of_envirnment&gt;
     
  2. 激活虚拟环境

     &lt; name_of_envirnment&gt; \ scripts \ activate
     

官方文档:创建一个虚拟环境

It looks like you have multiple python versions installed on your machine, and your computer's default python version should be python2 (perhaps related to system environment variables). You can check the version with py -V.

It is recommended that you use a virtual environment and keep only one python version in each virtual environment. When you select an interpreter ( Ctrl + Shift + P --> Python: Select Interpreter), the new terminal ( Ctrl + Shift + ` ) will automatically activate the virtual environment.

Virtual environments are very useful for you to use a specific version of the interpreter and a specific package.

To prevent such clutter, developers often create a virtual environment for a project. A virtual environment is a folder that contains a copy (or symlink) of a specific interpreter. When you install into a virtual environment, any packages you install are installed only in that subfolder. When you then run a Python program within that environment, you know that it's running against only those specific packages.

How to create a virtual environment:

  1. Create Virtual Environment

    python -m venv <name_of_envirnment>
    
  2. Activate Virtual Environment

    <name_of_envirnment>\scripts\activate
    

official documentation: Create a virtual environment

在Vscode终端运行编码器时,它说我的变量不确定

旧时浪漫 2025-02-17 13:33:31

您对 _source 字段是正确的,但是如果您不定义字段的映射,则Elasticsearch会生成默认映射,并使用这些字段的默认参数。您可以阅读有关映射param param 在您的情况下,如果您想搜索字段,则需要成为倒置索引的一部分,并且由 index param param

您可以通过定义自己的映射来覆盖这些参数的值(建议否则Elasticsearch将根据您在字段中索引的第一个数据猜测字段类型)。

希望这有帮助并清除您的疑问,简而言之,如果您没有定义映射,则 text 默认情况下可以搜索数据。

you are right about the _source field, but if you don't define the mapping for your fields, Elasticsearch generates the default mapping with default param for these fields . You can read more about the mapping param and in your case, if you want field to be searchable it needs to be the part of the inverted index and this is controlled by the index param.

You can override the value of these params by defining your own mapping(recommended otherwise Elasticsearch will guess the field type based on the first data you index in a field).

Hope this helps and clears your doubt, in short if you are not defining your mapping, your text data is searchable by default.

添加数据弹性搜索的最佳方法

旧时浪漫 2025-02-16 18:11:22

您正在问如何将多个对象放在一个数组中,但是所需的输出是字符串对象。因此,我将所需的输出视为实际问题:)

您只需要通过 Datalist 迭代并将值合并到字符串对象中。

StringObject = ''
for(let i=0; i < DataList.length; i++){
    if(i===0)
        StringObject += DataList[i]
    else
        StringObject += ',' + DataList[i]
}
console.log(StringObject)

或只是

StringObject = String(DataList)
console.log(StringObject)

Your are asking how to put multiple objects in one array but your desired output is the string object. So I'm considering your desired output as the actual question :)

For that you just have to iterate through your DataList and merge values into an string object.

StringObject = ''
for(let i=0; i < DataList.length; i++){
    if(i===0)
        StringObject += DataList[i]
    else
        StringObject += ',' + DataList[i]
}
console.log(StringObject)

Or just

StringObject = String(DataList)
console.log(StringObject)

如何将多个对象放在JavaScript中的一个数组中?

旧时浪漫 2025-02-16 10:36:15

使用:

#filter only S columns
df1 = df.filter(like='S')
#compare for greater or equal by division nlargestsum with N and if match replace values
df.update(df1.mask(df1.ge(df['nlargestsum'].div(N), axis=0), df['nlargestsum'], axis=0))
print (df)
     S1   S2   S3   S4   S5   S6  nlargestsum
ID                                           
1   0.9  0.0  0.0  0.0  0.0  0.0          0.9
2   0.9  0.9  0.9  0.0  0.0  0.1          0.9
3   0.0  0.0  0.0  0.2  0.6  0.0          0.6
4   1.0  0.0  0.0  0.0  0.0  0.0          1.0
5   0.1  0.1  0.9  0.9  0.0  0.0          0.9

Use:

#filter only S columns
df1 = df.filter(like='S')
#compare for greater or equal by division nlargestsum with N and if match replace values
df.update(df1.mask(df1.ge(df['nlargestsum'].div(N), axis=0), df['nlargestsum'], axis=0))
print (df)
     S1   S2   S3   S4   S5   S6  nlargestsum
ID                                           
1   0.9  0.0  0.0  0.0  0.0  0.0          0.9
2   0.9  0.9  0.9  0.0  0.0  0.1          0.9
3   0.0  0.0  0.0  0.2  0.6  0.0          0.6
4   1.0  0.0  0.0  0.0  0.0  0.0          1.0
5   0.1  0.1  0.9  0.9  0.0  0.0          0.9

如何替换dataframe pandas中那些最大值值的nlar最大值

旧时浪漫 2025-02-16 06:30:53

具有接受 const char*的构造函数。
因此,您要做的就是使用 gcnew 创建一个新的 system :: string const char*传递为参数(a <代码> char*也可以传递)。

请参阅下面的代码:

System::String^ cts(const char *aa)
{
    return gcnew System::String(aa);
}

int main()
{
    System::String ^ system_str = cts("abcd");
    System::Console::WriteLine(system_str);
    return 0;
}

输出:

abcd

System::String has a constructor that accepts a const char*.
Therefore all you have to do is to use gcnew to create a new System::String passing the const char* as a parameter (a char* can also be passed).

See the code below:

System::String^ cts(const char *aa)
{
    return gcnew System::String(aa);
}

int main()
{
    System::String ^ system_str = cts("abcd");
    System::Console::WriteLine(system_str);
    return 0;
}

Output:

abcd

在c&#x2b;/cli中,如何将char *复制到系统:: string(不是c&#x2b;&#x2b; std :: string)?

旧时浪漫 2025-02-15 18:15:01

在克隆的存储库中首先尝试 git ls-files -eol (git 2.8(2016年3月) ))

git config -global core.autocrlf false 之后也尝试同一克隆。

如果这与EOL相关,则不应有差异,并且 git状态应该干净。

Try first in your cloned repository git ls-files --eol (Git 2.8 (March 2016))

Try also the same clone after git config --global core.autocrlf false.

If this is eol (end-of-line) related, there should be no diff, and git status should be clean.

为什么在git添加后什么都没有提交。?

旧时浪漫 2025-02-15 17:28:15

您可以这样写它:

use num::Complex;

macro_rules! vec_cplx {
    ($(($re:expr, $im:expr)),*) => {
        vec![$(Complex::new($re, $im)),*]
    }
}

fn main() {
    let v: Vec<Complex<f32>> = vec_cplx![(0.0, -25.0), (0.0, -9.0)];
    dbg!(v);
    let v: Vec<Complex<f64>> = vec_cplx![(0.0, -25.0), (0.0, -9.0)];
    dbg!(v);
}

这将适用于复杂:: new()接受的任何类型,因为它是宏,并且类型检查在宏扩展后发生。

You can write it like this:

use num::Complex;

macro_rules! vec_cplx {
    ($(($re:expr, $im:expr)),*) => {
        vec![$(Complex::new($re, $im)),*]
    }
}

fn main() {
    let v: Vec<Complex<f32>> = vec_cplx![(0.0, -25.0), (0.0, -9.0)];
    dbg!(v);
    let v: Vec<Complex<f64>> = vec_cplx![(0.0, -25.0), (0.0, -9.0)];
    dbg!(v);
}

Playground

This will work with any type that Complex::new() accepts since it's a macro and the type checking happens after macro expansion.

如何编写宏以将元素列表转换为复数的VEC

旧时浪漫 2025-02-15 17:20:10

这是一个简单的解决方案,它使用 fetch()从这两个URL中获取数据,然后插入所有返回到网页的人和一个星球:

function myFetch(...args) {
    return fetch(...args).then(response => {
        if (!response.ok) {
            throw new Error(`fetch failed with status ${response.status}`);
        }
        return response.json();
    });
}

Promise.all([
    myFetch("https://swapi.dev/api/people/"),
    myFetch("https://swapi.dev/api/planets/2/")
]).then(([people, planet]) => {
    const peopleDiv = document.getElementById("people");
    let peopleHTML = "";
    for (let p of people.results) {
        peopleHTML += `<div>${p.name}</div>`;
    }
    peopleDiv.innerHTML = peopleHTML;
    
    const planetDiv = document.getElementById("planets");
    let planetHTML = `<div>${planet.name}</div>`;
    planetDiv.innerHTML = planetHTML;
}).catch(err => {
    console.log(err);
});
<div id="people"></div>
<hr>
<div id="planets"></div>

至于使用结果,人们URL返回一个看起来像这样的结构:

{
  count: 82,
  next: 'https://swapi.dev/api/people/?page=2',
  previous: null,
  results: [
    {
      name: 'Luke Skywalker',
      height: '172',
      mass: '77',
      hair_color: 'blond',
      skin_color: 'fair',
      eye_color: 'blue',
      birth_year: '19BBY',
      gender: 'male',
      homeworld: 'https://swapi.dev/api/planets/1/',
      films: [Array],
      species: [],
      vehicles: [Array],
      starships: [Array],
      created: '2014-12-09T13:50:51.644000Z',
      edited: '2014-12-20T21:17:56.891000Z',
      url: 'https://swapi.dev/api/people/1/'
    },
    {
      name: 'C-3PO',
      height: '167',
      mass: '75',
      hair_color: 'n/a',
      skin_color: 'gold',
      eye_color: 'yellow',
      birth_year: '112BBY',
      gender: 'n/a',
      homeworld: 'https://swapi.dev/api/planets/1/',
      films: [Array],
      species: [Array],
      vehicles: [],
      starships: [],
      created: '2014-12-10T15:10:51.357000Z',
      edited: '2014-12-20T21:17:50.309000Z',
      url: 'https://swapi.dev/api/people/2/'
    }
}

因此,您有 people.results ,这是一个数组,您可以访问 people.results [n]代码>从该数组中获取项目。 的对象。


该项目将是一个

{
  name: 'Alderaan',
  rotation_period: '24',
  orbital_period: '364',
  diameter: '12500',
  climate: 'temperate',
  gravity: '1 standard',
  terrain: 'grasslands, mountains',
  surface_water: '40',
  population: '2000000000',
  residents: [
    'https://swapi.dev/api/people/5/',
    'https://swapi.dev/api/people/68/',
    'https://swapi.dev/api/people/81/'
  ],
  films: [
    'https://swapi.dev/api/films/1/',
    'https://swapi.dev/api/films/6/'
  ],
  created: '2014-12-10T11:35:48.479000Z',
  edited: '2014-12-20T20:58:18.420000Z',
  url: 'https://swapi.dev/api/planets/2/'
}

具有 .name ,的属性 您可以在 planet.name 中访问该对象上的属性。


请注意,人们的结果是分页的。总共有82个,但第一个结果只有10个。其余的带有其他页面的结果,例如 https://swapi.dev/api/people/?page=2

Here's a simple solution that uses fetch() to grab data from both those URLs and then insert all the people and the one planet that is returned into your web page:

function myFetch(...args) {
    return fetch(...args).then(response => {
        if (!response.ok) {
            throw new Error(`fetch failed with status ${response.status}`);
        }
        return response.json();
    });
}

Promise.all([
    myFetch("https://swapi.dev/api/people/"),
    myFetch("https://swapi.dev/api/planets/2/")
]).then(([people, planet]) => {
    const peopleDiv = document.getElementById("people");
    let peopleHTML = "";
    for (let p of people.results) {
        peopleHTML += `<div>${p.name}</div>`;
    }
    peopleDiv.innerHTML = peopleHTML;
    
    const planetDiv = document.getElementById("planets");
    let planetHTML = `<div>${planet.name}</div>`;
    planetDiv.innerHTML = planetHTML;
}).catch(err => {
    console.log(err);
});
<div id="people"></div>
<hr>
<div id="planets"></div>

As for using the results, the people URL returns a structure that looks like this:

{
  count: 82,
  next: 'https://swapi.dev/api/people/?page=2',
  previous: null,
  results: [
    {
      name: 'Luke Skywalker',
      height: '172',
      mass: '77',
      hair_color: 'blond',
      skin_color: 'fair',
      eye_color: 'blue',
      birth_year: '19BBY',
      gender: 'male',
      homeworld: 'https://swapi.dev/api/planets/1/',
      films: [Array],
      species: [],
      vehicles: [Array],
      starships: [Array],
      created: '2014-12-09T13:50:51.644000Z',
      edited: '2014-12-20T21:17:56.891000Z',
      url: 'https://swapi.dev/api/people/1/'
    },
    {
      name: 'C-3PO',
      height: '167',
      mass: '75',
      hair_color: 'n/a',
      skin_color: 'gold',
      eye_color: 'yellow',
      birth_year: '112BBY',
      gender: 'n/a',
      homeworld: 'https://swapi.dev/api/planets/1/',
      films: [Array],
      species: [Array],
      vehicles: [],
      starships: [],
      created: '2014-12-10T15:10:51.357000Z',
      edited: '2014-12-20T21:17:50.309000Z',
      url: 'https://swapi.dev/api/people/2/'
    }
}

So, you have people.results which is an array and you can access people.results[n] to get an item from that array. That item will be an object which has properties like .name, .height, etc...


The specific planet URL you show returns a single planet object like this:

{
  name: 'Alderaan',
  rotation_period: '24',
  orbital_period: '364',
  diameter: '12500',
  climate: 'temperate',
  gravity: '1 standard',
  terrain: 'grasslands, mountains',
  surface_water: '40',
  population: '2000000000',
  residents: [
    'https://swapi.dev/api/people/5/',
    'https://swapi.dev/api/people/68/',
    'https://swapi.dev/api/people/81/'
  ],
  films: [
    'https://swapi.dev/api/films/1/',
    'https://swapi.dev/api/films/6/'
  ],
  created: '2014-12-10T11:35:48.479000Z',
  edited: '2014-12-20T20:58:18.420000Z',
  url: 'https://swapi.dev/api/planets/2/'
}

So, you access properties on that object as in planet.name.


Notice that the people results are paged. There are 82 total results, but only 10 come in this first result. The rest come with results for other pages such as https://swapi.dev/api/people/?page=2.

JavaScript,获取,API

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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