疑心病

文章 评论 浏览 507

疑心病 2025-02-21 01:45:38

从异步函数返回值的另一种方法是传递将从异步函数中存储结果的对象。

这是一个相同的示例:

var async = require("async");

// This wires up result back to the caller
var result = {};
var asyncTasks = [];
asyncTasks.push(function(_callback){
    // some asynchronous operation
    $.ajax({
        url: '...',
        success: function(response) {
            result.response = response;
            _callback();
        }
    });
});

async.parallel(asyncTasks, function(){
    // result is available after performing asynchronous operation
    console.log(result)
    console.log('Done');
});

我正在使用结果对象在异步操作期间存储该值。这允许结果即使在异步工作后也可以使用。

我经常使用这种方法。我很想知道这种方法的效果如何,其中涉及连续模块的结果对结果进行接线。

Another approach to return a value from an asynchronous function, is to pass in an object that will store the result from the asynchronous function.

Here is an example of the same:

var async = require("async");

// This wires up result back to the caller
var result = {};
var asyncTasks = [];
asyncTasks.push(function(_callback){
    // some asynchronous operation
    $.ajax({
        url: '...',
        success: function(response) {
            result.response = response;
            _callback();
        }
    });
});

async.parallel(asyncTasks, function(){
    // result is available after performing asynchronous operation
    console.log(result)
    console.log('Done');
});

I am using the result object to store the value during the asynchronous operation. This allows the result be available even after the asynchronous job.

I use this approach a lot. I would be interested to know how well this approach works where wiring the result back through consecutive modules is involved.

如何从异步电话中返回响应?

疑心病 2025-02-20 21:25:55

尝试在AppComponent的构造函数中初始化类型AUTH的变量(您必须从“@angular/fire/auth”中导入它)。

import { Auth } from '@angular/fire/auth' //import statement


export class AppComponent  {
      constructor(private auth: Auth){}   

      //I did this, it worked for me 
}

try initializing a variable of type Auth (you have to import it from '@angular/fire/auth') inside the constructor of AppComponent like this.

import { Auth } from '@angular/fire/auth' //import statement


export class AppComponent  {
      constructor(private auth: Auth){}   

      //I did this, it worked for me 
}

在Angular 13项目中添加firebase不起作用

疑心病 2025-02-20 19:52:05

要更快地读取CSV文件,您可以使用 甚至比 fread()更快。 请参阅此处

现在使用vroom,

library(vroom)

vroom("https://docs.google.com/spreadsheets/d/170235QwbmgQvr0GWmT-8yBsC7Vk6p_dmvYxrZNfsKqk/pub?output=csv")

#> Rows: 387048 Columns: 14
#> ── Column specification ────────────────────────────────────────────────────────
#> Delimiter: ","
#> chr  (6): StationCode, SampleID, WeatherCode, OrganismCode, race, race2
#> dbl  (7): WaterTemperature, Turbidity, Velocity, ForkLength, Weight, Count, ...
#> date (1): SampleDate
#> 
#> ℹ Use `spec()` to retrieve the full column specification for this data.
#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
#> # A tibble: 387,048 × 14
#>    StationCode SampleDate SampleID WeatherCode WaterTemperature Turbidity
#>    <chr>       <date>     <chr>    <chr>                  <dbl>     <dbl>
#>  1 Gate 11     2000-04-25 116_00   CLD                    13.1       2   
#>  2 Gate 5      1995-04-26 117_95   CLR                    NA         2   
#>  3 Gate 2      1995-04-21 111_95   W                      10.4      12   
#>  4 Gate 6      2008-12-13 348_08   CLR                    49.9       1.82
#>  5 Gate 5      1999-12-10 344_99   CLR                     7.30      1.5 
#>  6 Gate 6      2012-05-25 146_12   CLR                    55.5       1.60
#>  7 Gate 10     2011-06-28 179_11   RAN                    57.3       3.99
#>  8 Gate 11     1996-04-25 116_96   CLR                    13.8      21   
#>  9 Gate 9      2007-07-02 183_07   CLR                    56.6       2.09
#> 10 Gate 6      2009-06-04 155_09   CLR                    58.6       3.08
#> # … with 387,038 more rows, and 8 more variables: Velocity <dbl>,
#> #   OrganismCode <chr>, ForkLength <dbl>, Weight <dbl>, Count <dbl>,
#> #   race <chr>, year <dbl>, race2 <chr>

