玩套路吗

文章 评论 浏览 29

玩套路吗 2025-02-21 01:14:01

编译器正在做的是将您的lambda和lambda捕获的任何变量捕获到编译器生成的嵌套类中。

编译后,您的示例看起来很像:

class Program
{
        delegate void Action();
        static void Main(string[] args)
        {
                List<Action> actions = new List<Action>();

                DisplayClass1 displayClass1 = new DisplayClass1();
                for (displayClass1.i = 0; displayClass1.i < 10; ++displayClass1.i )
                        actions.Add(new Action(displayClass1.Lambda));

                foreach (Action a in actions)
                        a();
        }

        class DisplayClass1
        {
                int i;
                void Lambda()
                {
                        Console.WriteLine(i);
                }
        }
}

通过在for循环中制作副本,编译器会在每个迭代中生成新对象,例如:

for (int i = 0; i < 10; ++i)
{
    DisplayClass1 displayClass1 = new DisplayClass1();
    displayClass1.i = i;
    actions.Add(new Action(displayClass1.Lambda));
}

What the compiler is doing is pulling your lambda and any variables captured by the lambda into a compiler generated nested class.

After compilation your example looks a lot like this:

class Program
{
        delegate void Action();
        static void Main(string[] args)
        {
                List<Action> actions = new List<Action>();

                DisplayClass1 displayClass1 = new DisplayClass1();
                for (displayClass1.i = 0; displayClass1.i < 10; ++displayClass1.i )
                        actions.Add(new Action(displayClass1.Lambda));

                foreach (Action a in actions)
                        a();
        }

        class DisplayClass1
        {
                int i;
                void Lambda()
                {
                        Console.WriteLine(i);
                }
        }
}

By making a copy within the for loop, the compiler generates new objects in each iteration, like so:

for (int i = 0; i < 10; ++i)
{
    DisplayClass1 displayClass1 = new DisplayClass1();
    displayClass1.i = i;
    actions.Add(new Action(displayClass1.Lambda));
}

如何告诉lambda函数捕获副本而不是C#中的参考?

玩套路吗 2025-02-21 00:51:33

让我们称它们为arraya和arrayb。和输出数组作为arrayc。该算法看起来像:


    check_index = 0
    for each_index in range(len(arrayA)):
      if arrayA[each_index] == 1:
        append(arrayC, arrayB[check_index])
        # this bumps the index to the next value
        check_index += 1
    
      else:
        append(arrayC, arrayB[check_index])
        # otherwise, the index would stay the same


Let's call them arrayA and arrayB. And output array as arrayC. The algorithm would look like:


    check_index = 0
    for each_index in range(len(arrayA)):
      if arrayA[each_index] == 1:
        append(arrayC, arrayB[check_index])
        # this bumps the index to the next value
        check_index += 1
    
      else:
        append(arrayC, arrayB[check_index])
        # otherwise, the index would stay the same


如何从索引数组中创建最后一个标记值的数组

玩套路吗 2025-02-21 00:33:12

给您的类型一个ID并使其可识别,如果您不需要确定,请不要添加它。

struct MyType: Encodable, Identifiable {
  let id = UUID()

  // other properties
}

使用 Codable 只是添加编码可解码的简写。因此,如果您不需要两者,请使用所需的。

Give your type an id and make it identifiable and if you don’t need decidable don’t add it.

struct MyType: Encodable, Identifiable {
  let id = UUID()

  // other properties
}

Using Codable is just shorthand for adding Encodable and Decodable. So if you don’t need both, then just use the one you need.

SwiftUI-错误 - 初始化器&#x27; init(_:RowContent:)&#x27;要求&#x27; customdatamodel&#x27;符合识别性&#x27;

玩套路吗 2025-02-20 18:19:57

一种pythonic,递归和功能性方法来解开任意json树:

handlers = {
    list:  iterate,
    dict:  delve,
    str:   emit_li,
    float: emit_li,
}

def emit_li(stuff, strong=False):
    emission = '<li><strong>%s</strong></li>' if strong else '<li>%s</li>'
    print(emission % stuff)

def iterate(a_list):
    print('<ul>')
    map(unravel, a_list)
    print('</ul>')

def delve(a_dict):
    print('<ul>')
    for key, value in a_dict.items():
        emit_li(key, strong=True)
        unravel(value)
    print('</ul>')

def unravel(structure):
    h = handlers[type(structure)]
    return h(structure)

