空城缀染半城烟沙

文章 评论 浏览 34

空城缀染半城烟沙 2025-02-21 02:07:09

鉴于新的症状(崩溃是从CMDNext返回之后),播放处理程序返回后的队列上运行:

// NOTE: As Christopher Richmond commented, move this to a place that is only called once.
audio.PlaybackEnded += SafePlayNext;
...

private void SafePlayNext(object sender, EventArgs e)
{
    // Queue to run after return.
    Device.BeginInvokeOnMainThread(() =>
        cmdNextClicked(null, null));   // Arguments not used, `null` works fine.
}

说明:启动另一个音频显然是 disposes 。原始代码启动了另一个音频,然后处理程序结束,然后返回到该音频的播放事件处理器。在该处置的音频上可以访问一些东西。因此处置了例外。

以上代码将 cmdnextClicked 调用到Mainthread队列,然后立即返回到该音频的播放。因此,在要求下一个音频之前,它有机会完成。

Given the new symptom (crash happens after return from cmdNext), queue to run after PlaybackEnded handler returns:

// NOTE: As Christopher Richmond commented, move this to a place that is only called once.
audio.PlaybackEnded += SafePlayNext;
...

private void SafePlayNext(object sender, EventArgs e)
{
    // Queue to run after return.
    Device.BeginInvokeOnMainThread(() =>
        cmdNextClicked(null, null));   // Arguments not used, `null` works fine.
}

EXPLANATION: Starting another audio apparently disposes the previous audio. Original code started another audio, then handler ends, and returns to that audio's PlaybackEnded event processor. Something is accessed on that disposed audio. Thus the disposed Exception.

The above code puts the cmdNextClicked call on to MainThread's queue, then immediately returns to that audio's PlaybackEnded. Which thus has a chance to finish, before the next audio is asked for.

音频播放器会自动处置

空城缀染半城烟沙 2025-02-20 11:54:45

递归蛮力解决方案

def sliding_triangle(triangle, row = 0, index = 0):
    if row >= len(triangle) or index >= len(triangle[row]):
        return 0      # row or index out of bounds
    
    # Add parent value to max of child triangles
    return triangle[row][index] + max(sliding_triangle(triangle, row+1, index), sliding_triangle(triangle, row+1, index+1))

测试

print(sliding_triangle([[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]]))
# Output: 23