在2022-07-08创建的 reprex package (v2.0.1)< /sup>

To read the CSV file faster you can use vroom which is even faster than fread(). See here.

Now using vroom,

library(vroom)

vroom("https://docs.google.com/spreadsheets/d/170235QwbmgQvr0GWmT-8yBsC7Vk6p_dmvYxrZNfsKqk/pub?output=csv")

#> Rows: 387048 Columns: 14
#> ── Column specification ────────────────────────────────────────────────────────
#> Delimiter: ","
#> chr  (6): StationCode, SampleID, WeatherCode, OrganismCode, race, race2
#> dbl  (7): WaterTemperature, Turbidity, Velocity, ForkLength, Weight, Count, ...
#> date (1): SampleDate
#> 
#> ℹ Use `spec()` to retrieve the full column specification for this data.
#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
#> # A tibble: 387,048 × 14
#>    StationCode SampleDate SampleID WeatherCode WaterTemperature Turbidity
#>    <chr>       <date>     <chr>    <chr>                  <dbl>     <dbl>
#>  1 Gate 11     2000-04-25 116_00   CLD                    13.1       2   
#>  2 Gate 5      1995-04-26 117_95   CLR                    NA         2   
#>  3 Gate 2      1995-04-21 111_95   W                      10.4      12   
#>  4 Gate 6      2008-12-13 348_08   CLR                    49.9       1.82
#>  5 Gate 5      1999-12-10 344_99   CLR                     7.30      1.5 
#>  6 Gate 6      2012-05-25 146_12   CLR                    55.5       1.60
#>  7 Gate 10     2011-06-28 179_11   RAN                    57.3       3.99
#>  8 Gate 11     1996-04-25 116_96   CLR                    13.8      21   
#>  9 Gate 9      2007-07-02 183_07   CLR                    56.6       2.09
#> 10 Gate 6      2009-06-04 155_09   CLR                    58.6       3.08
#> # … with 387,038 more rows, and 8 more variables: Velocity <dbl>,
#> #   OrganismCode <chr>, ForkLength <dbl>, Weight <dbl>, Count <dbl>,
#> #   race <chr>, year <dbl>, race2 <chr>

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

从Google Drive读取文件

疑心病 2025-02-20 19:18:32

这里的大多数答案无法解释切片的实际问题。他们只解释了切片的良性案例,而不是危险的案例。假设像其他答案一样,您正在处理两个类 a b ,其中 b 公开派生(公开)

在这种情况下,C ++使您可以将 b 的实例传递给 a 的分配操作员(以及复制构造函数)。之所以起作用,是因为 b 的实例可以转换为 const a&amp; ,这是分配运算符和复制构建者期望其参数的原因。

良性案例

B b;
A a = b;

在那里没有任何不好的事 - 您要求 a 的实例,该实例是 b 的副本,这正是您所获得的。当然, a 不包含 b 的某些成员,但是该如何?毕竟,这是一个 a ,不是 b ,因此它甚至没有关于这些成员的听到的,更不用说能够存储他们。

您可能会认为 b2 的危险情况

B b1;
B b2;
A& a_ref = b2;
a_ref = b1;
//b2 now contains a mixture of b1 and b2!

将是 b1 之后的副本。但是,a,不是!如果检查它,您会发现 b2 是弗兰肯斯坦的生物 a ),以及 b2 的一些块(仅包含 b 的块)。哎哟!

发生了什么?好吧,默认情况下,C ++不会将分配运算符视为 Virtual 。因此,行 a_ref = b1 将调用 a 的分配操作员,而不是 b 的分配操作员。这是因为,对于非虚拟函数,声明为(形式: static )类型( a&amp; )确定哪个函数称为,与实际(形式上: dynamic )类型相反(这将是 b ,因为 a_ref 引用引用实例 b )。现在, a 的分配操作员显然只知道 a 中声明的成员,因此它将仅复制这些成员,而将成员添加到 b 不变。

解决方案

仅分配给对象部分的 通常毫无意义,但是不幸的是,C ++没有内置的方式禁止此方法。但是,您可以自己滚动。第一步是使分配运算符 virtual 。这将保证始终是实际类型的分配操作员,而不是声明的类型。第二步是使用 dynamic_cast 来验证分配的对象是否具有兼容类型。第三步是在(受保护的!)成员 agiss()中进行实际分配,因为 b 's nistion> nistion()可能会想要使用 a 's nistion()复制 a 's,成员。