unravel(data)

其中 data 是python列表(根据JSON文本列表):

data = [
    {'data': {'customKey1': 'customValue1',
           'customKey2': {'customSubKey1': {'customSubSubKey1': 'keyvalue'}}},
  'geometry': {'location': {'lat': 37.3860517, 'lng': -122.0838511},
               'viewport': {'northeast': {'lat': 37.4508789,
                                          'lng': -122.0446721},
                            'southwest': {'lat': 37.3567599,
                                          'lng': -122.1178619}}},
  'name': 'Mountain View',
  'scope': 'GOOGLE',
  'types': ['locality', 'political']}
]

A pythonic, recursive and functional approach to unravel arbitrary JSON trees:

handlers = {
    list:  iterate,
    dict:  delve,
    str:   emit_li,
    float: emit_li,
}

def emit_li(stuff, strong=False):
    emission = '<li><strong>%s</strong></li>' if strong else '<li>%s</li>'
    print(emission % stuff)

def iterate(a_list):
    print('<ul>')
    map(unravel, a_list)
    print('</ul>')

def delve(a_dict):
    print('<ul>')
    for key, value in a_dict.items():
        emit_li(key, strong=True)
        unravel(value)
    print('</ul>')

def unravel(structure):
    h = handlers[type(structure)]
    return h(structure)

unravel(data)

where data is a python list (parsed from a JSON text string):

data = [
    {'data': {'customKey1': 'customValue1',
           'customKey2': {'customSubKey1': {'customSubSubKey1': 'keyvalue'}}},
  'geometry': {'location': {'lat': 37.3860517, 'lng': -122.0838511},
               'viewport': {'northeast': {'lat': 37.4508789,
                                          'lng': -122.0446721},
                            'southwest': {'lat': 37.3567599,
                                          'lng': -122.1178619}}},
  'name': 'Mountain View',
  'scope': 'GOOGLE',
  'types': ['locality', 'political']}
]

如何访问和处理嵌套对象,数组或JSON?

玩套路吗 2025-02-20 08:01:24

您可以使用将结果压缩至(-1,0,1)。
然后,您可以轻松编写数据表。

import spock.lang.*

class ASpec extends Specification {
  def "compare"() {
    expect: 
        Math.signum(comparator(a, b)) == result
      
    where:
        a | b || result
        1 | 2 || -1
        1 | 9 || -1
        1 | 1 || 0
        5 | 2 || 1    
        4 | 2 || -1 // fail intentionally
  }
    
    int comparator(int a, int b) {
        a - b
    }
}

Groovy Web控制台

You can use Math.signum to compress your result down to (-1,0,1).
Then you can easily write your data table.

import spock.lang.*

class ASpec extends Specification {
  def "compare"() {
    expect: 
        Math.signum(comparator(a, b)) == result
      
    where:
        a | b || result
        1 | 2 || -1
        1 | 9 || -1
        1 | 1 || 0
        5 | 2 || 1    
        4 | 2 || -1 // fail intentionally
  }
    
    int comparator(int a, int b) {
        a - b
    }
}

Groovy Web Console

Groovy- Spock数据表期望值

玩套路吗 2025-02-19 03:32:16

就我而言,我正在传递空论点,所以请检查您的论点

In my case I was passing empty arguments, so check your arguments

致电firebase.initializeapp()返回&#x27;无法在频道上建立连接&#x27; -Flutter&#x2B;火基

玩套路吗 2025-02-19 02:09:11

The recommended way to install Tomcat8.5 as a service is to open a command prompt as administrator, then cd %TOMCAT_HOME%\bin, and run service.bat install. This script provides many more parameters. (In a cmd bat script, ^ before newline continues a command on the next line.)

服务特定错误代码1使用Tomcat 8作为Windows服务

玩套路吗 2025-02-18 22:35:15

我认为您应该以不同的方式解释表。 O(n^2)复杂性说,如果输入n加倍,运行时应该四倍(需要4倍)。在这种情况下,函数(n:number)返回一个镜像其运行时的数字。我将f(n)用作它的简短。

因此,说n从1到2,这意味着输入增加了一倍(2/1 = 2)。然后,运行时间从F(1)变为F(2),这意味着它增加了F(2)/F(1)= 3/1 = 3次。那不是4次,但是Big-O复杂性度量是渐近的,处理了N接近Infinity的情况。如果我们从表中测试另一个输入,则为F(6)/F(3)= 21/6 = 3.5。它已经接近4。

