三人与歌

文章 评论 浏览 30

三人与歌 2025-02-08 05:32:41

我对 with_items 有严重的性能问题,这些任务是整本运行书中最昂贵的单个任务。

my-service : Set 'client_internal_ids' --- 62.13s
my-service : Set 'client_internal_ids' --- 61.73s

任务很简单:

- name: "Set 'client_internal_ids'"
  set_fact:
    client_internal_ids: "{{ client_internal_ids|default({}) | combine ( { item.clientId: item.id } ) }}"
  no_log: true
  with_items:
    - "{{ all_clients_response.json }}"

这就是为什么我创建一个专用插件来使用简单的过滤器转换字典内联(在 filter_plugins下):


def items2dict(input: any, key: any, value: any = None):
    """Converts items to a single dict without using with_items|loop|combine"""
    target_dict = {}

    if isinstance(input, list):
        source = input
    elif isinstance(input, dict):
        source = input.items()
    else:
        source = input.__dict__.items()

    for item in source:
        if key in item:
            key_val = item[key]
        else:
            key_val = key

        if value in item:
            value_val = item[value]
        else:
            value_val = value

        target_dict[key_val] = value_val

    return target_dict

usage:

- name: "Set 'client_internal_ids'"
  set_fact:
    client_internal_ids: "{{ all_clients_response.json | items2dict('clientId','id') }}"
  no_log: true

where client> clientId 是项目密钥和 ID 项目值。

该任务不再显示在分析列表中。

I have serious performance issues with with_items, these tasks are the most expensive single tasks of the whole runbook.

my-service : Set 'client_internal_ids' --- 62.13s
my-service : Set 'client_internal_ids' --- 61.73s

and the task is quite simple:

- name: "Set 'client_internal_ids'"
  set_fact:
    client_internal_ids: "{{ client_internal_ids|default({}) | combine ( { item.clientId: item.id } ) }}"
  no_log: true
  with_items:
    - "{{ all_clients_response.json }}"

That's why I create a dedicated plugin to convert a dictionary inline using a simple filter (under filter_plugins):


def items2dict(input: any, key: any, value: any = None):
    """Converts items to a single dict without using with_items|loop|combine"""
    target_dict = {}

    if isinstance(input, list):
        source = input
    elif isinstance(input, dict):
        source = input.items()
    else:
        source = input.__dict__.items()

    for item in source:
        if key in item:
            key_val = item[key]
        else:
            key_val = key

        if value in item:
            value_val = item[value]
        else:
            value_val = value

        target_dict[key_val] = value_val

    return target_dict

Usage:

- name: "Set 'client_internal_ids'"
  set_fact:
    client_internal_ids: "{{ all_clients_response.json | items2dict('clientId','id') }}"
  no_log: true

where clientId is the item key and id the item value.

The task doesn't show up in the profiling list anymore.

使用大型YAML VAR时慢速可观的性能

三人与歌 2025-02-07 18:45:07

将最大宽度更改为宽度:100%;进入.text机构并将其放入中心添加显示:flex;

.textbody {
    margin-top: 10vh;
    font-family: "Source Sans Pro", sans-serif;
    font-weight: bold;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100%;
    display: flex;
    justify-content: center;
    color: white;
}

Change max-width to width : 100%; into the .textbody and to put it in center add display: flex;

.textbody {
    margin-top: 10vh;
    font-family: "Source Sans Pro", sans-serif;
    font-weight: bold;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100%;
    display: flex;
    justify-content: center;
    color: white;
}

为什么我的文字在一定宽度上进行垂直?

三人与歌 2025-02-07 07:21:28

问题解决了

什么问题是什么?

问题是在关闭或离开应用程序后重新打开应用程序时,重新创建了主要碎片,并带有新的模糊背景和新的自定义对话框。
broadcastreceiver 存储在旧的主碎片中,因此它转介到旧视图(旧视图和对话框视图)
旧视图的可见性已经改变,但新视图没有变化,因此可见性状态变化对用户不可见。