print(sliding_triangle([
            [75],
            [95, 64],
            [17, 47, 82],
            [18, 35, 87, 10],
            [20,  4, 82, 47, 65],
            [19,  1, 23, 75,  3, 34],
            [88,  2, 77, 73,  7, 63, 67],
            [99, 65,  4, 28,  6, 16, 70, 92],
            [41, 41, 26, 56, 83, 40, 80, 70, 33],
            [41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
            [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
            [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
            [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
            [63, 66,  4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
            [ 4, 62, 98, 27, 23,  9, 70, 98, 73, 93, 38, 53, 60,  4, 23],
            ]))
# Output: 1074

,但是,蛮力进近时间在 larges数据集

优化解决方案

将记忆应用于蛮力解决方案。

  • 使用缓存来避免反复求解父母的子路径

code

def sliding_triangle(triangle):
    ' Wrapper setup function '
    def sliding_triangle_(row, index):
        ' Memoized function which does the calcs'
        if row >= len(triangle) or index >= len(triangle[row]):
            return 0
        if not (row, index) in cache:
             # Update cache
             cache[(row, index)] = (triangle[row][index] + 
                                    max(sliding_triangle_(row+1, index), 
                                        sliding_triangle_(row+1, index+1)))
        return cache[(row, index)]
    cache = {}     # init cache
    return sliding_triangle_(0, 0)  # calcuate starting from top most node

测试

查找并显示最佳路径*

  • 修改野蛮力量返回路径
  • 显示三角形的路径在三角形

code 中突出显示路径

####### Main function
def sliding_triangle_path(triangle, row = 0, index = 0, path = None):
    '''
        Finds highest scoring path (using brute force)
    '''
    if path is None:
        path = [(0, 0)]                   # Init path with top most triangle node

    if row >= len(triangle) or index >= len(triangle[row]):
        path.pop()                        # drop last item since place out of bounds
        return path
    
    # Select best path of child nodes
    path_ = max(sliding_triangle_path(triangle, row+1, index, path + [(row+1, index)]), 
           sliding_triangle_path(triangle, row+1, index+1, path + [(row+1, index+1)]), 
           key = lambda p: score(triangle, p))
    
    return path_

####### Utils
def getter(x, args):
    '''
        Gets element of multidimensional array using tuple as index
        Source (Modified): https://stackoverflow.com/questions/40258083/recursive-itemgetter-for-python
    '''
    try:
        for k in args:
            x = x[k]
        return x
    
    except IndexError:
        return 0

def score(tri, path):
    ' Score for a path through triangle tri '
    return sum(getter(tri, t) for t in path)


def colored(r, g, b, text):
    '''
        Use rgb code to color text'
        Source: https://www.codegrepper.com/code-examples/python/how+to+print+highlighted+text+in+python
    '''
    return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)

def highlight_path(triangle, path):
    ' Created string that highlight path in red through triangle'
    result = ""                  # output string
    for p in path:               # Looop over path tuples
        row, index = p        
        values = triangle[row]   # corresponding values in row 'row' of triangle
        
        # Color in red path value at index, other values are in black (color using rgb)
        row_str = ' '.join([colored(255, 0, 0, str(v)) if i == index else colored(0, 0, 0, str(v)) for i, v in enumerate(values)])
        result += row_str + '\n'
        
    return result

test

# Test
triangle = ([
            [75],
            [95, 64],
            [17, 47, 82],
            [18, 35, 87, 10],
            [20,  4, 82, 47, 65],
            [19,  1, 23, 75,  3, 34],
            [88,  2, 77, 73,  7, 63, 67],
            [99, 65,  4, 28,  6, 16, 70, 92],
            [41, 41, 26, 56, 83, 40, 80, 70, 33],
            [41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
            [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
            [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
            [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
            [63, 66,  4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
            [ 4, 62, 98, 27, 23,  9, 70, 98, 73, 93, 38, 53, 60,  4, 23],
            ])


path = sliding_triangle_path(triangle)
print(f'Score: {score(tri, path)}')
print(f"Path\n {'->'.join(map(str,path))}")
print(f'Highlighted path\n {highlight_path(tri, path)}')

输出

Score: 1074
Path
 (0, 0)->(1, 1)->(2, 2)->(3, 2)->(4, 2)->(5, 3)->(6, 3)->(7, 3)->(8, 4)->(9, 5)->(10, 6)->(11, 7)->(12, 8)->(13, 8)->(14, 9)

Recursive brute force solution

def sliding_triangle(triangle, row = 0, index = 0):
    if row >= len(triangle) or index >= len(triangle[row]):
        return 0      # row or index out of bounds
    
    # Add parent value to max of child triangles
    return triangle[row][index] + max(sliding_triangle(triangle, row+1, index), sliding_triangle(triangle, row+1, index+1))

Tests

print(sliding_triangle([[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]]))
# Output: 23

print(sliding_triangle([
            [75],
            [95, 64],
            [17, 47, 82],
            [18, 35, 87, 10],
            [20,  4, 82, 47, 65],
            [19,  1, 23, 75,  3, 34],
            [88,  2, 77, 73,  7, 63, 67],
            [99, 65,  4, 28,  6, 16, 70, 92],
            [41, 41, 26, 56, 83, 40, 80, 70, 33],
            [41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
            [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
            [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
            [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
            [63, 66,  4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
            [ 4, 62, 98, 27, 23,  9, 70, 98, 73, 93, 38, 53, 60,  4, 23],
            ]))
# Output: 1074

However, brute force approach times out on larges dataset

Optimized Solution

Apply memoization to brute force solution.

  • Uses cache to avoid repeatedly solving for subpaths of a parent triangle node

Code

def sliding_triangle(triangle):
    ' Wrapper setup function '
    def sliding_triangle_(row, index):
        ' Memoized function which does the calcs'
        if row >= len(triangle) or index >= len(triangle[row]):
            return 0
        if not (row, index) in cache:
             # Update cache
             cache[(row, index)] = (triangle[row][index] + 
                                    max(sliding_triangle_(row+1, index), 
                                        sliding_triangle_(row+1, index+1)))
        return cache[(row, index)]
    cache = {}     # init cache
    return sliding_triangle_(0, 0)  # calcuate starting from top most node

Tests

Find and Show Optimal Path*

  • Modify Brute Force to Return Path
  • Show highlighted path in triangle

Code

####### Main function
def sliding_triangle_path(triangle, row = 0, index = 0, path = None):
    '''
        Finds highest scoring path (using brute force)
    '''
    if path is None:
        path = [(0, 0)]                   # Init path with top most triangle node

    if row >= len(triangle) or index >= len(triangle[row]):
        path.pop()                        # drop last item since place out of bounds
        return path
    
    # Select best path of child nodes
    path_ = max(sliding_triangle_path(triangle, row+1, index, path + [(row+1, index)]), 
           sliding_triangle_path(triangle, row+1, index+1, path + [(row+1, index+1)]), 
           key = lambda p: score(triangle, p))
    
    return path_

####### Utils
def getter(x, args):
    '''
        Gets element of multidimensional array using tuple as index
        Source (Modified): https://stackoverflow.com/questions/40258083/recursive-itemgetter-for-python
    '''
    try:
        for k in args:
            x = x[k]
        return x
    
    except IndexError:
        return 0

def score(tri, path):
    ' Score for a path through triangle tri '
    return sum(getter(tri, t) for t in path)


def colored(r, g, b, text):
    '''
        Use rgb code to color text'
        Source: https://www.codegrepper.com/code-examples/python/how+to+print+highlighted+text+in+python
    '''
    return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)

def highlight_path(triangle, path):
    ' Created string that highlight path in red through triangle'
    result = ""                  # output string
    for p in path:               # Looop over path tuples
        row, index = p        
        values = triangle[row]   # corresponding values in row 'row' of triangle
        
        # Color in red path value at index, other values are in black (color using rgb)
        row_str = ' '.join([colored(255, 0, 0, str(v)) if i == index else colored(0, 0, 0, str(v)) for i, v in enumerate(values)])
        result += row_str + '\n'
        
    return result

Test

# Test
triangle = ([
            [75],
            [95, 64],
            [17, 47, 82],
            [18, 35, 87, 10],
            [20,  4, 82, 47, 65],
            [19,  1, 23, 75,  3, 34],
            [88,  2, 77, 73,  7, 63, 67],
            [99, 65,  4, 28,  6, 16, 70, 92],
            [41, 41, 26, 56, 83, 40, 80, 70, 33],
            [41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
            [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
            [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
            [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
            [63, 66,  4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
            [ 4, 62, 98, 27, 23,  9, 70, 98, 73, 93, 38, 53, 60,  4, 23],
            ])


path = sliding_triangle_path(triangle)
print(f'Score: {score(tri, path)}')
print(f"Path\n {'->'.join(map(str,path))}")
print(f'Highlighted path\n {highlight_path(tri, path)}')

Output

Score: 1074
Path
 (0, 0)->(1, 1)->(2, 2)->(3, 2)->(4, 2)->(5, 3)->(6, 3)->(7, 3)->(8, 4)->(9, 5)->(10, 6)->(11, 7)->(12, 8)->(13, 8)->(14, 9)

Highlighted path

为什么我的循环在以后我返回时没有退出

空城缀染半城烟沙 2025-02-20 05:06:45

这是一个在MySQL 5.7上解决的毛茸茸的问题。这是一种方法:

SELECT s1.section, s1.sub_section, s1.category
FROM
(
    SELECT section, sub_section, category, COUNT(*) AS cnt
    FROM yourTable
    GROUP BY section, sub_section, category
) s1
INNER JOIN
(
    SELECT section, sub_section, MAX(cnt) AS max_cnt
    FROM
    (
        SELECT section, sub_section, category, COUNT(*) AS cnt
        FROM yourTable
        GROUP BY section, sub_section, category
    ) t
    GROUP BY section, sub_section
) s2
    ON s2.section = s1.section AND
       s2.sub_section = s1.sub_section AND
       s1.cnt = s2.max_cnt
ORDER BY s1.section, s1.sub_section, s1.category;

这是一个运行

This is a hairy problem to handle on MySQL 5.7. Here is one approach:

SELECT s1.section, s1.sub_section, s1.category
FROM
(
    SELECT section, sub_section, category, COUNT(*) AS cnt
    FROM yourTable
    GROUP BY section, sub_section, category
) s1
INNER JOIN
(
    SELECT section, sub_section, MAX(cnt) AS max_cnt
    FROM
    (
        SELECT section, sub_section, category, COUNT(*) AS cnt
        FROM yourTable
        GROUP BY section, sub_section, category
    ) t
    GROUP BY section, sub_section
) s2
    ON s2.section = s1.section AND
       s2.sub_section = s1.sub_section AND
       s1.cnt = s2.max_cnt
ORDER BY s1.section, s1.sub_section, s1.category;

Here is a running demo.

在分组结果MySQL版本5.7中获得最重复的价值

空城缀染半城烟沙 2025-02-20 02:08:41

您是否听说过 object.entries object.values object.keys.keys in and 对于循环?

const data = {
  "channel_count": "1",
  "channels": [
    {
      "logo": "default.png",
      "name": "Default Channel",
      "token": "default"
    }
  ],
  "messages": [
    {
      "2022-07-04": [
        {
          "body": "Body",
          "title": "Title"
        },
      ]
    },
    {
      "2022-07-01": [
        {
          "body": "Body",
          "title": "Title"
        }
      ]
    }
  ]
}

console.log(data.messages.flatMap(e => Object.entries(e)))

Did you heard about Object.entries, Object.values, Object.keys and for in and for of loops?

const data = {
  "channel_count": "1",
  "channels": [
    {
      "logo": "default.png",
      "name": "Default Channel",
      "token": "default"
    }
  ],
  "messages": [
    {
      "2022-07-04": [
        {
          "body": "Body",
          "title": "Title"
        },
      ]
    },
    {
      "2022-07-01": [
        {
          "body": "Body",
          "title": "Title"
        }
      ]
    }
  ]
}

console.log(data.messages.flatMap(e => Object.entries(e)))

反应本地筑巢地图而不知道钥匙

空城缀染半城烟沙 2025-02-19 23:20:55

您不能将元素添加到尚不存在的索引中。通常,正如Japhei所说,您只能将元素添加到索引较小或等于阵列长度。这意味着,如果您的ArrayList仍然为空,则只能在索引0上添加元素,或者不指定索引(只需将其添加到末端)。

您想做的是用空元素初始化arraylist。通常,我使用毫无意义的值(例如0或-1)作为整数或空字符串,具体取决于数组类型(或无效元素),然后稍后将它们填充。

但是,如果您知道自己有多少个元素,或者需要什么数尺寸,为什么不使用普通数组呢?那将是正确的方法。

You cannot add elements to indexes which do not yet exist. In general, as Japhei said, you can only add elements to indexes smaller or equal to the array length. This means, if your ArrayList is still empty, you can only add elements at index 0 or without specifying the index (which will just add it to the end).

What you want to do is initialize your ArrayList with empty elements. I normally use meaningless values like 0 or -1 for integers or empty strings depending on the array type (or null elements), and just fill them later.

But if you know how many elements you have, or what array size you need, why not just use a normal array? That would be the right way to do it.

使用.ADD(index,element)时,在arrayList中获取indexoutofBoundSexception

空城缀染半城烟沙 2025-02-19 22:08:14

我首选的方法是用 ecmascript模块

您可以将每个功能都放入单独的文件中。您可以将文件命名为您喜欢的每个文件,但是我通常在包含的函数之后将它们命名。对于Web,我将给文件一个 .js 文件扩展名。在节点中,我会给它一个 .mjs 扩展名。

在每个文件中,prepend export export 这样的功能:

export function funcName()
{
}

然后从主代码文件中,您可以 import> import 您的函数您从这些独立文件中的函数

import { funcName } from "./fileName.mjs";

之后,您可以将函数像在主代码文件中声明一样(因为现在已导入)。

My preferred way to accomplish this is with ECMAscript modules.

You can place each of those functions into a separate file. You can name the files what every you like, but I usually name them after the function it contains. For web, I'd give the file a .js file extension. In node, I'd give it a .mjs extension.

In each file, prepend export on each function like this:

export function funcName()
{
}

Then from your main code file, you can import your functions from those separate files like this:

import { funcName } from "./fileName.mjs";

After this, you can use the functions as if they were declared in your main code file (because they are now imported).

如何将可重复使用的JavaScript代码移动到单独的文件中,而不是主文件并使用几次?

空城缀染半城烟沙 2025-02-19 19:54:34

navigation.setoptions是一个函数,将对象作为输入

尝试进行此更改,并让我知道它是否已固定

navigation.setOptions({
  headerTitle: 'Demo',
})

navigation.setOptions is a function which takes object as an input

Try making this change and let me know if its fixed

navigation.setOptions({
  headerTitle: 'Demo',
})

如何进行导航。

空城缀染半城烟沙 2025-02-19 18:37:15

您应该考虑使用工具 tidy ,然后将html文件转换为xhtml。它纠正了所有这些事情。

只需与参数-ASXML进行整理。

You should consider using the tool Tidy and convert html files into xhtml. It corrects all such things.

Just run tidy with the argument -asxml.

如何处理XSLT中的HTML实体

空城缀染半城烟沙 2025-02-19 17:27:41

在映射中添加一个日期:

"lastasseceddate": {
        "type": "date" 
      }

当然,每次访问文档时,您都必须对其进行更新。显然,如果您同时连接了许多更新 /用户,则可能会遇到一些麻烦。不要忘记检查您的“刷新”设置是否可以,您也可以考虑在任何更新后也强制刷新。

要检索文档,只需按以下日期字段(DESC)进行排序。

"sort": [
    {
      "lastasseceddate": {
        "order": "desc"
      }
    }
  ]

如果您的用户在每次访问它时修改文档,则可以考虑使用Collape( https://www.elastic.co/guide/en/elasticsearch/reference/current/collapse-search-results.html

注意:
如果仅需要保留X个最后访问的文档(让S的最后5个),最好的解决方案是将ES文档保存在应用程序端的静态列表中。

Add a date in your mappings:

"lastasseceddate": {
        "type": "date" 
      }

Of course, you would have to update it each time a document is accessed. Obviously if you have many update / user connected at the same time you could have some trouble. Dont forget to check if your "refresh" settings is ok, you could consider to force refresh after any update too.

To retrieve documents, just sort by this date field (desc).

"sort": [
    {
      "lastasseceddate": {
        "order": "desc"
      }
    }
  ]

If your users modify documents each time they accessed it, you could consider use collape (https://www.elastic.co/guide/en/elasticsearch/reference/current/collapse-search-results.html)

Note:
If you need only keep the X last accessed documents (let s say the last 5), the best solution is to keep es document in a static list on application side.

Elasticsearch最近访问的文档

空城缀染半城烟沙 2025-02-19 10:25:21

在使用字符串属性时,使用

window["MyNamespace"] = window["MyNamespace"] || {};

应该是正确的,但是如果您确实想拥有一个分离的窗口并组织了代码,则可以扩展窗口对象:

interface MyNamespacedWindow extends Window {
    MyNamespace: object;
}

declare var window: MyNamespacedWindow;

Using

window["MyNamespace"] = window["MyNamespace"] || {};

should be all right as it is using a string property, but if you really want to have a separated window and organised your code, you can extend the window object:

interface MyNamespacedWindow extends Window {
    MyNamespace: object;
}

declare var window: MyNamespacedWindow;

您如何在打字稿中的“窗口”上明确设置新属性?

空城缀染半城烟沙 2025-02-19 05:25:15

要么使用。eq()它将从其索引返回元素或使用CSS选择器像:nth-​​child()

console.log($('.test').eq(3).text());
console.log($('.test:nth-child(4)').text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div class="test">div 1</div>
  <div class="test">div 2</div>
  <div class="test">div 3</div>
  <div class="test">div 4</div>
</div>

Either use .eq() that will return an element from the index of it or use a CSS selector like :nth-child().

console.log($('.test').eq(3).text());
console.log($('.test:nth-child(4)').text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div class="test">div 1</div>
  <div class="test">div 2</div>
  <div class="test">div 3</div>
  <div class="test">div 4</div>
</div>

选择具有类的任何元素&#x27;&#x27;在JS

空城缀染半城烟沙 2025-02-19 03:29:47

在这里,您有一个带有虚拟数据的示例,并使用 geom_rec 您可以选择要用某种颜色填充的背景的那一部分,更改 xmin xmax < /代码>。

library(tidyverse)

# create dummy data
data <- data.frame(
  name=letters[1:5],
  value=sample(seq(4,15),5),
  sd=c(1,0.2,3,2,4)
)

# Plot
ggplot(data) +
  geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.7) +
  geom_rect(data=NULL,aes(xmin=0.25,xmax=1.25,ymin=-Inf,ymax=Inf),
            fill="lightgreen", alpha=0.1) +
  geom_rect(data=NULL,aes(xmin=1.25,xmax=2.25,ymin=-Inf,ymax=Inf),
            fill="red", alpha=0.1) +
  geom_rect(data=NULL,aes(xmin=2.25,xmax=3.25,ymin=-Inf,ymax=Inf),
            fill="lightblue", alpha=0.1) +
  geom_rect(data=NULL,aes(xmin=3.25,xmax=4.25,ymin=-Inf,ymax=Inf),
            fill="yellow", alpha=0.1) +
  geom_errorbar(aes(x=name, ymin=value-sd, ymax=value+sd), 
                width=0.4, colour="orange", alpha=0.9, size=1.3)

输出:

Here you have an example with dummy data and using geom_rec you can select that part of the background that you want to fill with some color, changing xmin and xmax.

library(tidyverse)

# create dummy data
data <- data.frame(
  name=letters[1:5],
  value=sample(seq(4,15),5),
  sd=c(1,0.2,3,2,4)
)

# Plot
ggplot(data) +
  geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.7) +
  geom_rect(data=NULL,aes(xmin=0.25,xmax=1.25,ymin=-Inf,ymax=Inf),
            fill="lightgreen", alpha=0.1) +
  geom_rect(data=NULL,aes(xmin=1.25,xmax=2.25,ymin=-Inf,ymax=Inf),
            fill="red", alpha=0.1) +
  geom_rect(data=NULL,aes(xmin=2.25,xmax=3.25,ymin=-Inf,ymax=Inf),
            fill="lightblue", alpha=0.1) +
  geom_rect(data=NULL,aes(xmin=3.25,xmax=4.25,ymin=-Inf,ymax=Inf),
            fill="yellow", alpha=0.1) +
  geom_errorbar(aes(x=name, ymin=value-sd, ymax=value+sd), 
                width=0.4, colour="orange", alpha=0.9, size=1.3)

OUTPUT:
enter image description here

如何在GGPLOT中创建多彩背景?

空城缀染半城烟沙 2025-02-19 03:22:18

今天的表现

今天27.12.2019我在

结论

  • str.replace(/abc/g,''); c )是所有字符串的良好跨浏览器快速解决方案。
  • 基于 split-join a,b )或替换 c,d )的解决方案是
  • 基于快速解决方案的()( e,f,g,h )的速度很慢 - 通常,小字符串慢了4倍,大约3000次(
  • !解决方案( ra,rb )很慢,不适用于长字符串,

我还创建了自己的解决方案。看来目前是做问题作业的最短的:

str.split`abc`.join``

str = "Test abc test test abc test test test abc test test abc";
str = str.split`abc`.join``

console.log(str);

详细信息

测试是在Chrome 79.0,Safari 13.0.4和Firefox 71.0(64位)上进行的。测试 RA RB 使用递归。结果

短字符串 - 55个字符

可以在计算机上运行测试在这里。 Chrome的结果:

“在此处输入图像描述”

长字符串:275 000个字符

递归解决方案 ra rb 给出

连击:最大呼叫堆栈大小超过

1M字符的最大呼叫堆栈大小,甚至可以打破Chrome

”在此处输入图像描述”

我尝试为其他解决方案执行1M字符的测试,但是 e,f,g,g,h 都这样做浏览器要求我打破脚本的很多时间,所以我将测试字符串缩小到275K字符。您可以在计算机上运行测试在这里。 Chrome

“在此处输入图像说明“

测试中使用的代码

var t="Test abc test test abc test test test abc test test abc"; // .repeat(5000)
var log = (version,result) => console.log(`${version}: ${result}`);


function A(str) {
  return str.split('abc').join('');
}

function B(str) {
  return str.split`abc`.join``; // my proposition
}


function C(str) {
  return str.replace(/abc/g, '');
}

function D(str) {
  return str.replace(new RegExp("abc", "g"), '');
}

function E(str) {
  while (str.indexOf('abc') !== -1) { str = str.replace('abc', ''); }
  return str;
}

function F(str) {
  while (str.indexOf('abc') !== -1) { str = str.replace(/abc/, ''); }
  return str;
}

function G(str) {
  while(str.includes("abc")) { str = str.replace('abc', ''); }
  return str;
}

// src: https://stackoverflow.com/a/56989553/860099
function H(str)
{
    let i = -1
    let find = 'abc';
    let newToken = '';

    if (!str)
    {
        if ((str == null) && (find == null)) return newToken;
        return str;
    }

    while ((
        i = str.indexOf(
            find, i >= 0 ? i + newToken.length : 0
        )) !== -1
    )
    {
        str = str.substring(0, i) +
            newToken +
            str.substring(i + find.length);
    }
    return str;
}

// src: https://stackoverflow.com/a/22870785/860099
function RA(string, prevstring) {
  var omit = 'abc';
  var place = '';
  if (prevstring && string === prevstring)
    return string;
  prevstring = string.replace(omit, place);
  return RA(prevstring, string)
}

// src: https://stackoverflow.com/a/26107132/860099
function RB(str) {
  var find = 'abc';
  var replace = '';
  var i = str.indexOf(find);
  if (i > -1){
    str = str.replace(find, replace);
    i = i + replace.length;
    var st2 = str.substring(i);
    if(st2.indexOf(find) > -1){
      str = str.substring(0,i) + RB(st2, find, replace);
    }
  }
  return str;
}




log('A ', A(t));
log('B ', B(t));
log('C ', C(t));
log('D ', D(t));
log('E ', E(t));
log('F ', F(t));
log('G ', G(t));
log('H ', H(t));
log('RA', RA(t)); // use reccurence
log('RB', RB(t)); // use reccurence
<p style="color:red">This snippet only presents codes used in tests. It not perform test itself!<p>

Performance

Today 27.12.2019 I perform tests on macOS v10.13.6 (High Sierra) for the chosen solutions.

Conclusions

  • The str.replace(/abc/g, ''); (C) is a good cross-browser fast solution for all strings.
  • Solutions based on split-join (A,B) or replace (C,D) are fast
  • Solutions based on while (E,F,G,H) are slow - usually ~4 times slower for small strings and about ~3000 times (!) slower for long strings
  • The recurrence solutions (RA,RB) are slow and do not work for long strings

I also create my own solution. It looks like currently it is the shortest one which does the question job:

str.split`abc`.join``

str = "Test abc test test abc test test test abc test test abc";
str = str.split`abc`.join``

console.log(str);

Details

The tests were performed on Chrome 79.0, Safari 13.0.4 and Firefox 71.0 (64 bit). The tests RA and RB use recursion. Results

Enter image description here

Short string - 55 characters

You can run tests on your machine HERE. Results for Chrome:

Enter image description here

Long string: 275 000 characters

The recursive solutions RA and RB gives

RangeError: Maximum call stack size exceeded

For 1M characters they even break Chrome

enter image description here

I try to perform tests for 1M characters for other solutions, but E,F,G,H takes so much time that browser ask me to break script so I shrink test string to 275K characters. You can run tests on your machine HERE. Results for Chrome

enter image description here

Code used in tests

var t="Test abc test test abc test test test abc test test abc"; // .repeat(5000)
var log = (version,result) => console.log(`${version}: ${result}`);


function A(str) {
  return str.split('abc').join('');
}

function B(str) {
  return str.split`abc`.join``; // my proposition
}


function C(str) {
  return str.replace(/abc/g, '');
}

function D(str) {
  return str.replace(new RegExp("abc", "g"), '');
}

function E(str) {
  while (str.indexOf('abc') !== -1) { str = str.replace('abc', ''); }
  return str;
}

function F(str) {
  while (str.indexOf('abc') !== -1) { str = str.replace(/abc/, ''); }
  return str;
}

function G(str) {
  while(str.includes("abc")) { str = str.replace('abc', ''); }
  return str;
}

// src: https://stackoverflow.com/a/56989553/860099
function H(str)
{
    let i = -1
    let find = 'abc';
    let newToken = '';

    if (!str)
    {
        if ((str == null) && (find == null)) return newToken;
        return str;
    }

    while ((
        i = str.indexOf(
            find, i >= 0 ? i + newToken.length : 0
        )) !== -1
    )
    {
        str = str.substring(0, i) +
            newToken +
            str.substring(i + find.length);
    }
    return str;
}

// src: https://stackoverflow.com/a/22870785/860099
function RA(string, prevstring) {
  var omit = 'abc';
  var place = '';
  if (prevstring && string === prevstring)
    return string;
  prevstring = string.replace(omit, place);
  return RA(prevstring, string)
}

// src: https://stackoverflow.com/a/26107132/860099
function RB(str) {
  var find = 'abc';
  var replace = '';
  var i = str.indexOf(find);
  if (i > -1){
    str = str.replace(find, replace);
    i = i + replace.length;
    var st2 = str.substring(i);
    if(st2.indexOf(find) > -1){
      str = str.substring(0,i) + RB(st2, find, replace);
    }
  }
  return str;
}




log('A ', A(t));
log('B ', B(t));
log('C ', C(t));
log('D ', D(t));
log('E ', E(t));
log('F ', F(t));
log('G ', G(t));
log('H ', H(t));
log('RA', RA(t)); // use reccurence
log('RB', RB(t)); // use reccurence
<p style="color:red">This snippet only presents codes used in tests. It not perform test itself!<p>

如何替换字符串的所有出现?

空城缀染半城烟沙 2025-02-18 21:45:36

您可以为此purporse使用 wp_kses 。使用 WP_KSES_ALLOD_HTML filter添加 img 元素的过滤器。

在您的functions.php中。

function theme_slug_kses_allowed_html($tags, $context) {
    switch($context) {
        case 'no-images': 
            $tags = wp_kses_allowed_html('post');
            unset( $tags['img'] );
            return $tags;
        default: 
            return $tags;
    }
}
add_filter( 'wp_kses_allowed_html', 'theme_slug_kses_allowed_html', 10, 2);

然后在index.php中。

echo wp_kses( get_the_content(), 'no-images' );

You can use the wp_kses for this purporse. Add the filter for the img element using the wp_kses_allowed_html filter.

In your functions.php.

function theme_slug_kses_allowed_html($tags, $context) {
    switch($context) {
        case 'no-images': 
            $tags = wp_kses_allowed_html('post');
            unset( $tags['img'] );
            return $tags;
        default: 
            return $tags;
    }
}
add_filter( 'wp_kses_allowed_html', 'theme_slug_kses_allowed_html', 10, 2);

Then in index.php.

echo wp_kses( get_the_content(), 'no-images' );

从帖子中删除the_content的所有图像?

空城缀染半城烟沙 2025-02-18 06:25:53

定义函数 f 中的比较,然后通过 Outs rowsums 是您想要的。

f <- \(x, y) df1[x, 1] >= df2[y, 2] & df1[x, 1] <= df2[y, 3]
cbind(df1, number=rowSums(outer(1:nrow(df1), 1:nrow(df2), f)))
#         dates number
# 1  2020-01-01      2
# 2  2020-01-02      2
# 3  2020-01-03      1
# 4  2020-01-04      0
# 5  2020-01-05      1
# 6  2020-01-06      1
# 7  2020-01-07      1
# 8  2020-01-08      1
# 9  2020-01-09      1
# 10 2020-01-10      2

Define the comparison in a function f and pass it through outer, rowSums is what you're looking for.

f <- \(x, y) df1[x, 1] >= df2[y, 2] & df1[x, 1] <= df2[y, 3]
cbind(df1, number=rowSums(outer(1:nrow(df1), 1:nrow(df2), f)))
#         dates number
# 1  2020-01-01      2
# 2  2020-01-02      2
# 3  2020-01-03      1
# 4  2020-01-04      0
# 5  2020-01-05      1
# 6  2020-01-06      1
# 7  2020-01-07      1
# 8  2020-01-08      1
# 9  2020-01-09      1
# 10 2020-01-10      2

将函数应用于行,但引用不同的表

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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