class A {
public:
  virtual A& operator= (const A& a) {
    assign(a);
    return *this;
  }

protected:
  void assign(const A& a) {
    // copy members of A from a to this
  }
};

class B : public A {
public:
  virtual B& operator= (const A& a) {
    if (const B* b = dynamic_cast<const B*>(&a))
      assign(*b);
    else
      throw bad_assignment();
    return *this;
  }

protected:
  void assign(const B& b) {
    A::assign(b); // Let A's assign() copy members of A from b to this
    // copy members of B from b to this
  }
};

请注意,为了纯粹的方便, b 's operator = 协变量覆盖返回类型,因为它知道它正在返回一个 b 。

Most answers here fail to explain what the actual problem with slicing is. They only explain the benign cases of slicing, not the treacherous ones. Assume, like the other answers, that you're dealing with two classes A and B, where B derives (publicly) from A.

In this situation, C++ lets you pass an instance of B to A's assignment operator (and also to the copy constructor). This works because an instance of B can be converted to a const A&, which is what assignment operators and copy-constructors expect their arguments to be.

The benign case

B b;
A a = b;

Nothing bad happens there - you asked for an instance of A which is a copy of B, and that's exactly what you get. Sure, a won't contain some of b's members, but how should it? It's an A, after all, not a B, so it hasn't even heard about these members, let alone would be able to store them.

The treacherous case

B b1;
B b2;
A& a_ref = b2;
a_ref = b1;
//b2 now contains a mixture of b1 and b2!

You might think that b2 will be a copy of b1 afterward. But, alas, it's not! If you inspect it, you'll discover that b2 is a Frankensteinian creature, made from some chunks of b1 (the chunks that B inherits from A), and some chunks of b2 (the chunks that only B contains). Ouch!

What happened? Well, C++ by default doesn't treat assignment operators as virtual. Thus, the line a_ref = b1 will call the assignment operator of A, not that of B. This is because, for non-virtual functions, the declared (formally: static) type (which is A&) determines which function is called, as opposed to the actual (formally: dynamic) type (which would be B, since a_ref references an instance of B). Now, A's assignment operator obviously knows only about the members declared in A, so it will copy only those, leaving the members added in B unchanged.

A solution

Assigning only to parts of an object usually makes little sense, yet C++, unfortunately, provides no built-in way to forbid this. You can, however, roll your own. The first step is making the assignment operator virtual. This will guarantee that it's always the actual type's assignment operator which is called, not the declared type's. The second step is to use dynamic_cast to verify that the assigned object has a compatible type. The third step is to do the actual assignment in a (protected!) member assign(), since B's assign() will probably want to use A's assign() to copy A's, members.

class A {
public:
  virtual A& operator= (const A& a) {
    assign(a);
    return *this;
  }

protected:
  void assign(const A& a) {
    // copy members of A from a to this
  }
};

class B : public A {
public:
  virtual B& operator= (const A& a) {
    if (const B* b = dynamic_cast<const B*>(&a))
      assign(*b);
    else
      throw bad_assignment();
    return *this;
  }

protected:
  void assign(const B& b) {
    A::assign(b); // Let A's assign() copy members of A from b to this
    // copy members of B from b to this
  }
};

Note that, for pure convenience, B's operator= covariantly overrides the return type, since it knows that it's returning an instance of B.

什么是对象切片?

疑心病 2025-02-20 17:31:39

为您的问题分享另一个调试流程。结果存储在数组中,而不是来自服务器 /网络请求。

  1. 从更改的来源开始 - 在您的示例中,&lt; div id =“ content”&gt; 是结果append(更改)

  2. 设置DOM断点 - 右键单击​​该元素,选择“ break on&gt;子树修改以在DOM中添加一个断点以跟踪任何代码修改。您可以在DOM断点**窗格中找到设置的DOM断点。

  3. 开始debug - 执行操作(例如类型鸡肉并从列表中选择第一个项目)以触发断点。代码中断 dofunction()

  1. 了解代码。阅读代码,逐步进行调试,然后您将意识到答案存储在数组中,而不是从服务器 /网络请求中存储。