让我们现在流浪在桌子外面,尝试更大的n。 )= 12502500/3126250 = 3.999。趋势很明显。随着n接近无穷大,输入的两倍趋向于四倍的运行时。这就是O(n^2)的标志。

I think you should interpret the table differently. The O(N^2) complexity says that if you double the input N, the runtime should quadruple (take 4 times as long). In this case, the function(n: number) returns a number mirroring its runtime. I use f(N) as a short for it.

So say N goes from 1 to 2, which means the input has doubled (2/1 = 2). The runtime then has gone from f(1) to f(2), which means it has increased f(2)/f(1) = 3/1 = 3 times. That is not 4 times, but the Big-O complexity measure is asymptotic, dealing with the situation where N approaches infinity. If we test another input doubling from the table, we have f(6)/f(3) = 21/6 = 3.5. It is already closer to 4.

Let us now stray outside the table and try more doublings with bigger N. For example we have f(200)/f(100) = 20100/5050 = 3.980 and f(5000)/f(2500) = 12502500/3126250 = 3.999. The trend is clear. As N approaches infinity, a doubled input tends toward a quadrupled runtime. And that is the hallmark of O(N^2).

运行1&#x2b; 2&#x2b; ...&#x2b; n times的算法的时间复杂性;

玩套路吗 2025-02-18 20:16:35

其原因是每个新覆盖层没有更新的Python软件包;由 jan tojnar的回复t/prev-python-override/20066/2“ rel =“ nofollow noreferrer”>此处::

overlays =
  let
    emptyOverlay = final: prev: {};
  in
  {
    autoslot = final: prev: {
      python310 = prev.python310.override (prevArgs: {
        packageOverrides =
          let
            ourOverlay = new: old: {
              autoslot = new.callPackage ./autoslot.nix {};
            };
          in
          prev.lib.composeExtensions
            prevArgs.packageOverrides or emptyOverlay
            ourOverlay;
      });
    };
    backtrace = final: prev: {
      python310 = prev.python310.override (prevArgs: {
        packageOverrides =
          let
            ourOverlay = new: old: {
              backtrace = new.callPackage ./backtrace.nix {};
            };
          in
          prev.lib.composeExtensions
            prevArgs.packageOverrides or emptyOverlay
            ourOverlay;
      });
    };
  }

The reason for this were the Python Packages not updating with each new overlay; solved by Jan Tojnar's reply here:

overlays =
  let
    emptyOverlay = final: prev: {};
  in
  {
    autoslot = final: prev: {
      python310 = prev.python310.override (prevArgs: {
        packageOverrides =
          let
            ourOverlay = new: old: {
              autoslot = new.callPackage ./autoslot.nix {};
            };
          in
          prev.lib.composeExtensions
            prevArgs.packageOverrides or emptyOverlay
            ourOverlay;
      });
    };
    backtrace = final: prev: {
      python310 = prev.python310.override (prevArgs: {
        packageOverrides =
          let
            ourOverlay = new: old: {
              backtrace = new.callPackage ./backtrace.nix {};
            };
          in
          prev.lib.composeExtensions
            prevArgs.packageOverrides or emptyOverlay
            ourOverlay;
      });
    };
  }