但这不是全部。后来,我发现除了所有这些,即使我指的是正确的视图并尝试显示它,它也没有显示,并且发现了另一个问题 - 我尝试过早地更改其可见性状态。

解决方案

解决非常简单。
我要做的就是使模糊背景和自定义对话框静态,因此每次创建主碎片时都不会重新创建。然后,用户可以看到他们的可见性状态变化。

下半部分的解决方案甚至更容易 - 我要做的就是命令调用该方法以显示 runnable 中的对话框,并由 handler延迟运行。 10毫秒的延迟已经完成了这项工作。

尽管此线程的问题现在已经解决,但 this 问题仍然不是。

注意自我的注意

是一个好习惯,就是要思考,知道我应该静态的物体,这样的事情就不会经常发生

Problem Solved

What was the issue all about?

The problem was when re-opening the app after closing or leaving it, the main-fragment was re-created, and with it a new blur-background and a new custom dialog.
The BroadcastReceiver was stored in the old main-fragment, and so it referred to the old views (the old blur and dialog views)
The old views' visibility has changed, but the new ones didn't, so the visibility state change wasn't visible to the user.

But that's not all. Later on, I discovered that in addition to all that, even if I refer to the right view and try to display it, it's not displaying, and I found another problem - I try to change its visibility state too early.

Solution

Solving it was quite simple.
All I had to do was make the blur-background and the custom dialog static, so they'll not re-create every time a main-fragment is created. Then Their visibility state changes were visible to the user.

And the solution for the second half of the problem was even easier - all I had to do is put the command calling the method to show the dialog inside a Runnable, running in delay by a Handler. 10 ms of delay has done the job.

Although this thread's issue is solved by now, this issue still isn't.

Note to self

A good habit is to think ahead, knowing what objects I should set static, so that stuff like this won't happen frequently

Android:视图设置为视图。可见但视图不可见

三人与歌 2025-02-07 03:29:49

如果我正确理解的话,您想要完成的工作是将数组动态分为块,如果我的假设正确,则可以使用此助手

function ChunkArray {
    param([int] $Chunks)

    [ref] $ref = 0
    $toProcess = @($input)
    $groupSize = [math]::Ceiling($toProcess.Count / $Chunks)
    $tag = ''
    while($Chunks) {
        $Chunks = $Chunks / 10
        $tag += 0
    }
    $toProcess | Group-Object {
        "Chunk{0:$tag}" -f [math]::Floor($ref.Value++ / $groupSize)
    }
}

/powershell/module/microsoft.powershell.core/about/about/about/about_functions?view=powershell-7.2“ rel =“ nofollow noreferrer”> function> function> function > $ input 将IT/组 splin/group 纳入传递给 chunks 参数的参数,例如,使用您的数组 $ a 来自您的问题:

PS /> $chunks = $a | ChunkArray -Chunks 8
PS /> $chunks | Format-Table

Count Name         Group
----- ----         -----
    6 Chunk00      {alocf, arbmi, ausbt, auspg…}
    6 Chunk01      {cltcr, cwnfl, dkdsd, dttsd…}
    6 Chunk02      {grrgv, grrym, hbgno, hopkn…}
    6 Chunk03      {housa, irvbp, jeftb, lnhmd…}
    6 Chunk04      {mkeav, msnav, msndd, mspav…}
    6 Chunk05      {omaha, phxbh, pitns, rbkca…}
    6 Chunk06      {rstev, rstss, rvrgr, scfwi…}
    4 Chunk07      {scvnm, tmbpw, tpafa, wakny}

# Inspecting the 4th chunk:
PS /> $chunks[3].Group

housa
irvbp
jeftb
lnhmd
mcnbn
mkcrd

If I understood correctly, what you're looking to accomplish is to dynamically split an array into chunks, if my assumption is correct, you could use this helper function:

function ChunkArray {
    param([int] $Chunks)

    [ref] $ref = 0
    $toProcess = @($input)
    $groupSize = [math]::Ceiling($toProcess.Count / $Chunks)
    $tag = ''
    while($Chunks) {
        $Chunks = $Chunks / 10
        $tag += 0
    }
    $toProcess | Group-Object {
        "Chunk{0:$tag}" -f [math]::Floor($ref.Value++ / $groupSize)
    }
}