Sharing another debugging flow for your question. The result is stored in array, and not from server / network request.

  1. Start with the source of changes - In your example, the <div id="content"> is where the result append (changes)

  2. Set a DOM breakpoint - Right click on the element, select break on > subtree modifications to add a breakpoint to the DOM to track any code modification. You can find the DOM breakpoints you set in the DOM breakpoints** pane.
    enter image description here

  3. Start debug - Perform the action (e.g Type Chicken and select the first item from the list) to trigger the breakpoint. The code break in doFunction().

enter image description here

  1. Understand the code. Read the code, step through debug it then you will realize that the answer is stored in array, and not from server / network request.
    enter image description here

为什么Chrome Developer工具找不到从服务器发送的某些元素?

疑心病 2025-02-20 14:08:39

您有三个选择来解决此错误

选择1

从Android/gradle/warpper/gradle-wrapper降级gradle.properties更改
distributionUrl

distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-all.zip

“到

distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-all.zip

选择2”

进行此链接中找到的更改noreferrer“> https://github.com/nzme/react-native-native-ad-manager/blob/master/android/android/build.gradle

另外,将这些行更改

def DEFAULT_COMPILE_SDK_VERSION = 28
def DEFAULT_BUILD_TOOLS_VERSION = '28.0.3'

为此

def DEFAULT_COMPILE_SDK_VERSION = 30
def DEFAULT_BUILD_TOOLS_VERSION = '30.0.2'

选择3 3

查找替代了React-Native-Ad-Ad-Manager,它已更新和维护Gradle 7+

希望这对您有帮助

You have Three choices to fix this error

Choice 1

Downgrade gradle from android/gradle/wrapper/gradle-wrapper.properties change
distributionUrl

from

distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-all.zip

to

distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-all.zip

Choice 2

Make the changes found in this link https://github.com/NZME/react-native-ad-manager/blob/master/android/build.gradle in your node_modules/react-native-ad-manager/build.gradle.

Also Change these lines

def DEFAULT_COMPILE_SDK_VERSION = 28
def DEFAULT_BUILD_TOOLS_VERSION = '28.0.3'

to this

def DEFAULT_COMPILE_SDK_VERSION = 30
def DEFAULT_BUILD_TOOLS_VERSION = '30.0.2'

Choice 3

Find a replacement for react-native-ad-manager which is updated and maintained for gradle 7+

Hope this helps you

构建失败:gradle build失败,错误错误。请参阅“运行gradlew”的日志。阶段

疑心病 2025-02-20 05:31:32

我个人将在功能中移动数据争吵代码,然后使用 lapply 循环循环您的数据帧列表。

library(dplyr)

df_list <- list(df, df, df)

prep_data <- function(x) {
  x %>%
    group_by(Item) %>%
    summarise(
      outlier = mean(Cost),
      offset = outlier * 0.6,
      higher_value = outlier + offset,
      lower_value = outlier - offset
    ) %>%
    left_join(x, by = "Item") %>%
    transmute(Item, Cost, Outlier = ifelse(Cost < lower_value | Cost > higher_value, "Y", "N"))
}

df_prep <- lapply(df_list, prep_data)

lapply(df_prep, head, 2)
#> [[1]]
#> # A tibble: 2 × 3
#>   Item    Cost Outlier
#>   <fct>  <dbl> <chr>  
#> 1 Book A   5   N      
#> 2 Book A   3.5 N      
#> 
#> [[2]]
#> # A tibble: 2 × 3
#>   Item    Cost Outlier
#>   <fct>  <dbl> <chr>  
#> 1 Book A   5   N      
#> 2 Book A   3.5 N      
#> 
#> [[3]]
#> # A tibble: 2 × 3
#>   Item    Cost Outlier
#>   <fct>  <dbl> <chr>  
#> 1 Book A   5   N      
#> 2 Book A   3.5 N

如果要通过循环的进行操作,则可以达到相同的结果:

df_prep <- list()
for (i in seq_along(df_list)) {
  df_prep[[i]] <- prep_data(df_list[[i]])
}

Personally I would move the data wrangling code in a function and would then use lapply to loop over your list of data frames.

library(dplyr)

df_list <- list(df, df, df)

prep_data <- function(x) {
  x %>%
    group_by(Item) %>%
    summarise(
      outlier = mean(Cost),
      offset = outlier * 0.6,
      higher_value = outlier + offset,
      lower_value = outlier - offset
    ) %>%
    left_join(x, by = "Item") %>%
    transmute(Item, Cost, Outlier = ifelse(Cost < lower_value | Cost > higher_value, "Y", "N"))
}