在导入nixpkgs时,使用薄片叠加的覆盖物导致`错误:属性&#x27; autoSlot&#x27;缺少&#x27;

玩套路吗 2025-02-18 12:52:37

这样的事情会起作用:

var allowedPaths = map[string]bool{
    "GET/abc": true,
}

func APIRequestMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if _, ok := allowedPaths[r.Method+r.URL.Path]; ok {
             next.ServeHTTP(w, r)
             return
        }
        
        auth := r.Header.Get("authorization")
        type tokenDetails struct {
            Token      string
            Expires_at time.Time
            Rate_limit int
            Enabled    bool
            Created    time.Time
        }
        var details tokenDetails
        err = sqlx.Get(database.AccountDB, details, `Select * from keys where token = $1`, auth)
        if err != nil {
            request_util.InvalidTokenResponse(w, r)
            return
        }

        if details.Expires_at.Before(time.Now()) {
            request_util.InvalidTokenResponse(w, r)
            return
        }
        if !details.Enabled {
            request_util.InvalidTokenResponse(w, r)
            return
        }

        // Track # of requests
        // if currentRequest > details.Rate_limit {
        //  request_util.InvalidTokenResponse(w, r)
        //  return
        // }
        next.ServeHTTP(w, r)
    })
}

Something like this would work:

var allowedPaths = map[string]bool{
    "GET/abc": true,
}

func APIRequestMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if _, ok := allowedPaths[r.Method+r.URL.Path]; ok {
             next.ServeHTTP(w, r)
             return
        }
        
        auth := r.Header.Get("authorization")
        type tokenDetails struct {
            Token      string
            Expires_at time.Time
            Rate_limit int
            Enabled    bool
            Created    time.Time
        }
        var details tokenDetails
        err = sqlx.Get(database.AccountDB, details, `Select * from keys where token = $1`, auth)
        if err != nil {
            request_util.InvalidTokenResponse(w, r)
            return
        }

        if details.Expires_at.Before(time.Now()) {
            request_util.InvalidTokenResponse(w, r)
            return
        }
        if !details.Enabled {
            request_util.InvalidTokenResponse(w, r)
            return
        }

        // Track # of requests
        // if currentRequest > details.Rate_limit {
        //  request_util.InvalidTokenResponse(w, r)
        //  return
        // }
        next.ServeHTTP(w, r)
    })
}

了解如何仅适用于第三方的API密钥

玩套路吗 2025-02-18 07:43:49

我通过设置高度解决了问题:自动,Maxheight:自动,溢出:自动。

I fixed the issue by setting height: auto, maxHeight: auto, overflow: auto.

垂直滚动与移动铬上的溢出自动

玩套路吗 2025-02-18 05:51:16

您的问题需要重新配置。这些点没有连接。
如果要根据激活的选项卡检测选项卡更改并操纵视图,则Angular材料具有 MattabChangeEvent 以检测 MattabGroup 中的活动选项卡,并且基于零。第一个选项卡具有索引0。

onTabChange(event: MatTabChangeEvent) {
    switch (event.index) {
      case 0:
        // your logic
        break
      case 1:
         // your logic
        break
      case 2:
        // your logic
        break
    }
  }

Your question requires re-formulation. The dots are just not connected.
In case you want to detect the tab change and manipulate your view based on activated tab, Angular Material has MatTabChangeEvent to detect the active tab in MatTabGroup and it is zero based. First tab has index 0.

onTabChange(event: MatTabChangeEvent) {
    switch (event.index) {
      case 0:
        // your logic
        break
      case 1:
         // your logic
        break
      case 2:
        // your logic
        break
    }
  }

如果我想在看到网站时我的“ if”声明可以正常工作,该怎么办?

玩套路吗 2025-02-18 03:58:01

您必须在 composeview 上调用 .disposecomposition()

解决方案

 override fun onResume() {
    super.onResume()
    binding.composeHeader.disposeComposition()
}

Solution :

You have to call .disposeComposition() on your ComposeView

In your onResume() function

Example :

 override fun onResume() {
    super.onResume()
    binding.composeHeader.disposeComposition()
}

喷气背包构成视图,而不是绘制片段

玩套路吗 2025-02-17 14:59:07

您链接到的博客发布的问题是,作者没有清楚地说明他们正在查看的Java版本。

安全点的放置详细信息绝对是JVM版本的特定于JVM版本。如果可以在位置不好的地方确定简单(和现实的)示例,那么我想,Java维护者将弄清楚如何使优化器更聪明。因此,要知道(事先)问题是否会影响您,您将知道您正在使用与作者相同的JVM版本。显然,字节码编译器版本也很重要……根据下面的评论


Q:您是否应该修改编码样式以避免(根据博客发布)不当的情况?

答:我的建议通常是 - 否:

  1. 问题可能已经解决了您正在使用的Java版本中。
  2. 该问题可以用新版本的Java或即将发布的未来版本解决。 进行大修的努力要小。
  3. (升级要比对代码

但是,如果您&lt;基准您的应用程序和您&gt; do&lt;发现安全点问题具有可测量的效果,一定要调整应用程序中的循环,即受影响的循环,以及2)热点。 (但不是您所有的循环!这可能是浪费时间。)

简而言之……提防过早优化。

The problem with the blog posting you linked to is that the author does not state clearly what versions of Java they are looking at.

Details of the placement of safe points are definitely JVM version specific. If simple (and realistic) examples can be identified where the placement is bad, then I would imagine that the Java maintainers will figure out how to make the optimizer smarter. So to know (before hand) if the problem is going to affect you, you would to know you are using the same JVM version as the author. Apparently, the bytecode compiler version is also significant ... according to the comments below the posting


Q: Should you modify your coding style to avoid the cases that are (according to the blog posting) mishandled?

A: My advice would be in general - No:

  1. The problem may have been fixed already in the Java version you are using.
  2. The problem may be fixed in a newer version of Java, or a soon-to-be-released future version. (Upgrading would be less effort than overhauling your code.)
  3. Until you have written your code and benchmarked it with realistic data, you don't know if the problem will actually affect your application ... significantly.

However, if you >do< benchmark your application and you >do< find that that the safe-point problem has a measurable effect, by all means tweak the loops in your application that are 1) affected, and 2) hotspots. (But not all of your loops! That would probably be a waste of time.)

In short ... beware of premature optimization.

计数/未数的循环和安全性 - 是`while(&#x2b;&#x2b; i&lt; someinint)`被考虑到未数的循环吗?

玩套路吗 2025-02-17 11:14:40

以下是总结多列的另一种方法,当功能需要进一步参数时,尤其是有用的。您可以通过所有内容() any_of(c(“ a”,“ b”))等列的子集选择所有列。

library(dplyr)
# toy data
df <- tibble(a = sample(c(NA, 5:7), 30, replace = TRUE), 
             b = sample(c(NA, 1:5), 30, replace = TRUE), 
             c = sample(1:5, 30, replace = TRUE), 
             grp = sample(1:3, 30, replace = TRUE))
df
#> # A tibble: 30 × 4
#>        a     b     c   grp
#>    <int> <int> <int> <int>
#>  1     7     1     3     1
#>  2     7     4     4     2
#>  3     5     1     3     3
#>  4     7    NA     3     2
#>  5     7     2     5     2
#>  6     7     4     4     2
#>  7     7    NA     3     3
#>  8    NA     5     4     1
#>  9     5     1     1     2
#> 10    NA     3     1     2
#> # … with 20 more rows
df %>% 
  group_by(grp) %>%
  summarise(across(everything(), 
                   list(mean = ~mean(., na.rm = TRUE),
                        q75 = ~quantile(., probs = .75, na.rm = TRUE))))
#> # A tibble: 3 × 7
#>     grp a_mean a_q75 b_mean b_q75 c_mean c_q75
#>   <int>  <dbl> <dbl>  <dbl> <dbl>  <dbl> <dbl>
#> 1     1   6.6      7   2.88  4.25   3        4
#> 2     2   6.33     7   2.62  3.25   2.9      4
#> 3     3   5.78     6   3.33  4      3.09     4

Below is another way to summarize multiple columns, especially useful when the function needs further arguments. You can select all columns via everything() or a subset of columns like any_of(c("a", "b")).

library(dplyr)
# toy data
df <- tibble(a = sample(c(NA, 5:7), 30, replace = TRUE), 
             b = sample(c(NA, 1:5), 30, replace = TRUE), 
             c = sample(1:5, 30, replace = TRUE), 
             grp = sample(1:3, 30, replace = TRUE))
df
#> # A tibble: 30 × 4
#>        a     b     c   grp
#>    <int> <int> <int> <int>
#>  1     7     1     3     1
#>  2     7     4     4     2
#>  3     5     1     3     3
#>  4     7    NA     3     2
#>  5     7     2     5     2
#>  6     7     4     4     2
#>  7     7    NA     3     3
#>  8    NA     5     4     1
#>  9     5     1     1     2
#> 10    NA     3     1     2
#> # … with 20 more rows
df %>% 
  group_by(grp) %>%
  summarise(across(everything(), 
                   list(mean = ~mean(., na.rm = TRUE),
                        q75 = ~quantile(., probs = .75, na.rm = TRUE))))
#> # A tibble: 3 × 7
#>     grp a_mean a_q75 b_mean b_q75 c_mean c_q75
#>   <int>  <dbl> <dbl>  <dbl> <dbl>  <dbl> <dbl>
#> 1     1   6.6      7   2.88  4.25   3        4
#> 2     2   6.33     7   2.62  3.25   2.9      4
#> 3     3   5.78     6   3.33  4      3.09     4

汇总 /总结每个组的多个变量(例如总和,平均值)

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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