This function can take your array from pipeline using the automatic variable $input and split it / group it into the argument passed to the -Chunks parameter, for example, using your array $a from your question:

PS /> $chunks = $a | ChunkArray -Chunks 8
PS /> $chunks | Format-Table

Count Name         Group
----- ----         -----
    6 Chunk00      {alocf, arbmi, ausbt, auspg…}
    6 Chunk01      {cltcr, cwnfl, dkdsd, dttsd…}
    6 Chunk02      {grrgv, grrym, hbgno, hopkn…}
    6 Chunk03      {housa, irvbp, jeftb, lnhmd…}
    6 Chunk04      {mkeav, msnav, msndd, mspav…}
    6 Chunk05      {omaha, phxbh, pitns, rbkca…}
    6 Chunk06      {rstev, rstss, rvrgr, scfwi…}
    4 Chunk07      {scvnm, tmbpw, tpafa, wakny}

# Inspecting the 4th chunk:
PS /> $chunks[3].Group

housa
irvbp
jeftb
lnhmd
mcnbn
mkcrd

powershell:为变量分配多个值,但后来呼叫一半?

三人与歌 2025-02-06 15:35:38

我相信您的目标如下。

  • 您想从特定文件夹下每个电子表格的列“ B”列检索值。
  • 您想将检索到的值放在目标表的列“ A”列。

修改点:

  • 关于,但是当我运行脚本时,它仅在电子表格中放置1个数据点,而不是所有数据点。,当我看到您的脚本时,始终将检索到的值放在目标表的“ A2”单元格。我认为这可能是您问题的原因。

  • 在您的脚本中,我认为当使用以下流程时,过程成本将变得较低。通过此流程,您的问题也可以删除。

  • 在您的情况下,即使不使用板API,脚本也可能使用 getValues()

当这些要点反映在您的脚本中时,如下所示。

修改后的脚本:

请设置文件夹ID和目标电子表格ID。

function pullTogether() {
  // Retrieve values from each Spreadsheet.
  var values = [];
  var files = DriveApp.getFolderById('Folder ID').searchFiles(`title != 'nothing' and mimeType='${MimeType.GOOGLE_SHEETS}'`);
  var sheetName = 'Sheet1'
  while (files.hasNext()) {
    var xFile = files.next();
    var sheet = SpreadsheetApp.open(xFile).getSheetByName(sheetName);
    if (sheet) {
      var v = sheet.getRange("B2:B" + sheet.getLastRow()).getValues();
      values = [...values, ...v];
    }
  }

  // Put values to the destination sheet.
  var ss = SpreadsheetApp.openById("ID of new spreadsheet"); //I have the real ID in my code
  var dstSheet = ss.getSheets()[0];
  dstSheet.getRange(2, 1, values.length, values[0].length).setValues(values);
}