df_prep <- lapply(df_list, prep_data)

lapply(df_prep, head, 2)
#> [[1]]
#> # A tibble: 2 × 3
#>   Item    Cost Outlier
#>   <fct>  <dbl> <chr>  
#> 1 Book A   5   N      
#> 2 Book A   3.5 N      
#> 
#> [[2]]
#> # A tibble: 2 × 3
#>   Item    Cost Outlier
#>   <fct>  <dbl> <chr>  
#> 1 Book A   5   N      
#> 2 Book A   3.5 N      
#> 
#> [[3]]
#> # A tibble: 2 × 3
#>   Item    Cost Outlier
#>   <fct>  <dbl> <chr>  
#> 1 Book A   5   N      
#> 2 Book A   3.5 N

If you want to do it via a for loop then you could achieve the same result like so:

df_prep <- list()
for (i in seq_along(df_list)) {
  df_prep[[i]] <- prep_data(df_list[[i]])
}

通过r中的多个数据帧循环管道操作员代码

疑心病 2025-02-19 15:53:07

您可以使用相关的子查询:

SELECT t.teacher_id 
     , t.first_name
     , t.last_name 
     , c.course_id
     , c.course_name 
     , c.semester
     , (
         SELECT LISTAGG(s.last_name || ', ' || s.first_name, '; ')
                  WITHIN GROUP (ORDER BY s.last_name, s.first_name)
         FROM   enrollment e
                INNER JOIN students s
                ON (e.student_id = s.student_id)
         WHERE  e.course_id = c.course_id
       ) AS students
FROM   teachers t
       LEFT JOIN courses c
       ON t.teacher_id  = c.teacher_id 
ORDER BY
       teacher_id;

对于示例数据,输出:

cotherton_id first_name last_name course_id course_name 学期 学生
101 keith stein 1 几何 2022-2 aaron,信仰;阿尔特曼,莱斯利;库珀,贝丝;克恩,帕蒂; Saladino,丽莎
102 roger 木材 2 trigonometry 2022-2 aaron,信仰;阿尔特曼,莱斯利;库珀,贝丝;克恩,帕蒂; Saladino,丽莎
103 douglas kern 3 cyculus 2022-2 aaron,信仰;阿尔特曼,莱斯利;库珀,贝丝; Coralnick,吉尔;克恩,帕蒂; Saladino,丽莎
104 paul weber 4 化学 2022-2 null
105 jeffrey lebowitz 5 生物学 2022-2 null
106 carol seltzer 6 Physcology 2022-2 null

或者您可以使用 join s和汇总:

SELECT t.teacher_id 
     , MAX(t.first_name) AS first_name
     , MAX(t.last_name) AS last_name
     , c.course_id
     , MAX(c.course_name) AS course_name
     , MAX(c.semester) AS semester
     , LISTAGG(
         NVL2(s.student_id, s.last_name || ', ' || s.first_name, NULL),
         '; '
       ) WITHIN GROUP (ORDER BY s.last_name, s.first_name) AS students
     , COUNT(s.student_id) AS num_students
FROM   teachers t
       LEFT OUTER JOIN courses c
       ON t.teacher_id  = c.teacher_id
       LEFT OUTER JOIN (
         enrollment e
         INNER JOIN students s
         ON (e.student_id = s.student_id)
       )
       ON (e.course_id = c.course_id)
GROUP BY
       t.teacher_id,
       c.course_id
ORDER BY
       t.teacher_id,
       c.course_id;

db&lt;&gt; fiddle “ nofollow noreferrer”>在这里

You can use a correlated sub-query:

SELECT t.teacher_id 
     , t.first_name
     , t.last_name 
     , c.course_id
     , c.course_name 
     , c.semester
     , (
         SELECT LISTAGG(s.last_name || ', ' || s.first_name, '; ')
                  WITHIN GROUP (ORDER BY s.last_name, s.first_name)
         FROM   enrollment e
                INNER JOIN students s
                ON (e.student_id = s.student_id)
         WHERE  e.course_id = c.course_id
       ) AS students
FROM   teachers t
       LEFT JOIN courses c
       ON t.teacher_id  = c.teacher_id 
ORDER BY
       teacher_id;

Which, for the sample data, outputs:

TEACHER_ID FIRST_NAME LAST_NAME COURSE_ID COURSE_NAME SEMESTER STUDENTS
101 Keith Stein 1 Geometry 2022-2 Aaron, Faith; Altman, Leslee; Cooper, Beth; Kern, Patty; Saladino, Lisa
102 Roger Wood 2 Trigonometry 2022-2 Aaron, Faith; Altman, Leslee; Cooper, Beth; Kern, Patty; Saladino, Lisa
103 Douglas Kern 3 Calculus 2022-2 Aaron, Faith; Altman, Leslee; Cooper, Beth; Coralnick, Jill; Kern, Patty; Saladino, Lisa
104 Paul Weber 4 Chemistry 2022-2 null
105 Jeffrey Lebowitz 5 Biology 2022-2 null
106 Carol Seltzer 6 Physcology 2022-2 null

Or you can use JOINs and aggregate:

SELECT t.teacher_id 
     , MAX(t.first_name) AS first_name
     , MAX(t.last_name) AS last_name
     , c.course_id
     , MAX(c.course_name) AS course_name
     , MAX(c.semester) AS semester
     , LISTAGG(
         NVL2(s.student_id, s.last_name || ', ' || s.first_name, NULL),
         '; '
       ) WITHIN GROUP (ORDER BY s.last_name, s.first_name) AS students
     , COUNT(s.student_id) AS num_students
FROM   teachers t
       LEFT OUTER JOIN courses c
       ON t.teacher_id  = c.teacher_id
       LEFT OUTER JOIN (
         enrollment e
         INNER JOIN students s
         ON (e.student_id = s.student_id)
       )
       ON (e.course_id = c.course_id)
GROUP BY
       t.teacher_id,
       c.course_id
ORDER BY
       t.teacher_id,
       c.course_id;

db<>fiddle here

使用Listagg将所有学生分组为老师,课程,Semster

疑心病 2025-02-19 13:35:31

功能

const fetchChat = db.ref("messages/" + username + "/" + receiver + "/");
fetchChat.on("child_added", function (snapshot)
{
    const messages = snapshot.val();
    const msg = "<li>" + messages.usr + " : " + messages.msg + "</li>";
    document.getElementById("messages").innerHTML += msg;
});

只要将孩子添加到消息的目录中,它就会获取聊天的 ,因此,当您将打字状态存储在“ message/” + username +“/” + ceveriver +“ +”/“/” 中时函数 .on 知道您已更改/添加了一些内容,因此发布了消息。这是不确定的,因为消息实际上是空的。您应该在存储 aretheytyping 状态的情况下创建一个新目录,例如“ status/status/ + username +”/“ +接收者 +”/“/”
希望我帮助。

The function

const fetchChat = db.ref("messages/" + username + "/" + receiver + "/");
fetchChat.on("child_added", function (snapshot)
{
    const messages = snapshot.val();
    const msg = "<li>" + messages.usr + " : " + messages.msg + "</li>";
    document.getElementById("messages").innerHTML += msg;
});

It fetches the chat whenever a child is added to the directory of your messages, so when you store the typing status in "messages/" + username + "/" + receiver + "/" the function .on knows that you've changed/added something, therefore posting a message. It's undefined because the message is in fact empty. You should create a new directory where you store the areTheyTyping status, something like "status/" + username + "/" + receiver + "/"
Hope I helped.

当我在数据库中添加新元素时,整个过程停止工作

疑心病 2025-02-19 10:32:40

您可以使用类似的内容

l = ['a','b','c']
d = {element:index for index,element in enumerate(l)}

,这些内容将为您提供映射到其索引的每个元素。

如果要设置一些任意价值,请使用

l = ['a','b','c']
d = {element:value for element in l}

You could use something like

l = ['a','b','c']
d = {element:index for index,element in enumerate(l)}

which will give you each element mapped to its index.

if you want to set some arbitrary value, use

l = ['a','b','c']
d = {element:value for element in l}

如何为每个给定的键创建一个字典值?

疑心病 2025-02-19 06:02:52

使用

array = ['xx', 'xxxxxxxx', 'xxx'];
array.fill('');
console.log(array)

如果需要创建新数组,请使用 <代码>数组 构造函数与 array.fill.fill.fill

array = ['xx', 'xxxxxxxx', 'xxx'];
const newArray = new Array(array.length);
newArray.fill('');
console.log(newArray)

Use Array.fill.

array = ['xx', 'xxxxxxxx', 'xxx'];
array.fill('');
console.log(array)

If you need to create a new array, use the Array constructor combined with Array.fill:

array = ['xx', 'xxxxxxxx', 'xxx'];
const newArray = new Array(array.length);
newArray.fill('');
console.log(newArray)

如何在一系列字符串中清空字符串,但保持数组的长度

疑心病 2025-02-19 00:24:07

要使 github_configuration block可选,您可以做:

  dynamic "github_configuration" {

    for_each = var.Environment == "dev" ? [1] : []

    content {
      account_name    = var.Environment == "dev" ? var.AccountName : null
      branch_name     = var.Environment == "dev" ? var.Branch : null
      git_url         = var.Environment == "dev" ? var.RepoUrl : null
      repository_name = var.Environment == "dev" ? var.RepoName : null
      root_folder     = var.Environment == "dev" ? var.RepoFolder : null
    }
  }
}

[1] 确保 for_each 执行一个。 1 的实际值无关紧要。只要列表具有一个元素,就可以是任何值。

To make github_configuration block optional, you can do:

  dynamic "github_configuration" {

    for_each = var.Environment == "dev" ? [1] : []

    content {
      account_name    = var.Environment == "dev" ? var.AccountName : null
      branch_name     = var.Environment == "dev" ? var.Branch : null
      git_url         = var.Environment == "dev" ? var.RepoUrl : null
      repository_name = var.Environment == "dev" ? var.RepoName : null
      root_folder     = var.Environment == "dev" ? var.RepoFolder : null
    }
  }
}

[1] ensures that for_each executes ones. Actual value of 1 is irrelevant. It can be any value, as long as the list have one element.

Terraform如何根据条件创建代码块

疑心病 2025-02-18 22:09:38

啊!我要寻找的窍门是使用 $ undind 对于certrestresults阵列。

Aha! The trick I was looking for was to use $unwind for the certResults array.

Mongo聚集指导

疑心病 2025-02-18 20:38:23

@Davide的答案是完全正确的,我只想补充说您可以使用构造函数注入:


private final AgroalDataSource ds;
private final Logger log;

public FindPrepaidSubscriberICCID(AgroalDataSource ds, Logger log) {
   this.ds = ds;
   this.log = log;
}

构造函数注入倾向于简化可测试性(因为您可以创建对象传递间谍或模拟的实例)。它还确保您不会写入托管字段(因为字段是最终的)。

@Davide answer is totally right, I just wanted to add that you can use constructor injection:


private final AgroalDataSource ds;
private final Logger log;

public FindPrepaidSubscriberICCID(AgroalDataSource ds, Logger log) {
   this.ds = ds;
   this.log = log;
}

Constructor injection tends to ease testability (because you can create instances of your objects passing spies or mocks). It also makes sure you do not write to the managed fields (as the fields are final).

使用Logger JBoss中使用Quarkus中的日志时的错误

疑心病 2025-02-18 16:14:22

原因是因为您的 MAP 操作是从已在执行者上发生的事物中读取的。

如果您查看管道:

val result = testRepository.readTable(db, tableName)
  .map(testInstance.doSomeOperation)
  .count()

您要做的第一件事是 testrepository.readtable(db,tablename)。如果我们在读取方法中查看内部,我们会看到您在其中进行 spark.table 操作。如果我们从 api docs ,我们看到以下功能签名:

def table(tableName: String): DataFrame

这不是仅在驱动程序上进行的操作(想象一下阅读阅读在仅在驱动程序上进行的&gt; 1tb的文件中),并创建一个数据框(本身就是一个分布式数据集)。这意味着需要分发 testRepository.ReadTable(db,tableName)函数,因此您的 testrepository 需要分发对象。

希望这对您有帮助!

The reason why is because your map operation is reading from something that already takes place on the executors.

If you look at your pipeline:

val result = testRepository.readTable(db, tableName)
  .map(testInstance.doSomeOperation)
  .count()

The first thing you do is testRepository.readTable(db, tableName). If we look inside of the readTable method, we see that you are doing a spark.table operation in there. If we look at the function signature of this method from the API docs, we see the following function signature:

def table(tableName: String): DataFrame

This is not an operation that solely takes place on the driver (imagine reading in a file of >1TB while only taking place on the driver), and it creates a Dataframe (which is by itself a distributed dataset). That means that the testRepository.readTable(db, tableName) function needs to be distributed, and so your testRepository object needs to be distributed.

Hope this helps you!

为什么spark dataset.map要求查询的所有部分都可以序列化?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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