注意:

  • 尽管我不确定您的实际情况,但是当上述脚本不使用大数据时,请按以下方式进行修改。

    • 来自

        dstsheet.getRange(2,1,values.length,values [0] .length).setValues(values);
       
    • to

        sheets.spreadsheets.values.update({values},ss.getId(),`'$ {dstsheet.getSheetName()}'!a2'!
       

文献:

I believe your goal is as follows.

  • You want to retrieve the values from the column "B" of each Spreadsheet under the specific folder.
  • You want to put the retrieved values to the column "A" of the destination sheet.

Modification points:

  • About but when I run my script, it only puts 1 data point in the spreadsheet instead of all of them., when I saw your script, the retrieved value is always put to the cell "A2" of the destination sheet. I think that this might be the reason for your issue.

  • In your script, I thought that when the following flow is used, the process cost will become low. By this flow, your issue can be also removed.

  • In your situation, even when Sheets API is not used, the script might work using getValues().

When these points are reflected in your script, it becomes as follows.

Modified script:

Please set the folder ID and the destination Spreadsheet ID.

function pullTogether() {
  // Retrieve values from each Spreadsheet.
  var values = [];
  var files = DriveApp.getFolderById('Folder ID').searchFiles(`title != 'nothing' and mimeType='${MimeType.GOOGLE_SHEETS}'`);
  var sheetName = 'Sheet1'
  while (files.hasNext()) {
    var xFile = files.next();
    var sheet = SpreadsheetApp.open(xFile).getSheetByName(sheetName);
    if (sheet) {
      var v = sheet.getRange("B2:B" + sheet.getLastRow()).getValues();
      values = [...values, ...v];
    }
  }

  // Put values to the destination sheet.
  var ss = SpreadsheetApp.openById("ID of new spreadsheet"); //I have the real ID in my code
  var dstSheet = ss.getSheets()[0];
  dstSheet.getRange(2, 1, values.length, values[0].length).setValues(values);
}

Note:

  • Although I'm not sure about your actual situation, when the above script didn't work by the large data, please modify as follows.

    • From

        dstSheet.getRange(2, 1, values.length, values[0].length).setValues(values);
      
    • To

        Sheets.Spreadsheets.Values.update({ values }, ss.getId(), `'${dstSheet.getSheetName()}'!A2`, { valueInputOption: "USER_ENTERED" });
      

References:

应用脚本新的Google Sheet Creation问题

三人与歌 2025-02-06 13:41:45

Erin的方法已更新为Swift 3,这显示了从今天开始的几天(无视一天中的时间)

func daysBetweenDates( endDate: Date) -> Int 
    let calendar: Calendar = Calendar.current 
    let date1 = calendar.startOfDay(for: Date()) 
    let date2 = calendar.startOfDay(for: secondDate) 
    return calendar.dateComponents([.day], from: date1, to: date2).day! 
}

Erin's method updated to Swift 3, This shows days from today (disregarding time of day)

func daysBetweenDates( endDate: Date) -> Int 
    let calendar: Calendar = Calendar.current 
    let date1 = calendar.startOfDay(for: Date()) 
    let date2 = calendar.startOfDay(for: secondDate) 
    return calendar.dateComponents([.day], from: date1, to: date2).day! 
}

两个NSDATES之间的迅速日子

三人与歌 2025-02-06 03:00:36

打开AppGallery搜索“ HMS Core”,然后单击“更新”按钮以将您的HMS Core版本升级到最新版本。

您也可以直接从华为官方网站下载HMS Core。

https://www.huaweicicentral.com/ -latest-hms-core-apk-34/

下载后,您可以直接安装它。

然后重试用帐户套件。如果您仍然有问题,请参考以下官方帐户套件演示并尝试。

然后再试一次以获取应用程序内购买套件。如果您仍然有问题,请参考以下官方IAP套件演示并尝试。

Open AppGallery to search "hms core", then click UPDATE button to upgrade your hms core version to the latest version.

you can also download hms core directly from huawei official website as below.

https://www.huaweicentral.com/download-the-latest-hms-core-apk-34/

After your download you can directly install it.

enter image description here

Then try again for account kit. if you still have issue, pls refer to below official account kit demo and try.

https://developer.huawei.com/consumer/en/doc/development/HMSCore-Examples/client-sample-code-0000001050048970

Then try again for in-app purchase kit. if you still have issue, pls refer to below official iap kit demo and try.

https://developer.huawei.com/consumer/en/doc/development/HMSCore-Examples/client-sample-code-0000001050143598

华为帐户套件不起作用。可能的解决方案是什么?

三人与歌 2025-02-05 05:41:26

一个简单的解决方案就是这样:

m = 'first, second, third'
print (m.replace(', ', '\n'))

确保在替换逗号之后包含空间,否则您最终会陷入困境。

A simple solution would be like this:

m = 'first, second, third'
print (m.replace(', ', '\n'))

make sure to include the space after the comma in the replace or you will end up with indents.

如何将字符串分为Python中的多行?

三人与歌 2025-02-05 05:08:58

尝试以下操作:

<style type="text/css">
    body{
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
         background-image: url("/img/indexbackground.png");
    }

</style>

否则,您的链接中可能存在一些语法问题。
并且更改代码后不要忘记保存您的代码。

Try this:

<style type="text/css">
    body{
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
         background-image: url("/img/indexbackground.png");
    }

</style>

Otherwise there may be some syntax problems in your link.
And don't forget to save your code after you changed it.

无法使用CSS更改背景图像

三人与歌 2025-02-04 16:39:56

file_get_contents('http://ytinfo.ezyro.com/?id=0wo5uuwhz3o')正在返回以下html:

<html>

<body>
  <script type="text/javascript" src="/aes.js"></script>
  <script>
    function toNumbers(d) {
      var e = [];
      d.replace(/(..)/g, function(d) {
        e.push(parseInt(d, 16))
      });
      return e
    }

    function toHex() {
      for (var d = [], d = 1 == arguments.length && arguments[0].constructor == Array ? arguments[0] : arguments, e = "", f = 0; f < d.length; f++) e += (16 > d[f] ? "0" : "") + d[f].toString(16);
      return e.toLowerCase()
    }
    var a = toNumbers("f655ba9d09a112d4968c63579db590b4"),
      b = toNumbers("98344c2eee86c3994890592585b49f80"),
      c = toNumbers("d72fb33abc28df4430f7b7643e8aeda2");
    document.cookie = "__test=" + toHex(slowAES.decrypt(c, 2, a, b)) + "; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";
    location.href = "http://ytinfo.ezyro.com/?id=0WO5uUWHz3o&i=1";
  </script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body>

</html>

如您所见,它正在创建一个具有加密值的cookie,然后重新装饰页面使用附加 i = 1 参数。该服务器大概是在检查该曲奇值,并且只有在找到它时返回JSON。

cookie的值应为 49262D78C44EED05B1683AFBC9B5364F ,您可以在 file> file_get_contents()中添加。

$context = stream_context_create([
    'http' => [
        'header' => "Cookie: __test=49262d78c44eed05b1683afbc9b5364f\r\n"
    ]
]);
$y = json_decode(file_get_contents('http://ytinfo.ezyro.com/?id=0WO5uUWHz3o&i=1', false, $context));

file_get_contents('http://ytinfo.ezyro.com/?id=0WO5uUWHz3o') is returning the following HTML:

<html>

<body>
  <script type="text/javascript" src="/aes.js"></script>
  <script>
    function toNumbers(d) {
      var e = [];
      d.replace(/(..)/g, function(d) {
        e.push(parseInt(d, 16))
      });
      return e
    }

    function toHex() {
      for (var d = [], d = 1 == arguments.length && arguments[0].constructor == Array ? arguments[0] : arguments, e = "", f = 0; f < d.length; f++) e += (16 > d[f] ? "0" : "") + d[f].toString(16);
      return e.toLowerCase()
    }
    var a = toNumbers("f655ba9d09a112d4968c63579db590b4"),
      b = toNumbers("98344c2eee86c3994890592585b49f80"),
      c = toNumbers("d72fb33abc28df4430f7b7643e8aeda2");
    document.cookie = "__test=" + toHex(slowAES.decrypt(c, 2, a, b)) + "; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";
    location.href = "http://ytinfo.ezyro.com/?id=0WO5uUWHz3o&i=1";
  </script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body>

</html>

As you can see, it's creating a cookie with an encrypted value, then reloading the page with the additional i=1 parameter. The server is presumably checking for that that cookie value, and only returns the JSON when it finds it.

The value of the cookie should be 49262d78c44eed05b1683afbc9b5364f, you can add that in your file_get_contents().

$context = stream_context_create([
    'http' => [
        'header' => "Cookie: __test=49262d78c44eed05b1683afbc9b5364f\r\n"
    ]
]);
$y = json_decode(file_get_contents('http://ytinfo.ezyro.com/?id=0WO5uUWHz3o&i=1', false, $context));

为什么我可以在PHP中使用此站点的File_get_contents获取文件内容

三人与歌 2025-02-04 15:53:55

$ home/.vim/plugin )中

function Send_to_Pane(text)
  if !exists("g:tmux_target")
    call Tmux_Vars()
  end
  echo system("tmux send-keys -t " . g:tmux_target . " '" . substitute(a:text, "'", "'\\\\''", 'g') . "'")
endfunction

function Tmux_Pane_Names(A,L,P)
  return system("tmux list-panes -a | awk '/active/ {printf \"%s:%s\n\", $1, $2}' FS=:")
endfunction

function Tmux_Vars()
  if !exists("g:tmux_target")
    let g:tmux_target = "%1"
  end
  let g:tmux_target = input("session:window.pane> ", "%1", "custom,Tmux_Pane_Names")
endfunction

vmap <C-c><C-c> "ry :call Send_to_Pane(@r)<CR>
nmap <C-c><C-c> vip<C-c><C-c>
nmap <C-c>v :call Tmux_Vars()<CR>

,在vim中,如果您键入&lt; cc&gt;&gt;&gt;&lt; cc&gt; ,当前段落将被发送到窗格(假设 vim 是使用 textObjects 启用功能构建的)。在视觉模式下,将发送选定的文本。要仅发送当前行,您可以通过执行 v&lt; cc&gt;&lt; cc&gt; 来使用线路视觉。 ( vim 实际上没有对线路文本对象的内置支持,但是有可用的插件。)

请注意,可以通过在运行中运行的过程中检查$ tmux_pane可以轻松确定目标窗格的正确值那个窗格。您可以使用 0:2.1 之类的特定目标,但是上面使用%1 作为默认值。这可能是一个不好的默认值。 YMMV

With some minor tweaks to slime.vim, you can do this by putting the following file in your vim plugin dir (eg $HOME/.vim/plugin)

function Send_to_Pane(text)
  if !exists("g:tmux_target")
    call Tmux_Vars()
  end
  echo system("tmux send-keys -t " . g:tmux_target . " '" . substitute(a:text, "'", "'\\\\''", 'g') . "'")
endfunction

function Tmux_Pane_Names(A,L,P)
  return system("tmux list-panes -a | awk '/active/ {printf \"%s:%s\n\", $1, $2}' FS=:")
endfunction

function Tmux_Vars()
  if !exists("g:tmux_target")
    let g:tmux_target = "%1"
  end
  let g:tmux_target = input("session:window.pane> ", "%1", "custom,Tmux_Pane_Names")
endfunction

vmap <C-c><C-c> "ry :call Send_to_Pane(@r)<CR>
nmap <C-c><C-c> vip<C-c><C-c>
nmap <C-c>v :call Tmux_Vars()<CR>

Now, in vim, if you type <C-c><C-c>, the current paragraph will be sent to the pane (assuming vim was built with the textobjects feature enabled). In visual mode, the selected text will be sent. To send just the current line, you can use linewise-visual by doing V<C-c><C-c>. (vim doesn't really have builtin support for linewise text objects, but there are plugins available.)

Note that the correct value for the target pane can easily be determined by inspecting $TMUX_PANE in the process running in that pane. You can use specific targets like 0:2.1, but the above uses %1 as a default. This is probably a bad default to use. YMMV

将VIM上的线发送到另一个窗格或TMUX中的部分

三人与歌 2025-02-04 13:45:41

@danh Si右边 i-1

此外,还有另一个错误:
让点= []; 可能是全局,否则列表将通过每个调用重置。

目前尚不清楚 w()函数有什么,但是您应该仔细检查返回的值有效。

这是您的代码的调整版本,上述注释已应用:

let points = [];
  
function setup() {
  createCanvas(300, 300);
}

function draw() {
  irregularCircle(3200);
}

function irregularCircle(limit) {
  let t = frameCount / 20
  let i = floor(t)
  if (frameCount < limit) {
    let radius = 250;
    let x = width/2 + radius*cos(t)*noise(t/2)
    let y = height/2 + radius*sin(t)*noise(t/2)
    let point = createVector(x,y)
    points.push(point)
    let pt = points[i]
    let old_pt = points[i > 0 ? i-1 : 0]
    stroke(24,34,64,75)
    strokeWeight(0.1);
    if (frameCount > 1 && frameCount < limit) {
      line(pt.x,pt.y,old_pt.x,old_pt.y)
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>

由于您将上点连接到当前点,因此您可能不需要将点附加到列表中:您只需保留对上点的引用:

let oldPt;
  
function setup() {
  createCanvas(300, 300);
}

function draw() {
  irregularCircle(3200);
}

function irregularCircle(limit) {
  let t = frameCount / 20
  let i = floor(t)
  if (frameCount < limit) {
    let radius = 250;
    let x = width/2 + radius*cos(t)*noise(t/2)
    let y = height/2 + radius*sin(t)*noise(t/2)
    let pt = createVector(x,y)
    // check if the previous point exists before drawing a line
    if(oldPt){
      if (frameCount > 1 && frameCount < limit) {
        line(pt.x,pt.y,oldPt.x,oldPt.y)
      }
    }
    // now that we've drawn the line we can point the old point to the current point
    oldPt = pt;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>

@danh si right about i-1.

Additionally there another error:
let points = []; should probably be global, otherwise the list gets reset with each call.

It's unclear what the w() function does, but you should double check the values returned are valid.

Here's a tweaked version of your code with the above notes applied:

let points = [];
  
function setup() {
  createCanvas(300, 300);
}

function draw() {
  irregularCircle(3200);
}

function irregularCircle(limit) {
  let t = frameCount / 20
  let i = floor(t)
  if (frameCount < limit) {
    let radius = 250;
    let x = width/2 + radius*cos(t)*noise(t/2)
    let y = height/2 + radius*sin(t)*noise(t/2)
    let point = createVector(x,y)
    points.push(point)
    let pt = points[i]
    let old_pt = points[i > 0 ? i-1 : 0]
    stroke(24,34,64,75)
    strokeWeight(0.1);
    if (frameCount > 1 && frameCount < limit) {
      line(pt.x,pt.y,old_pt.x,old_pt.y)
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>

Since you're connecting the previous point to the current point, you might not need to keep appending points to a list: you can simply hold a reference to the previous point instead:

let oldPt;
  
function setup() {
  createCanvas(300, 300);
}

function draw() {
  irregularCircle(3200);
}

function irregularCircle(limit) {
  let t = frameCount / 20
  let i = floor(t)
  if (frameCount < limit) {
    let radius = 250;
    let x = width/2 + radius*cos(t)*noise(t/2)
    let y = height/2 + radius*sin(t)*noise(t/2)
    let pt = createVector(x,y)
    // check if the previous point exists before drawing a line
    if(oldPt){
      if (frameCount > 1 && frameCount < limit) {
        line(pt.x,pt.y,oldPt.x,oldPt.y)
      }
    }
    // now that we've drawn the line we can point the old point to the current point
    oldPt = pt;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>

用一系列点绘制一个不规则的圆圈

三人与歌 2025-02-04 12:20:40

您正在尝试在实际加载图像之前渲染图像。您应该将 image Succecallback image> Image 函数的参数中调用。

function imageLoaded() {
    document.querySelector('main').classList.remove('hidden')
    document.querySelector('#load').classList.add('hidden')
    const url = document.querySelector('#file').value;
    loadImage(url, (img) => image(img, 0, 0, 400, 400));
}

You're trying to render the image before it is actually loaded. You should put the image call in the successCallback parameter of the image function.

function imageLoaded() {
    document.querySelector('main').classList.remove('hidden')
    document.querySelector('#load').classList.add('hidden')
    const url = document.querySelector('#file').value;
    loadImage(url, (img) => image(img, 0, 0, 400, 400));
}

p5.j​​s图像未显示

三人与歌 2025-02-03 12:42:58

如果要按降序排序数据,请使用sorted(),只需在排序函数中添加反向= true,但是它允许您一次仅对一个列进行排序。

from prettytable import from_csv
import csv, operator

with open('test.txt', 'r') as open_file:
  table_file = from_csv(open_file)
print(table_file)
 
srt =  sorted(data, key=operator.itemgetter(2), reverse=True) 
print(st)

或者,您可以使用Pandas,

from prettytable import from_csv
import csv, operator
import pandas as pd


with open('test.txt', 'r') as open_file:
    table_file = from_csv(open_file)
print(table_file)
srt = table_file.sort_values(["Age"], axis=0, ascending=[False], inplace=True)
print(st)


希望能为您提供帮助。

use sorted() if you want to sort data in descending order, just add reverse=True in sorted function but it allows you to sort only one column at a time.

from prettytable import from_csv
import csv, operator

with open('test.txt', 'r') as open_file:
  table_file = from_csv(open_file)
print(table_file)
 
srt =  sorted(data, key=operator.itemgetter(2), reverse=True) 
print(st)

or you can use pandas

from prettytable import from_csv
import csv, operator
import pandas as pd


with open('test.txt', 'r') as open_file:
    table_file = from_csv(open_file)
print(table_file)
srt = table_file.sort_values(["Age"], axis=0, ascending=[False], inplace=True)
print(st)


I hope that gonna helps you .

如何根据特定列(python中的比例和下降)对表进行分类

三人与歌 2025-02-03 09:33:37

您目前正在做的是为每个 p标签中的每个样式更改

我会建议您有一个自定义类,该类返回您的 div标签,其中包含p标签

具有包含 card样式 text 将显示。通过数组映射并返回样式和标签。如下所示。

处理自定义Div中的点击事件。

import React from 'react';
import "./game.css";
import MyDiv from './MyDiv';


const cards = [{ cardStyle: 'card-1', text: "Win" },
{ cardStyle: 'card-2', text: 'Sorry, No Win' },
{ cardStyle: 'card-3', text: 'Sorry, NoWin' }];


function Game() {
    return (
        <div className="cards">

            {cards.map((card, index) =>
            (<MyDiv cardNumberStyle={card.cardStyle}
                key={index}
               
                textToDisplay={card.text} />))
            }
        </div>
    );
}





export default Game;

然后mydiv是:

import React, { useState } from "react";

const MyDiv = ({ cardNumberStyle, textToDisplay }) => {
    const [styling, setStyling] = useState('card-content');

    ///Handles clicks
    const handleClick = () => {
        //conditionally change the styling
        if (styling === 'card-content')
            setStyling('card-content-2')
        else setStyling('card-content');

    }

    return (
        <div className={`cardDisplay ${cardNumberStyle}`} onClick={handleClick}>
            <p className={styling}>{textToDisplay}</p>
        </div>
    );
}

export default MyDiv;

What you are currently doing is changing the styling for each of the p tags.

I will advise you have a custom class that returns your div tag that contains the p tag

Have an array of Objects that contain the card style and the text that will be displayed. Map through the array and return the style and tags accordingly. As displayed below.

handle the click events in the custom div.

import React from 'react';
import "./game.css";
import MyDiv from './MyDiv';


const cards = [{ cardStyle: 'card-1', text: "Win" },
{ cardStyle: 'card-2', text: 'Sorry, No Win' },
{ cardStyle: 'card-3', text: 'Sorry, NoWin' }];


function Game() {
    return (
        <div className="cards">

            {cards.map((card, index) =>
            (<MyDiv cardNumberStyle={card.cardStyle}
                key={index}
               
                textToDisplay={card.text} />))
            }
        </div>
    );
}





export default Game;

And then MyDiv is:

import React, { useState } from "react";

const MyDiv = ({ cardNumberStyle, textToDisplay }) => {
    const [styling, setStyling] = useState('card-content');

    ///Handles clicks
    const handleClick = () => {
        //conditionally change the styling
        if (styling === 'card-content')
            setStyling('card-content-2')
        else setStyling('card-content');

    }

    return (
        <div className={`cardDisplay ${cardNumberStyle}`} onClick={handleClick}>
            <p className={styling}>{textToDisplay}</p>
        </div>
    );
}

export default MyDiv;

当单击按钮时,如何使用E.Target的React中的各个元素添加样式?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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