问:
If element: rather than if element not None won't work
From what I understand this should just pass by the if statement if there is no email column present but it's throwing KeyError: None when it gets to the if statement. Could someone help me understand this rule? Thanks!

```<code>def not_isin(df1, df2, phone_col, df2phone_col,website_col, df2website_col,company_col, df2company_col, email_col, df2email_col):
    print("entered not_isin")
    df1 = df1[~df1[phone_col].isin(df2[df2phone_col])]
    df1 = df1[~df1[website_col].isin(df2[df2website_col])]
    df1 = df1[~df1[company_col].isin(df2[df2company_col])]
    if df1[email_col] and df2[df2email_col]:
        df1 = df1[~df1[email_col].isin(df2[df2email_col])]
        return df1
    return df1
</code>```

答:
I think it fails at df1[email_col].

Obviously, if email_col is None, you get a KeyError before even reaching the if statement.

Body:
From what I understand this should just pass by the if statement if there is no email column present but it's throwing KeyError: None when it gets to the if statement. Could someone help me understand this rule? Thanks!

def not_isin(df1, df2, phone_col, df2phone_col,website_col, df2website_col,company_col, df2company_col, email_col, df2email_col):
    print("entered not_isin")
    df1 = df1[~df1[phone_col].isin(df2[df2phone_col])]
    df1 = df1[~df1[website_col].isin(df2[df2website_col])]
    df1 = df1[~df1[company_col].isin(df2[df2company_col])]
    if df1[email_col] and df2[df2email_col]:
        df1 = df1[~df1[email_col].isin(df2[df2email_col])]
        return df1
    return df1


来源: stackexchange

问:
How can I set expiry on Second Level Cache?

Problem

I can't set expiry of second level cache with Ehcache.

Is there any way to config expiry?

My Codes

build.gradle

```<code>implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'org.hibernate:hibernate-jcache:5.6.5.Final'
implementation 'org.ehcache:ehcache:3.9.9'
</code>```

application.yml

spring:
  jpa:

    properties:
      javax:
        persistence:
          sharedCache:
            mode: ENABLE_SELECTIVE   # Enable caches only @Cacheable annotated classes
      hibernate:
        cache:
          use_query_cache: true
          use_second_level_cache: true
          region:
            factory_class: org.hibernate.cache.jcache.JCacheRegionFactory
```
<h3>My Entity</h3>
<pre class="lang-kotlin prettyprint-override"><code>@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
@Cacheable
@Cache(region = "test_cache", usage = CacheConcurrencyStrategy.READ_WRITE)
public class Test {
.
.
.
}
</code>```

答:
Yes, there is a way.

Change your factory_class to org.hibernate.cache.ehcache.EhCacheRegionFactory

Create an ehcache.xml in /src/main/resources with this content:

```<code>   ...
   <cache-template name="default">
      <expiry>
         <ttl unit="hours">48</ttl>
      </expiry>
    </cache-template>
   ...
</code>```

Details to the XML configuration can be found at https://www.ehcache.org/documentation/3.9/xml.html

ContentLicense: CC BY-SA 4.0

Body:
Problem

I can't set expiry of second level cache with Ehcache.

Is there any way to config expiry?

My Codes

build.gradle

implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'org.hibernate:hibernate-jcache:5.6.5.Final'
implementation 'org.ehcache:ehcache:3.9.9'

application.yml

spring:
  jpa:

    properties:
      javax:
        persistence:
          sharedCache:
            mode: ENABLE_SELECTIVE   # Enable caches only @Cacheable annotated classes
      hibernate:
        cache:
          use_query_cache: true
          use_second_level_cache: true
          region:
            factory_class: org.hibernate.cache.jcache.JCacheRegionFactory

My Entity

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
@Cacheable
@Cache(region = "test_cache", usage = CacheConcurrencyStrategy.READ_WRITE)
public class Test {
.
.
.
}

Body:
Yes, there is a way.

Change your factory_class to org.hibernate.cache.ehcache.EhCacheRegionFactory

Create an ehcache.xml in /src/main/resources with this content:

   ...
   <cache-template name="default">
      <expiry>
         <ttl unit="hours">48</ttl>
      </expiry>
    </cache-template>
   ...

Details to the XML configuration can be found at https://www.ehcache.org/documentation/3.9/xml.html


问:
Why does the compiler copy RDI to another register, and then copy it back to RDI inside a loop?
I'm analysing a piece of inefficient code, but some of it is so confusing?

Original code:

#include <string.h>

void lowwer(char *str) {
  for (int i = 0; i < strlen(str); ++i) {
    str[i] -= ('A' - 'a');
  }
}
```
<p>Assembly code (generated by clang 13 with -Og option):</p>
```lowwer:
  pushq %r14 # use saved-registers
  pushq %rbx
  pushq %rax
  # guard do while
  cmpb  $0, (%rdi) # compare &str with null (check if strlen(str) == 0)
  je    .LBB0_3
  # loop initialization
  movq  %rdi, %r14 # %r14 = str
  xorl  %ebx, %ebx # clear %rbx (for more compact encoding)
.LBB0_2:                                # =>This Inner Loop Header: Depth=1
  addb  $32, (%r14,%rbx) # subtract -32 from str[i] ('A' - 'a' = -32)
  addq  $1, %rbx # ++i
  movq  %r14, %rdi # seems meaningless here?
  callq strlen@PLT
  cmpq  %rbx, %rax # check i < strlen(str)
  ja    .LBB0_2
.LBB0_3: # end
  addq  $8, %rsp # ???
  popq  %rbx # free registers
  popq  %r14
  retq
```

what does the instruction movq %r14, %rdi is doing? It seemed meangingless because %r14 holding the string pointer and the rdi is the same.

What the intention of the instruction addq $8, %rsp. Looks clueless.

答:
rdi is a caller-saved register and is hence trashed by the call to strlen.  To preserve its contents, the compiler emitted code to  move its contents to r14, copying it back once every iteration as an argument to strlen.

The addq $8, %rsp instruction releases stack space previously allocated by pushq %rax.  This stack space was allocated to satisfy the stack alignment requirements imposed by the amd64 SysV ABI.

Refer to the amd64 SysV ABI supplement for the full calling convention and a list of caller/callee saved registers.

Body:
I'm analysing a piece of inefficient code, but some of it is so confusing?

Original code:

#include <string.h>

void lowwer(char *str) {
  for (int i = 0; i < strlen(str); ++i) {
    str[i] -= ('A' - 'a');
  }
}

Assembly code (generated by clang 13 with -Og option):

lowwer:
  pushq %r14 # use saved-registers
  pushq %rbx
  pushq %rax
  # guard do while
  cmpb  $0, (%rdi) # compare &str with null (check if strlen(str) == 0)
  je    .LBB0_3
  # loop initialization
  movq  %rdi, %r14 # %r14 = str
  xorl  %ebx, %ebx # clear %rbx (for more compact encoding)
.LBB0_2:                                # =>This Inner Loop Header: Depth=1
  addb  $32, (%r14,%rbx) # subtract -32 from str[i] ('A' - 'a' = -32)
  addq  $1, %rbx # ++i
  movq  %r14, %rdi # seems meaningless here?
  callq strlen@PLT
  cmpq  %rbx, %rax # check i < strlen(str)
  ja    .LBB0_2
.LBB0_3: # end
  addq  $8, %rsp # ???
  popq  %rbx # free registers
  popq  %r14
  retq

what does the instruction movq %r14, %rdi is doing? It seemed meangingless because %r14 holding the string pointer and the rdi is the same.

What the intention of the instruction addq $8, %rsp. Looks clueless.


问:
Change guild name and picture in discord.js?
I'm trying to edit my server in discord.js so as soon as I enter a command, it overwrites the name and icon. This is my code:

const Discord = require('discord.js');
const client = new Discord.Client();
const guild = new Discord.Guild();
const { prefix, token } = require('./config.json');

client.once('ready', () => {
    console.log('Ready to launch!');
});

client.login(token);

guild.setIcon('./icon.png');
guild.setName('Guild name');
```

If anyone could help and explain why I'm getting loads of error messages, that'd be great.

答:
I've been using this one:</p>
```<code>client.on("message", async (message) => {
if(message.content.startsWith(";setguildicon")) {
  if (!message.guild.me.permissions.has('MANAGE_SERVER')) {
    const perms = new Discord.MessageEmbed()
    .setTitle(`Bot missing permissions`)
    .setColor(`2f3136`)
    .setDescription(`I need **MANAGE_SERVER** permission in order to change the server's icon!`)
    message.lineReplyNoMention(perms)
   }
  if (!message.member.hasPermission(['ADMINISTRATOR'])) {
    const missingperms = new Discord.MessageEmbed()
    .setTitle(`Missing permissions`)
    .setColor(`2f3136`)
     .setDescription("> **ADMINISTRATOR** permission requiered to change the server icon!");
     message.lineReplyNoMention(missingperms)
} else {
   args = message.content.split(" ").slice(1);
             var argresult = args.join(' ');
             if(argresult) {
               message.channel.send(`Guild icon changed. If it didn't, something may be wrong with the permissions or image link!`)
              message.guild.setIcon(
                `${argresult}`
              ).catch(error => {
                console.log(`error`)
              })
 } else {
   const missingargs = new Discord.MessageEmbed()
.setTitle(`Missing arguments`)
.setDescription(`\`;setguildicon [image link]\``)
.setColor(`2f3136`)
message.lineReplyNoMention(missingargs)
 }
}
}
if(message.content.startsWith(";setguildname")) {
  if (!message.guild.me.permissions.has('MANAGE_SERVER')) {
    const perms = new Discord.MessageEmbed()
    .setTitle(`Bot missing permissions`)
    .setColor(`2f3136`)
    .setDescription(`I need **MANAGE_SERVER** permission in order to change the server's name!`)
    message.lineReplyNoMention(perms)
   }
  if (!message.member.hasPermission(['ADMINISTRATOR'])) {
    const missingperms = new Discord.MessageEmbed()
    .setTitle(`Missing permissions`)
    .setColor(`2f3136`)
     .setDescription("> **ADMINISTRATOR** permission requiered to change the server name!");
     message.lineReplyNoMention(missingperms)
} else {
   args = message.content.split(" ").slice(1);
             var argresult = args.join(' ');
             if(argresult) {
               message.channel.send(`Guild name changed. If it didn't, something may be wrong with the permissions or the name!`)
              message.guild.setName(
                `${argresult}`
              ).catch(error => {
                console.log(`error`)
              })
 } else {
   const missingargs = new Discord.MessageEmbed()
.setTitle(`Missing arguments`)
.setDescription(`\`;setguildname [name]\``)
.setColor(`2f3136`)
message.lineReplyNoMention(missingargs)
 }
}
}
});
</code>```

Body:
I'm trying to edit my server in discord.js so as soon as I enter a command, it overwrites the name and icon. This is my code:

const Discord = require('discord.js');
const client = new Discord.Client();
const guild = new Discord.Guild();
const { prefix, token } = require('./config.json');

client.once('ready', () => {
    console.log('Ready to launch!');
});

client.login(token);

guild.setIcon('./icon.png');
guild.setName('Guild name');

If anyone could help and explain why I'm getting loads of error messages, that'd be great.

Body:
I've been using this one:

client.on("message", async (message) => {
if(message.content.startsWith(";setguildicon")) {
  if (!message.guild.me.permissions.has('MANAGE_SERVER')) {
    const perms = new Discord.MessageEmbed()
    .setTitle(`Bot missing permissions`)
    .setColor(`2f3136`)
    .setDescription(`I need **MANAGE_SERVER** permission in order to change the server's icon!`)
    message.lineReplyNoMention(perms)
   }
  if (!message.member.hasPermission(['ADMINISTRATOR'])) {
    const missingperms = new Discord.MessageEmbed()
    .setTitle(`Missing permissions`)
    .setColor(`2f3136`)
     .setDescription("> **ADMINISTRATOR** permission requiered to change the server icon!");
     message.lineReplyNoMention(missingperms)
} else {
   args = message.content.split(" ").slice(1);
             var argresult = args.join(' ');
             if(argresult) {
               message.channel.send(`Guild icon changed. If it didn't, something may be wrong with the permissions or image link!`)
              message.guild.setIcon(
                `${argresult}`
              ).catch(error => {
                console.log(`error`)
              })
 } else {
   const missingargs = new Discord.MessageEmbed()
.setTitle(`Missing arguments`)
.setDescription(`\`;setguildicon [image link]\``)
.setColor(`2f3136`)
message.lineReplyNoMention(missingargs)
 }
}
}
if(message.content.startsWith(";setguildname")) {
  if (!message.guild.me.permissions.has('MANAGE_SERVER')) {
    const perms = new Discord.MessageEmbed()
    .setTitle(`Bot missing permissions`)
    .setColor(`2f3136`)
    .setDescription(`I need **MANAGE_SERVER** permission in order to change the server's name!`)
    message.lineReplyNoMention(perms)
   }
  if (!message.member.hasPermission(['ADMINISTRATOR'])) {
    const missingperms = new Discord.MessageEmbed()
    .setTitle(`Missing permissions`)
    .setColor(`2f3136`)
     .setDescription("> **ADMINISTRATOR** permission requiered to change the server name!");
     message.lineReplyNoMention(missingperms)
} else {
   args = message.content.split(" ").slice(1);
             var argresult = args.join(' ');
             if(argresult) {
               message.channel.send(`Guild name changed. If it didn't, something may be wrong with the permissions or the name!`)
              message.guild.setName(
                `${argresult}`
              ).catch(error => {
                console.log(`error`)
              })
 } else {
   const missingargs = new Discord.MessageEmbed()
.setTitle(`Missing arguments`)
.setDescription(`\`;setguildname [name]\``)
.setColor(`2f3136`)
message.lineReplyNoMention(missingargs)
 }
}
}
});


问:
How compare array of dates with an date string to find count of same days in JavaScript?
I tried this method to check duplicate date in the array with date string array, but didn't work Please anyone can help..

    const dateArray = ["2000-07-13","03/24/2000", "June 7 2021"]
    const compaingDate =new Date("2000-06-13")
    let countOfDays=0
    for(let sameDate of dateArray){
        if(compaingDate.getDate()===sameDate.getDate()){
            countOfDays+=1
        }
    }
    console.log(countOfDays);```

答:
Maybe this is what you are looking for?

A shorten version:

const dateArray = ["2000-07-13", "03/24/2000", "June 7 2021"]
const compaingDate = new Date("2000-06-13")
let countOfDays = 0
dateArray.forEach(item => {
  if (new Date(item).getDate() === compaingDate.getDate())
    countOfDays++
})
console.log(countOfDays);```


问:
Count Consecutive Days Worked by Name and Date
Fairly new to this so hopefully my query makes sense!

I have a dataset which covers numerous drivers and dates they have worked, example below:

Driver
Date

Steve
11/02/2022

Steve
14/02/2022

Steve
15/02/2022

Steve
16/02/2022

Steve
17/02/2022

Steve
18/02/2022

Steve
20/02/2022

Graham
11/02/2022

Graham
12/02/2022

Graham
14/02/2022

Graham
15/02/2022

Graham
16/02/2022

Graham
18/02/2022

Graham
19/02/2022

Graham
20/02/2022

I am trying to calculate the consecutive days each has worked, to come out as below:

Driver
Date
Days

Steve
11/02/2022
1

Steve
14/02/2022
1

Steve
15/02/2022
2

Steve
16/02/2022
3

Steve
17/02/2022
4

Steve
18/02/2022
5

Steve
20/02/2022
1

Graham
11/02/2022
1

Graham
12/02/2022
2

Graham
14/02/2022
1

Graham
15/02/2022
2

Graham
16/02/2022
3

Graham
18/02/2022
1

Graham
19/02/2022
2

Graham
20/02/2022
3

So far i have managed to find the code below (by Grzegorz Skibinski on here) which seems to work in general. However i am getting some negative values, which seem to be calculated where it resets to 0 more than once. As i say i am fairly new to this and am not totally familiar with what the code is doing. I am just wondering if anything obvious stands out, or if this is not suitable for what i need.

```<code>    df3["Date"]=pd.to_datetime(df3["Date"])
    df3=df3.sort_values(["Driver", "Date"])

    df["Days"]=df.groupby("Driver")["Date"].diff()
    mask=df["Days"].isna()
    df["Days"]=df["Days"].eq(pd.to_timedelta("1 days"))
    df["Days"]=np.where(~df["Days"]&~mask, -df.groupby("Driver")["Days"].cumsum(), df["Days"])
    df["Days"]=df.groupby("Driver")["Days"].cumsum().add(1).astype(int)
</code>```

Many thanks

答:
Assuming that the dates are sorted, you can use:

```<code># ensure datetime type
df['Date'] = pd.to_datetime(df['Date'])

# get non-consecutive days
s = df.groupby('Driver')['Date'].diff().ne('1d')

# groupby consecutive days and  cumulate the counts
df['Days'] = (~s).groupby([df['Driver'], s.cumsum()]).cumsum()+1
</code>```

output:

```<code>    Driver       Date  Days
0    Steve 2022-02-11     1
1    Steve 2022-02-14     1
2    Steve 2022-02-15     2
3    Steve 2022-02-16     3
4    Steve 2022-02-17     4
5    Steve 2022-02-18     5
6    Steve 2022-02-20     1
7   Graham 2022-02-11     1
8   Graham 2022-02-12     2
9   Graham 2022-02-14     1
10  Graham 2022-02-15     2
11  Graham 2022-02-16     3
12  Graham 2022-02-18     1
13  Graham 2022-02-19     2
14  Graham 2022-02-20     3
</code>```

Body:
Fairly new to this so hopefully my query makes sense!

I have a dataset which covers numerous drivers and dates they have worked, example below:

Driver
Date

Steve
11/02/2022

Steve
14/02/2022

Steve
15/02/2022

Steve
16/02/2022

Steve
17/02/2022

Steve
18/02/2022

Steve
20/02/2022

Graham
11/02/2022

Graham
12/02/2022

Graham
14/02/2022

Graham
15/02/2022

Graham
16/02/2022

Graham
18/02/2022

Graham
19/02/2022

Graham
20/02/2022

I am trying to calculate the consecutive days each has worked, to come out as below:

Driver
Date
Days

Steve
11/02/2022
1

Steve
14/02/2022
1

Steve
15/02/2022
2

Steve
16/02/2022
3

Steve
17/02/2022
4

Steve
18/02/2022
5

Steve
20/02/2022
1

Graham
11/02/2022
1

Graham
12/02/2022
2

Graham
14/02/2022
1

Graham
15/02/2022
2

Graham
16/02/2022
3

Graham
18/02/2022
1

Graham
19/02/2022
2

Graham
20/02/2022
3

So far i have managed to find the code below (by Grzegorz Skibinski on here) which seems to work in general. However i am getting some negative values, which seem to be calculated where it resets to 0 more than once. As i say i am fairly new to this and am not totally familiar with what the code is doing. I am just wondering if anything obvious stands out, or if this is not suitable for what i need.

    df3["Date"]=pd.to_datetime(df3["Date"])
    df3=df3.sort_values(["Driver", "Date"])

    df["Days"]=df.groupby("Driver")["Date"].diff()
    mask=df["Days"].isna()
    df["Days"]=df["Days"].eq(pd.to_timedelta("1 days"))
    df["Days"]=np.where(~df["Days"]&~mask, -df.groupby("Driver")["Days"].cumsum(), df["Days"])
    df["Days"]=df.groupby("Driver")["Days"].cumsum().add(1).astype(int)

Many thanks

Body:
Assuming that the dates are sorted, you can use:

# ensure datetime type
df['Date'] = pd.to_datetime(df['Date'])

# get non-consecutive days
s = df.groupby('Driver')['Date'].diff().ne('1d')

# groupby consecutive days and  cumulate the counts
df['Days'] = (~s).groupby([df['Driver'], s.cumsum()]).cumsum()+1

output:

    Driver       Date  Days
0    Steve 2022-02-11     1
1    Steve 2022-02-14     1
2    Steve 2022-02-15     2
3    Steve 2022-02-16     3
4    Steve 2022-02-17     4
5    Steve 2022-02-18     5
6    Steve 2022-02-20     1
7   Graham 2022-02-11     1
8   Graham 2022-02-12     2
9   Graham 2022-02-14     1
10  Graham 2022-02-15     2
11  Graham 2022-02-16     3
12  Graham 2022-02-18     1
13  Graham 2022-02-19     2
14  Graham 2022-02-20     3


问:
Why won't the lighten and darken method pass information to the toString method for final output?
Below is my Java Color class for my intro to Java class. I am attempting to pass the color object created by the lighten and darken method to the toString() method for final output, however every time I attempt to do the output from the toString method is always #000 when it is suppose to be the hex value of the color.</p>
```<code>public class Color {

    private static int red;
    private static int green;
    private static int blue;

    public Color(int r, int g, int b) {
        r = red;
        g = green;
        b = blue;
    }

    public String toString() {
        String ax = Integer.toHexString(Color.red);
        String bx = Integer.toHexString(Color.green);
        String cx = Integer.toHexString(Color.blue);
        return "#" + ax + bx + cx;
    }

    public static Color dim() {
        int xr = ((red * 80)/100);
        if (xr < 0) {xr = 0;}
        int xg = ((green * 80)/100);
        if (xg < 0) {xg = 0;}
        int xb = ((blue * 80)/100);
        if (xb < 0) {xb = 0;}
        return new Color(xr, xg, xb);
    }

    public static Color lighten() {
        int xr = ((red * 120)/100);
        if (xr > 255) {xr = 255;}
        int xg = ((green * 120)/100);
        if (xg > 255) {xg = 255;}
        int xb = ((blue * 120)/100);
        if (xb > 255) {xb = 255;}
        return new Color(xr, xg, xb);
    }
}
</code>```

答:
In java you have Classes and Objects that are instances of those classes. When you declare a field or method as static it will belong to the class and not to the instance. So when you call Color.red, you will get the value of the class field which is not instanced.
The best practice in your case would be to remove the static from your fields (but keep it on your methods) and create getters and setters instead.
This concept is better explained there : http://tutorials.jenkov.com/java/fields.html#static-and-non-static-fields

Body:
Below is my Java Color class for my intro to Java class. I am attempting to pass the color object created by the lighten and darken method to the toString() method for final output, however every time I attempt to do the output from the toString method is always #000 when it is suppose to be the hex value of the color.

public class Color {

    private static int red;
    private static int green;
    private static int blue;

    public Color(int r, int g, int b) {
        r = red;
        g = green;
        b = blue;
    }

    public String toString() {
        String ax = Integer.toHexString(Color.red);
        String bx = Integer.toHexString(Color.green);
        String cx = Integer.toHexString(Color.blue);
        return "#" + ax + bx + cx;
    }

    public static Color dim() {
        int xr = ((red * 80)/100);
        if (xr < 0) {xr = 0;}
        int xg = ((green * 80)/100);
        if (xg < 0) {xg = 0;}
        int xb = ((blue * 80)/100);
        if (xb < 0) {xb = 0;}
        return new Color(xr, xg, xb);
    }

    public static Color lighten() {
        int xr = ((red * 120)/100);
        if (xr > 255) {xr = 255;}
        int xg = ((green * 120)/100);
        if (xg > 255) {xg = 255;}
        int xb = ((blue * 120)/100);
        if (xb > 255) {xb = 255;}
        return new Color(xr, xg, xb);
    }
}


问:
How to get value of $1 parameter from executed prepared statement (inside a trigger using a current_query())
In a trigger I want to see what sql query triggered this trigger. I used current_query() function of postgresql (8.4).

Everything is fine, but if trigger is executed by prepared statement I get placeholders ($1) instead of correct values. for example (logged query):

```<code>delete from some_table where id=$1
</code>```

Is there a way to get/have this values/parameters?

Edited (example added):

```<code>--table for saving query
create table log_table (
query text
)

--table for trigger
create table some_table (
id text
)
--function itself
CREATE FUNCTION save_query() RETURNS trigger AS $$
    switch $TG_op {
    DELETE {
            spi_exec "INSERT INTO log_table (query) VALUES (current_query())"
        }
    default {
            return OK
        }
    }
    return OK
$$ LANGUAGE pltcl;
</code>```

Creating a trigger:

```<code>create trigger test_trigger before delete on some_table for each row execute procedure save_query();
</code>```

Prepared statement is executed from hibernate.

Edit again (java part added)

```<code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DeleteUsingPreparedStmt {

    public static void main(String[] args) {
        try {
            String deleteString = "delete from floors where id = ? ";
            final int idToDelte = 1;

            Class.forName("org.postgresql.Driver");
            String url = "jdbc:postgresql://127.0.0.1:5432/YOUR_DATABASE";
            Connection conn = DriverManager.getConnection(url, "user", "password");

            PreparedStatement deleteStmt = conn.prepareStatement(deleteString);
            deleteStmt.setInt(1, idToDelte);
            deleteStmt.executeUpdate();
        } catch (Exception e) {
            //hide me :)
        }
    }
}
</code>```

You need a jdbc driver - click.

答:
Here is some working code (for Debian users: just install postgresql-pltcl-8.4 package and run CREATE LANGUAGE pltcl;)

```<code>CREATE TABLE log_table (
    id serial,
    query text
);

CREATE TABLE floors (
    id serial,
    value text
);

INSERT INTO floors(value) VALUES ('aaa'), ('bbb');

CREATE OR REPLACE FUNCTION save_query() RETURNS trigger AS $$
    switch $TG_op {
        DELETE {
            spi_exec "INSERT INTO log_table (query) VALUES (current_query())"
        }
        default {
            return OK
        }
    }
    return OK
$$ LANGUAGE pltcl;

CREATE TRIGGER test_trigger
    BEFORE DELETE ON floors
    FOR EACH ROW
    EXECUTE PROCEDURE save_query();
</code>```

However I can't get placeholders in prepared statement (it returns EXECUTE deleteFromFloors(2);):

```<code>TABLE log_table;
 id | query
----+-------
(0 rows)
DELETE FROM floors WHERE id = 1;
DELETE 1
TABLE log_table;
 id |              query
----+----------------------------------
  1 | DELETE FROM floors WHERE id = 1;
(1 row)
PREPARE deleteFromFloors(integer) AS
    DELETE FROM floors WHERE id = $1;
PREPARE
EXECUTE deleteFromFloors(2);
DELETE 1
TABLE log_table;
 id |              query
----+----------------------------------
  1 | DELETE FROM floors WHERE id = 1;
  2 | EXECUTE deleteFromFloors(2);
(2 rows)
</code>```

EDIT:

As a workaround use OLD record (represented as array in Tcl), fetch id column from there and use replace function to put it instead of $1. Here you have two solutions: PL/pgSQL and PL/Tcl:

```<code>CREATE OR REPLACE FUNCTION save_query() RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO log_table (query)
        VALUES (replace(current_query(), '$1', OLD.id::text));
    RETURN OLD;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION save_query() RETURNS trigger AS $$
    switch $TG_op {
        DELETE {
            spi_exec "INSERT INTO log_table (query)
                VALUES (replace(current_query(), '\$1', '$OLD(id)'))"
        }
        default {
            return OK
        }
    }
    return OK
$$ LANGUAGE pltcl;
</code>```

Result:

```<code>java -classpath '.:postgresql-8.4-702.jdbc4.jar' DeleteUsingPreparedStmt

TABLE log_table;
 id |              query
----+---------------------------------
  1 | delete from floors where id = 1
</code>```

(1 row)

ContentLicense: CC BY-SA 3.0

Body:
In a trigger I want to see what sql query triggered this trigger. I used current_query() function of postgresql (8.4).

Everything is fine, but if trigger is executed by prepared statement I get placeholders ($1) instead of correct values. for example (logged query):

delete from some_table where id=$1

Is there a way to get/have this values/parameters?

Edited (example added):

--table for saving query
create table log_table (
query text
)

--table for trigger
create table some_table (
id text
)
--function itself
CREATE FUNCTION save_query() RETURNS trigger AS $$
    switch $TG_op {
    DELETE {
            spi_exec "INSERT INTO log_table (query) VALUES (current_query())"
        }
    default {
            return OK
        }
    }
    return OK
$$ LANGUAGE pltcl;

Creating a trigger:

create trigger test_trigger before delete on some_table for each row execute procedure save_query();

Prepared statement is executed from hibernate.

Edit again (java part added)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DeleteUsingPreparedStmt {

    public static void main(String[] args) {
        try {
            String deleteString = "delete from floors where id = ? ";
            final int idToDelte = 1;

            Class.forName("org.postgresql.Driver");
            String url = "jdbc:postgresql://127.0.0.1:5432/YOUR_DATABASE";
            Connection conn = DriverManager.getConnection(url, "user", "password");

            PreparedStatement deleteStmt = conn.prepareStatement(deleteString);
            deleteStmt.setInt(1, idToDelte);
            deleteStmt.executeUpdate();
        } catch (Exception e) {
            //hide me :)
        }
    }
}

You need a jdbc driver - click.

Body:
Here is some working code (for Debian users: just install postgresql-pltcl-8.4 package and run CREATE LANGUAGE pltcl;)

CREATE TABLE log_table (
    id serial,
    query text
);

CREATE TABLE floors (
    id serial,
    value text
);

INSERT INTO floors(value) VALUES ('aaa'), ('bbb');

CREATE OR REPLACE FUNCTION save_query() RETURNS trigger AS $$
    switch $TG_op {
        DELETE {
            spi_exec "INSERT INTO log_table (query) VALUES (current_query())"
        }
        default {
            return OK
        }
    }
    return OK
$$ LANGUAGE pltcl;

CREATE TRIGGER test_trigger
    BEFORE DELETE ON floors
    FOR EACH ROW
    EXECUTE PROCEDURE save_query();

However I can't get placeholders in prepared statement (it returns EXECUTE deleteFromFloors(2);):

TABLE log_table;
 id | query
----+-------
(0 rows)
DELETE FROM floors WHERE id = 1;
DELETE 1
TABLE log_table;
 id |              query
----+----------------------------------
  1 | DELETE FROM floors WHERE id = 1;
(1 row)
PREPARE deleteFromFloors(integer) AS
    DELETE FROM floors WHERE id = $1;
PREPARE
EXECUTE deleteFromFloors(2);
DELETE 1
TABLE log_table;
 id |              query
----+----------------------------------
  1 | DELETE FROM floors WHERE id = 1;
  2 | EXECUTE deleteFromFloors(2);
(2 rows)

EDIT:

As a workaround use OLD record (represented as array in Tcl), fetch id column from there and use replace function to put it instead of $1. Here you have two solutions: PL/pgSQL and PL/Tcl:

CREATE OR REPLACE FUNCTION save_query() RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO log_table (query)
        VALUES (replace(current_query(), '$1', OLD.id::text));
    RETURN OLD;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION save_query() RETURNS trigger AS $$
    switch $TG_op {
        DELETE {
            spi_exec "INSERT INTO log_table (query)
                VALUES (replace(current_query(), '\$1', '$OLD(id)'))"
        }
        default {
            return OK
        }
    }
    return OK
$$ LANGUAGE pltcl;

Result:

java -classpath '.:postgresql-8.4-702.jdbc4.jar' DeleteUsingPreparedStmt

TABLE log_table;
 id |              query
----+---------------------------------
  1 | delete from floors where id = 1

(1 row)


问:
Excel formula to extract string between 2 specific character
I have a data table that looks like this:

And am using the following forumula:
=MID(LEFT(F2,FIND("D",F2)-1),FIND(" ",F2)+1,LEN(F2))

With the goal of extracting the numeric value after the "D" character in my Visit column. Some visits have 1 digit after the "D", some are 2, max will be 3 digits. However, the formula I've tried to use above is returning blanks and #VALUE! only. I figured the number character between the D and the space would work, but then I realize not all will have the space (see C2D16). Can someone explain what I am doing incorrectly?

TIA

答:
EDIT

Here is an explanation of how the below formula works,

```<code>=MAX(IFERROR(MID(SUBSTITUTE($F2,"PREDOSE",""),ROW($1:$10),3)/1,""))
</code>```

First we are removing or substituting the word PREDOSE from the string, even if we don't have the word the function shall ignore and leave it as it is

```<code>=SUBSTITUTE($F2," PREDOSE","")
</code>```

Next we are wrapping the formula with an MID function and for the start number we are using ROW function which breaks the string into 10 segments

```<code>=MID(SUBSTITUTE($F2," PREDOSE",""),ROW($1:$10),3)
</code>```

On selecting the formula & press F9 or if you goto Formulas tab and evaluate you shall see it gives us an array

```<code>{"C2D";"2D1";"D1";"1";"";"";"";"";"";""}
</code>```

Therefore we need to ignore the text part from the array, so we can either multiply by 1, divide by 1, add 0 or we can use double minus(--) which negates the text values as #VALUE! error while leaves the numeric part

So, to exclude the error values we just wrap it within an IFERROR Function

```<code>=IFERROR(--MID(SUBSTITUTE($F2," PREDOSE",""),ROW($1:$10),3),"")
</code>```

Which again on selecting and pressing F9 shall give us an array of number and blanks

```<code>{"";"";"";1;"";"";"";"";"";""}
</code>```

Last but not least, we need the numeric as an output, hence MAX comes to save us

```<code>=MAX(IFERROR(--MID(SUBSTITUTE($F2," PREDOSE",""),ROW($1:$10),3),""))
</code>```

and gives an output as we desire!

Body:
EDIT

Here is an explanation of how the below formula works,

=MAX(IFERROR(MID(SUBSTITUTE($F2,"PREDOSE",""),ROW($1:$10),3)/1,""))

First we are removing or substituting the word PREDOSE from the string, even if we don't have the word the function shall ignore and leave it as it is

=SUBSTITUTE($F2," PREDOSE","")

Next we are wrapping the formula with an MID function and for the start number we are using ROW function which breaks the string into 10 segments

=MID(SUBSTITUTE($F2," PREDOSE",""),ROW($1:$10),3)

On selecting the formula & press F9 or if you goto Formulas tab and evaluate you shall see it gives us an array

{"C2D";"2D1";"D1";"1";"";"";"";"";"";""}

Therefore we need to ignore the text part from the array, so we can either multiply by 1, divide by 1, add 0 or we can use double minus(--) which negates the text values as #VALUE! error while leaves the numeric part

So, to exclude the error values we just wrap it within an IFERROR Function

=IFERROR(--MID(SUBSTITUTE($F2," PREDOSE",""),ROW($1:$10),3),"")

Which again on selecting and pressing F9 shall give us an array of number and blanks

{"";"";"";1;"";"";"";"";"";""}

Last but not least, we need the numeric as an output, hence MAX comes to save us

=MAX(IFERROR(--MID(SUBSTITUTE($F2," PREDOSE",""),ROW($1:$10),3),""))

and gives an output as we desire!


问:
Jmeter: Access all results from all threadGroups from JSR223 Sampler or BeanShell Sampler in TeardownThread
is there a way to get info about all requests in the mentioned samplers after main thread group finished? In TeardownThread maybe?
I want to perform some calculation and send couple request which are based on info about those requests and it is to resource consuming to do it with sampler for each of the requests.</p>

答:
No.

The options are in:

Parse the .jtl results file

Use the JSR23 Listener in the main Thread Group. The Listeners obey JMeter Scoping Rules if you don't want your code to run after all samplers

Create a JMeter Plugin, the most suitable option for your case would be your own implementation of Backend Listener


问:
Why is the .__proto__ of the base object in Javascript null instead of undefined?
```<code>var a = {};
console.log(a.__proto__); // shows the base object
console.log(a.__proto__.__proto__); // shows the prototype of the base object as "null".
</code>```

Why isn't it undefined (as it is never declared as a property in the base object)?

答:
null indicates an intentional absence of a value, typically of an object value. From the spec:

null value

primitive value that represents the intentional absence of any object value

In contrast, for undefined it says:

undefined value

primitive value used when a variable has not been assigned a value

Object.prototype's prototype is intentionlly set to indicate that there's no prototype, and separately prototype objects are, well, objects, so null for "no object" makes the most sense.

That said, beware of "why" questions with JavaScript, because although most of them have perfectly reasonable explanations, some of the most odd things just come down to "Because that's what Brendan Eich thought he should do at the time" and/or "Because there was a bug in the original implementation that got copied by other implementations and couldn't be changed without breaking existing code, so it had to be put in the spec." (For instance, that's why typeof null is "object" rather than "null".) I'm not saying don't ask "why" questions, because again, often there's a good reason that can lead to a better understanding of the language. Just beware that sometimes, well, there just isn't.

Body:
var a = {};
console.log(a.__proto__); // shows the base object
console.log(a.__proto__.__proto__); // shows the prototype of the base object as "null".

Why isn't it undefined (as it is never declared as a property in the base object)?


问:
Android Studio Mediaplayer
I am a completely begginer guy in Android Studio and mobile apps in general. I used to create websites on Wordpress and i don't have so much experience on coding. Recently i started experimenting with mobile apps and mostly Android Studio. I bought a template for a Logo Quiz game and i managed to make it run without errors and publish it in Play Store as my first game. The player can see a part of the logo and guess the brand name using the given letters

But i would like to use the same template with new graphics and create a music quiz.

Instead of the logo guess game, the player will be able to listen a part of a song and guess the song's title.

The current project is getting the file names from a database stored in assets/databases folder.

So i managed to add start, pause and stop buttons in my activity_play.xml and succesfully created a mediaplayer in activityPlay.java file like:

```<code>public void music(View view) {
        switch (view.getId()){
            case R.id.button:
                // Check if mediaPlayer is null. If true, we'll instantiate the MediaPlayer object
                if(mediaPlayer == null){
                    mediaPlayer = MediaPlayer.create(this, R.raw.music);
                }
                // Then, register OnCompletionListener that calls a user supplied callback method onCompletion() when
                // looping mode was set to false to indicate playback is completed.
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        // Here, call a method to release the MediaPlayer object and to set it to null.
                        stopMusic();
                    }
                });
                // Next, call start() method on mediaPlayer to start playing the music.
                mediaPlayer.start();
                break;
            case R.id.button2:
                if(mediaPlayer != null) {
                    // Here, call pause() method on mediaPlayer to pause the music.
                    mediaPlayer.pause();
                }
                break;
            case R.id.button3:
                if(mediaPlayer != null){
                    // Here, call stop() method on mediaPlayer to stop the music.
                    mediaPlayer.stop();
                    // Call stopMusic() method
                    stopMusic();
                }
                break;
        }
    }

    private void stopMusic() {
        mediaPlayer.release();
        mediaPlayer = null;
    }

    // Call stopMusic() in onStop() overridden method as well.
    @Override
    protected void onStop() {
        super.onStop();
        stopMusic();
    }
</code>```

The above code can succesfully play the music.mp3 file located in raw folder. The app i bought is using the following code to load the images and display them for each level:

```<code>        String image_a = listDataBase.get(1);
        String image_q = listDataBase.get(2);

        if (isTrue == 1) {
            String imgPath;
            if (numImage == 0) {
                imgPath = "file:///android_asset/logos/" + image_a;
            } else {
                imgPath = "file:///android_asset/logos/" + image_q;
            }
            Picasso.get().load(imgPath).into(imageView);
            linearLayoutNullClick.setVisibility(View.VISIBLE);
            recyclerViewKeys.setVisibility(View.GONE);
            trueLogo = 2;
        } else {
            String imgPath = "file:///android_asset/logos/" + image_q;
            Picasso.get().load(imgPath).into(imageView);
            recyclerViewKeys.setVisibility(View.VISIBLE);
            recyclerViewLogoKeys.setVisibility(View.VISIBLE);
        }
</code>```

So is it possible to use the same code and load the imgPath into mediaPlayer = MediaPlayer.create(this, R.raw.music);

I tried loading imgPath directly to mediaplayer like this but didn't work:

```<code>mediaPlayer = MediaPlayer.create(this, imgPath);
</code>```

Then i tried:

```<code>private String audioPath;
audioPath = imgPath;
mediaPlayer = MediaPlayer.create(this, audioPath);
</code>```

but also didn't work.
Tried many more methods i found on the web, but always i am missing something

As i said before i am a newbie in coding and programming so the solution probably will be very easy .
Anyone can help please?

答:
Are you sure you are getting a audio path in your imgPath object?

Then you can try getting actual storage path from device using code mentioned
here

Title: Android Studio Mediaplayer

Body:
I am a completely begginer guy in Android Studio and mobile apps in general. I used to create websites on Wordpress and i don't have so much experience on coding. Recently i started experimenting with mobile apps and mostly Android Studio. I bought a template for a Logo Quiz game and i managed to make it run without errors and publish it in Play Store as my first game. The player can see a part of the logo and guess the brand name using the given letters

But i would like to use the same template with new graphics and create a music quiz.

Instead of the logo guess game, the player will be able to listen a part of a song and guess the song's title.

The current project is getting the file names from a database stored in assets/databases folder.

So i managed to add start, pause and stop buttons in my activity_play.xml and succesfully created a mediaplayer in activityPlay.java file like:

public void music(View view) {
        switch (view.getId()){
            case R.id.button:
                // Check if mediaPlayer is null. If true, we'll instantiate the MediaPlayer object
                if(mediaPlayer == null){
                    mediaPlayer = MediaPlayer.create(this, R.raw.music);
                }
                // Then, register OnCompletionListener that calls a user supplied callback method onCompletion() when
                // looping mode was set to false to indicate playback is completed.
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        // Here, call a method to release the MediaPlayer object and to set it to null.
                        stopMusic();
                    }
                });
                // Next, call start() method on mediaPlayer to start playing the music.
                mediaPlayer.start();
                break;
            case R.id.button2:
                if(mediaPlayer != null) {
                    // Here, call pause() method on mediaPlayer to pause the music.
                    mediaPlayer.pause();
                }
                break;
            case R.id.button3:
                if(mediaPlayer != null){
                    // Here, call stop() method on mediaPlayer to stop the music.
                    mediaPlayer.stop();
                    // Call stopMusic() method
                    stopMusic();
                }
                break;
        }
    }

    private void stopMusic() {
        mediaPlayer.release();
        mediaPlayer = null;
    }

    // Call stopMusic() in onStop() overridden method as well.
    @Override
    protected void onStop() {
        super.onStop();
        stopMusic();
    }

The above code can succesfully play the music.mp3 file located in raw folder. The app i bought is using the following code to load the images and display them for each level:

        String image_a = listDataBase.get(1);
        String image_q = listDataBase.get(2);

        if (isTrue == 1) {
            String imgPath;
            if (numImage == 0) {
                imgPath = "file:///android_asset/logos/" + image_a;
            } else {
                imgPath = "file:///android_asset/logos/" + image_q;
            }
            Picasso.get().load(imgPath).into(imageView);
            linearLayoutNullClick.setVisibility(View.VISIBLE);
            recyclerViewKeys.setVisibility(View.GONE);
            trueLogo = 2;
        } else {
            String imgPath = "file:///android_asset/logos/" + image_q;
            Picasso.get().load(imgPath).into(imageView);
            recyclerViewKeys.setVisibility(View.VISIBLE);
            recyclerViewLogoKeys.setVisibility(View.VISIBLE);
        }

So is it possible to use the same code and load the imgPath into mediaPlayer = MediaPlayer.create(this, R.raw.music);

I tried loading imgPath directly to mediaplayer like this but didn't work:

mediaPlayer = MediaPlayer.create(this, imgPath);

Then i tried:

private String audioPath;
audioPath = imgPath;
mediaPlayer = MediaPlayer.create(this, audioPath);

but also didn't work.
Tried many more methods i found on the web, but always i am missing something

As i said before i am a newbie in coding and programming so the solution probably will be very easy .
Anyone can help please?


问:
Vue js rerender the same component when changing route
I have one auth component that I am using both in the login and the signup route.

```<code>const routes = [{
  path     : '/',
  name: 'home',
  component: Home
}, {
  path     : '/signin',
  name: 'signin',
  component: Auth
},
  {
    path     : '/signup',
    name: 'signup',
    component: Auth
  }];
</code>```

If for example, I'm on the login page The problem is if I type something in the text inputs and go to the signup the text is still there, how I force the component to reinitialize?

答:
You should watch route params and when it changes, re-execute to fetch data.
Example

```<code>created() {
// watch the params of the route to fetch the data again
this.$watch(
  () => this.$route.params,
  () => {
    this.fetchData()
  },
  // fetch the data when the view is created and the data is
  // already being observed
  { immediate: true }
)
</code>```

},

More info at https://router.vuejs.org/guide/advanced/data-fetching.html#fetching-after-navigation

Body:
I have one auth component that I am using both in the login and the signup route.

const routes = [{
  path     : '/',
  name: 'home',
  component: Home
}, {
  path     : '/signin',
  name: 'signin',
  component: Auth
},
  {
    path     : '/signup',
    name: 'signup',
    component: Auth
  }];

If for example, I'm on the login page The problem is if I type something in the text inputs and go to the signup the text is still there, how I force the component to reinitialize?

Body:
You should watch route params and when it changes, re-execute to fetch data.
Example

created() {
// watch the params of the route to fetch the data again
this.$watch(
  () => this.$route.params,
  () => {
    this.fetchData()
  },
  // fetch the data when the view is created and the data is
  // already being observed
  { immediate: true }
)

},

More info at https://router.vuejs.org/guide/advanced/data-fetching.html#fetching-after-navigation


问:
Why doesn't style.display take affect for me?
I'm trying to make a progress indicator and an error message. Initially I set the style="display: none;" attributes.
I would like to change it to style="display: block;" with JS, but my code does not take affect.
Could you please help what am I missing?

HTML part:

```<code><div class="loader" id="loading-indicator" style="display: none;"></div>
    <div class="error-message" id="error-message" style="display: none;">
        An error has occured
    </div>
</code>```

JS part:

```<code>export const initForm = () =>{
    const displayLoadingIndicator = document.getElementById('loading-indicator');
    const errorMessage = document.getElementById('error-message')
    document.getElementById('submit-button').addEventListener('click', async eventObjeckt =>{
        const country = document.querySelector('#country-name').value;
        console.log("CHECKPOINT 4: submit button was pushed");
        console.log(`CHECKPOINT 3: ${country}`);
        eventObjeckt.preventDefault();
        // loadingIndicator START
        displayLoadingIndicator.style.display = "block";
        console.log("After setting displayLoadingIndicator.style.display to 'block' : ", displayLoadingIndicator)
        try{
            getData(country)
        }catch(e){
            errorMessage.style.display = 'block';

        }
        displayLoadingIndicator.style.display = "none";
        console.log("After setting back to displayLoadingIndicator.style.display to 'none': ", displayLoadingIndicator)
        // loadingIndicator END
    })
</code>```

I console.log-ed the HTML elements before and after the .style.display = 'block' commands, but they all look like this:

```<code><div class="loader" id="loading-indicator" style="display: none;"></div>
</code>```

so the .style.display = "block"; did not take effect.

Thank you

答:
JavaScript functions are blocking and console.log is lazy about evaluating objects.

You set it to block, then some JavaScript runs, then you set it back to none. In that time, there is no repaint of the display (because the JS blocks it) and by the time either console.log statement looks at the element it is back to none.

If getData(country) is a time consuming operation, consider farming it off to a Webworker, and setting block when the webworker messages the main process that it has finished doing the work. MDN has a tutorial on webworkers.

Body:
I'm trying to make a progress indicator and an error message. Initially I set the style="display: none;" attributes.
I would like to change it to style="display: block;" with JS, but my code does not take affect.
Could you please help what am I missing?

HTML part:

        An error has occured

JS part:

export const initForm = () =>{
    const displayLoadingIndicator = document.getElementById('loading-indicator');
    const errorMessage = document.getElementById('error-message')
    document.getElementById('submit-button').addEventListener('click', async eventObjeckt =>{
        const country = document.querySelector('#country-name').value;
        console.log("CHECKPOINT 4: submit button was pushed");
        console.log(`CHECKPOINT 3: ${country}`);
        eventObjeckt.preventDefault();
        // loadingIndicator START
        displayLoadingIndicator.style.display = "block";
        console.log("After setting displayLoadingIndicator.style.display to 'block' : ", displayLoadingIndicator)
        try{
            getData(country)
        }catch(e){
            errorMessage.style.display = 'block';

        }
        displayLoadingIndicator.style.display = "none";
        console.log("After setting back to displayLoadingIndicator.style.display to 'none': ", displayLoadingIndicator)
        // loadingIndicator END
    })

I console.log-ed the HTML elements before and after the .style.display = 'block' commands, but they all look like this:

so the .style.display = "block"; did not take effect.

Thank you


问:
create a function using data masking in R
inorder to do a paired analysis i need to write a function that sums integer counts. The total number required to be summed is specified in the corresponding "Yrs_Before" and "Yrs_After" columns in "df".  Is there a way i can avoid writing "fm_after" with just one function? Is this a variable masking for "Yrs_Before", "Yrs_After","Before.Yr_1...n+1" and "After.Yr_1...n+1" columns?

data frame

```<code>set.seed(123)
(df=data.frame(
  Yrs_Before=sample(1:8, 3),
  Yrs_After=sample(1:8, 3),
  Before.Yr_1=sample(1:8, 3),
  Before.Yr_2=sample(1:8, 3),
  Before.Yr_3=sample(1:8, 3),
  Before.Yr_4=sample(1:8, 3),
  Before.Yr_5=sample(1:8, 3),
  Before.Yr_6=sample(1:8, 3),
  Before.Yr_7=sample(1:8, 3),
  Before.Yr_8=sample(1:8, 3),
  After.Yr_1=sample(1:8, 3),
  After.Yr_2=sample(1:8, 3),
  After.Yr_3=sample(1:8, 3),
  After.Yr_4=sample(1:8, 3),
  After.Yr_5=sample(1:8, 3),
  After.Yr_6=sample(1:8, 3),
  After.Yr_7=sample(1:8, 3),
  After.Yr_8=sample(1:8, 3)

))
</code>```

function sums the corresponding rows based on the number of years in the before period.

```<code>fm=function(data,Yrs_Before){
  data |> dplyr::mutate(sums=
  ifelse(
  Yrs_Before == 1, rowSums(across(Before.Yr_1)),
  ifelse(
    Yrs_Before == 2, rowSums(across(Before.Yr_1:Before.Yr_2)),
    ifelse(
      Yrs_Before == 3, rowSums(across(Before.Yr_1:Before.Yr_3)),
      ifelse(
        Yrs_Before == 4, rowSums(across(Before.Yr_1:Before.Yr_4)),
        ifelse(
          Yrs_Before == 5, rowSums(across(Before.Yr_1:Before.Yr_5)),
          ifelse(
            Yrs_Before == 6, rowSums(across(Before.Yr_1:Before.Yr_6)),
            ifelse(
              Yrs_Before == 7, rowSums(across(Before.Yr_1:Before.Yr_7)),
              ifelse(
                Yrs_Before == 8, rowSums(across(Before.Yr_1:Before.Yr_8)),"")))))))))
}

</code>```

output

```<code>
fm(df,Yrs_Before)
Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1 After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 sums
1          7         6           2           5           6           3           3           1           3           1          4          3          4          5          1          4          3          2   23
2          8         3           6           4           1           5           1           8           2           6          6          7          7          7          2          5          6          5   33
3          3         2           3           6           2           8           4           5           7           3          1          5          2          1          3          7          1          7   11

</code>```

duplicated function with variable name changed to "After"

```<code>
fm_after=function(data,Yrs_After){
  data |> dplyr::mutate(sums=
                   ifelse(
                     Yrs_After == 1, rowSums(across(After.Yr_1)),
                     ifelse(
                       Yrs_After == 2, rowSums(across(After.Yr_1:After.Yr_2)),
                       ifelse(
                         Yrs_After == 3, rowSums(across(After.Yr_1:After.Yr_3)),
                         ifelse(
                           Yrs_After == 4, rowSums(across(After.Yr_1:After.Yr_4)),
                           ifelse(
                             Yrs_After == 5, rowSums(across(After.Yr_1:After.Yr_5)),
                             ifelse(
                               Yrs_After == 6, rowSums(across(After.Yr_1:After.Yr_6)),
                               ifelse(
                                 Yrs_After == 7, rowSums(across(After.Yr_1:After.Yr_7)),
                                 ifelse(
                                   Yrs_After == 8, rowSums(across(After.Yr_1:After.Yr_8)),"")))))))))
}

</code>```

output

```<code>fm_after(df,Yrs_After)
Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1 After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 sums
1          7         6           2           5           6           3           3           1           3           1          4          3          4          5          1          4          3          2   21
2          8         3           6           4           1           5           1           8           2           6          6          7          7          7          2          5          6          5   20
3          3         2           3           6           2           8           4           5           7           3          1          5          2          1          3          7          1          7    6

</code>```

UPDATE:

As recommended,  the following tidyverse function was used for counting Before.Yr and After.Yr crash counts.

```<code>sums=function(data,crashes,yrs){
data %>%
  dplyr::rowwise() %>%
    dplyr::transmute(sum = cumsum(c_across(matches(.data[[crashes]])))[.data[[yrs]]])
}
</code>```

however an  error was returned.

```<code>> sums(df,"Before.Yr","Yrs_Before")
Error: Problem with `mutate()` column `sum`.
ℹ `sum = cumsum(c_across(matches(.data[["Before.Yr"]])))[.data[["Yrs_Before"]]]`.
x Column `Before.Yr` not found in `.data`
ℹ The error occurred in row 1.
Run `rlang::last_error()` to see where the error occurred.
</code>```

suggestions for fixing the error?

答:
To avoid so much code you could use paste.

```<code>f <- \(x, dat=df) sapply(seq_len(nrow(dat)), \(i, ...)
                      sum(dat[i, paste0(x, '.Yr_', 1:dat[i, paste0('Yrs_', x)])]))

res <- transform(df, sums_bef=f('Before'), sums_aft=f('After'))
res
#   Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3
# 1          7         6           2           5           6
# 2          8         3           6           4           1
# 3          3         2           3           6           2
#   Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8
# 1           3           3           1           3           1
# 2           5           1           8           2           6
# 3           8           4           5           7           3
#   After.Yr_1 After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5
# 1          4          3          4          5          1
# 2          6          7          7          7          2
# 3          1          5          2          1          3
#   After.Yr_6 After.Yr_7 After.Yr_8 sums_bef sums_aft
# 1          4          3          2       23       21
# 2          5          6          5       33       20
# 3          7          1          7       11        6
</code>```

Data:

```<code>df <- structure(list(Yrs_Before = c(7L, 8L, 3L), Yrs_After = c(6L,
3L, 2L), Before.Yr_1 = c(2L, 6L, 3L), Before.Yr_2 = c(5L, 4L,
6L), Before.Yr_3 = c(6L, 1L, 2L), Before.Yr_4 = c(3L, 5L, 8L),
    Before.Yr_5 = c(3L, 1L, 4L), Before.Yr_6 = c(1L, 8L, 5L),
    Before.Yr_7 = c(3L, 2L, 7L), Before.Yr_8 = c(1L, 6L, 3L),
    After.Yr_1 = c(4L, 6L, 1L), After.Yr_2 = c(3L, 7L, 5L), After.Yr_3 = c(4L,
    7L, 2L), After.Yr_4 = c(5L, 7L, 1L), After.Yr_5 = 1:3, After.Yr_6 = c(4L,
    5L, 7L), After.Yr_7 = c(3L, 6L, 1L), After.Yr_8 = c(2L, 5L,
    7L)), class = "data.frame", row.names = c(NA, -3L))
</code>```

Body:
inorder to do a paired analysis i need to write a function that sums integer counts. The total number required to be summed is specified in the corresponding "Yrs_Before" and "Yrs_After" columns in "df".  Is there a way i can avoid writing "fm_after" with just one function? Is this a variable masking for "Yrs_Before", "Yrs_After","Before.Yr_1...n+1" and "After.Yr_1...n+1" columns?

data frame

set.seed(123)
(df=data.frame(
  Yrs_Before=sample(1:8, 3),
  Yrs_After=sample(1:8, 3),
  Before.Yr_1=sample(1:8, 3),
  Before.Yr_2=sample(1:8, 3),
  Before.Yr_3=sample(1:8, 3),
  Before.Yr_4=sample(1:8, 3),
  Before.Yr_5=sample(1:8, 3),
  Before.Yr_6=sample(1:8, 3),
  Before.Yr_7=sample(1:8, 3),
  Before.Yr_8=sample(1:8, 3),
  After.Yr_1=sample(1:8, 3),
  After.Yr_2=sample(1:8, 3),
  After.Yr_3=sample(1:8, 3),
  After.Yr_4=sample(1:8, 3),
  After.Yr_5=sample(1:8, 3),
  After.Yr_6=sample(1:8, 3),
  After.Yr_7=sample(1:8, 3),
  After.Yr_8=sample(1:8, 3)

))

function sums the corresponding rows based on the number of years in the before period.

fm=function(data,Yrs_Before){
  data |> dplyr::mutate(sums=
  ifelse(
  Yrs_Before == 1, rowSums(across(Before.Yr_1)),
  ifelse(
    Yrs_Before == 2, rowSums(across(Before.Yr_1:Before.Yr_2)),
    ifelse(
      Yrs_Before == 3, rowSums(across(Before.Yr_1:Before.Yr_3)),
      ifelse(
        Yrs_Before == 4, rowSums(across(Before.Yr_1:Before.Yr_4)),
        ifelse(
          Yrs_Before == 5, rowSums(across(Before.Yr_1:Before.Yr_5)),
          ifelse(
            Yrs_Before == 6, rowSums(across(Before.Yr_1:Before.Yr_6)),
            ifelse(
              Yrs_Before == 7, rowSums(across(Before.Yr_1:Before.Yr_7)),
              ifelse(
                Yrs_Before == 8, rowSums(across(Before.Yr_1:Before.Yr_8)),"")))))))))
}

output

fm(df,Yrs_Before)
Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1 After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 sums
1          7         6           2           5           6           3           3           1           3           1          4          3          4          5          1          4          3          2   23
2          8         3           6           4           1           5           1           8           2           6          6          7          7          7          2          5          6          5   33
3          3         2           3           6           2           8           4           5           7           3          1          5          2          1          3          7          1          7   11

duplicated function with variable name changed to "After"

fm_after=function(data,Yrs_After){
  data |> dplyr::mutate(sums=
                   ifelse(
                     Yrs_After == 1, rowSums(across(After.Yr_1)),
                     ifelse(
                       Yrs_After == 2, rowSums(across(After.Yr_1:After.Yr_2)),
                       ifelse(
                         Yrs_After == 3, rowSums(across(After.Yr_1:After.Yr_3)),
                         ifelse(
                           Yrs_After == 4, rowSums(across(After.Yr_1:After.Yr_4)),
                           ifelse(
                             Yrs_After == 5, rowSums(across(After.Yr_1:After.Yr_5)),
                             ifelse(
                               Yrs_After == 6, rowSums(across(After.Yr_1:After.Yr_6)),
                               ifelse(
                                 Yrs_After == 7, rowSums(across(After.Yr_1:After.Yr_7)),
                                 ifelse(
                                   Yrs_After == 8, rowSums(across(After.Yr_1:After.Yr_8)),"")))))))))
}

output

fm_after(df,Yrs_After)
Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1 After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 sums
1          7         6           2           5           6           3           3           1           3           1          4          3          4          5          1          4          3          2   21
2          8         3           6           4           1           5           1           8           2           6          6          7          7          7          2          5          6          5   20
3          3         2           3           6           2           8           4           5           7           3          1          5          2          1          3          7          1          7    6

UPDATE:

As recommended,  the following tidyverse function was used for counting Before.Yr and After.Yr crash counts.

sums=function(data,crashes,yrs){
data %>%
  dplyr::rowwise() %>%
    dplyr::transmute(sum = cumsum(c_across(matches(.data[[crashes]])))[.data[[yrs]]])
}

however an  error was returned.

> sums(df,"Before.Yr","Yrs_Before")
Error: Problem with `mutate()` column `sum`.
ℹ `sum = cumsum(c_across(matches(.data[["Before.Yr"]])))[.data[["Yrs_Before"]]]`.
x Column `Before.Yr` not found in `.data`
ℹ The error occurred in row 1.
Run `rlang::last_error()` to see where the error occurred.

suggestions for fixing the error?

Body:
To avoid so much code you could use paste.

f <- \(x, dat=df) sapply(seq_len(nrow(dat)), \(i, ...)
                      sum(dat[i, paste0(x, '.Yr_', 1:dat[i, paste0('Yrs_', x)])]))

res <- transform(df, sums_bef=f('Before'), sums_aft=f('After'))
res
#   Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3
# 1          7         6           2           5           6
# 2          8         3           6           4           1
# 3          3         2           3           6           2
#   Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8
# 1           3           3           1           3           1
# 2           5           1           8           2           6
# 3           8           4           5           7           3
#   After.Yr_1 After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5
# 1          4          3          4          5          1
# 2          6          7          7          7          2
# 3          1          5          2          1          3
#   After.Yr_6 After.Yr_7 After.Yr_8 sums_bef sums_aft
# 1          4          3          2       23       21
# 2          5          6          5       33       20
# 3          7          1          7       11        6

Data:

df <- structure(list(Yrs_Before = c(7L, 8L, 3L), Yrs_After = c(6L,
3L, 2L), Before.Yr_1 = c(2L, 6L, 3L), Before.Yr_2 = c(5L, 4L,
6L), Before.Yr_3 = c(6L, 1L, 2L), Before.Yr_4 = c(3L, 5L, 8L),
    Before.Yr_5 = c(3L, 1L, 4L), Before.Yr_6 = c(1L, 8L, 5L),
    Before.Yr_7 = c(3L, 2L, 7L), Before.Yr_8 = c(1L, 6L, 3L),
    After.Yr_1 = c(4L, 6L, 1L), After.Yr_2 = c(3L, 7L, 5L), After.Yr_3 = c(4L,
    7L, 2L), After.Yr_4 = c(5L, 7L, 1L), After.Yr_5 = 1:3, After.Yr_6 = c(4L,
    5L, 7L), After.Yr_7 = c(3L, 6L, 1L), After.Yr_8 = c(2L, 5L,
    7L)), class = "data.frame", row.names = c(NA, -3L))


问:
How to make view that uses a web scraper load faster
I have a view that outputs destination city results on a page. As part of the view, a web scraper searches for flight prices from the user's area to the destination city. After adding the web scraper to the view it now takes about 8 seconds to load. I was wondering how I can make the view load quicker, maybe with threading or another alternative.

views.py

```<code>def results(request, result1, result2, result3, result4, result5, result6, broad_variable1, broad_variable2, broad_variable3, specific_variable_dictionary, user_city):
    result1 = City.objects.filter(city=result1).first()
    result2 = City.objects.filter(city=result2).first()
    result3 = City.objects.filter(city=result3).first()
    result4 = City.objects.filter(city=result4).first()
    result5 = City.objects.filter(city=result5).first()
    result6 = City.objects.filter(city=result6).first()

    # get the first user selected specific variable value for each result
    result1_value1 = City.objects.filter(city=result1.city).values(broad_variable1)[0][broad_variable1]
    result2_value1 = City.objects.filter(city=result2.city).values(broad_variable1)[0][broad_variable1]
    result3_value1 = City.objects.filter(city=result3.city).values(broad_variable1)[0][broad_variable1]
    result4_value1 = City.objects.filter(city=result4.city).values(broad_variable1)[0][broad_variable1]
    result5_value1 = City.objects.filter(city=result5.city).values(broad_variable1)[0][broad_variable1]
    result6_value1 = City.objects.filter(city=result6.city).values(broad_variable1)[0][broad_variable1]

    # assign variables before referencing them
    result1_value2 = None
    result2_value2 = None
    result3_value2 = None
    result4_value2 = None
    result5_value2 = None
    result6_value2 = None

    # check if the user chose a second variable
    # get the second user selected specific variable value for each result
    if broad_variable2 != "Nothing":
        result1_value2 = City.objects.filter(city=result1.city).values(broad_variable2)[0][broad_variable2]
        result2_value2 = City.objects.filter(city=result2.city).values(broad_variable2)[0][broad_variable2]
        result3_value2 = City.objects.filter(city=result3.city).values(broad_variable2)[0][broad_variable2]
        result4_value2 = City.objects.filter(city=result4.city).values(broad_variable2)[0][broad_variable2]
        result5_value2 = City.objects.filter(city=result5.city).values(broad_variable2)[0][broad_variable2]
        result6_value2 = City.objects.filter(city=result6.city).values(broad_variable2)[0][broad_variable2]

    # assign variables before referencing them
    result1_value3 = None
    result2_value3 = None
    result3_value3 = None
    result4_value3 = None
    result5_value3 = None
    result6_value3 = None

    # check if the user chose a third variable
    # get the third user selected specific variable value for each result
    if broad_variable3 != "Nothing":
        result1_value3 = City.objects.filter(city=result1.city).values(broad_variable3)[0][broad_variable3]
        result2_value3 = City.objects.filter(city=result2.city).values(broad_variable3)[0][broad_variable3]
        result3_value3 = City.objects.filter(city=result3.city).values(broad_variable3)[0][broad_variable3]
        result4_value3 = City.objects.filter(city=result4.city).values(broad_variable3)[0][broad_variable3]
        result5_value3 = City.objects.filter(city=result5.city).values(broad_variable3)[0][broad_variable3]
        result6_value3 = City.objects.filter(city=result6.city).values(broad_variable3)[0][broad_variable3]

    # create list of cities
    city_list = [result1.city, result2.city, result3.city, result4.city, result5.city, result6.city]

    # create price list
    prices_list = []

    # set origin for flight
    origin = user_city

    # set headers
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36"
    }

    for city in city_list:

        # set search query
        url = "https://google.com/search?q=" + origin + " to " + city + " Google Flights"

        response = requests.get(url, headers=headers)

        soup = BeautifulSoup(response.text, 'lxml')

        # get price element
        prices = soup.find("span", attrs={"class": "GARawf"})
        if prices != None:
            prices_list.append(prices.text.strip())
        else:
            prices_list.append("Not Available")

    # change string dictionary into actual dictionary
    specific_variable_dictionary = ast.literal_eval(specific_variable_dictionary)

    context = {
        "result1": result1, "result2": result2, "result3": result3, "result4": result4, "result5": result5,
        "result6": result6, "result1_value1": result1_value1, "result2_value1": result2_value1, "result3_value1": result3_value1,
        "result4_value1": result4_value1, "result5_value1": result5_value1, "result6_value1": result6_value1, "result1_value2": result1_value2,
        "result2_value2": result2_value2, "result3_value2": result3_value2, "result4_value2": result4_value2,
        "result5_value2": result5_value2, "result6_value2": result6_value2, "result1_value3": result1_value3, "result2_value3": result2_value3,
        "result3_value3": result3_value3, "result4_value3": result4_value3, "result5_value3": result5_value3, "result6_value3": result6_value3,
        "broad_variable1": broad_variable1, "broad_variable2": broad_variable2, "broad_variable3": broad_variable3,
        "specific_variable_dictionary": specific_variable_dictionary, "prices_list": prices_list
    }
    return render(request, 'Discovery_App/results.html', context)
</code>```

答:
The low-hanging fruit is probably the lack of caching. You should cache the results for the same origin/destination, at least for some time. You can do this inside Python, in the database you are using, or inside an external cache like Redis or Memcached. If you don't want to bother with dependencies, just creating a file is also an option.

With or without the caching, another way to improve the page speed is loading an empty page quickly, and then filling in the scraper data with Javascript using something like the Fetch API.

Body:
I have a view that outputs destination city results on a page. As part of the view, a web scraper searches for flight prices from the user's area to the destination city. After adding the web scraper to the view it now takes about 8 seconds to load. I was wondering how I can make the view load quicker, maybe with threading or another alternative.

views.py

def results(request, result1, result2, result3, result4, result5, result6, broad_variable1, broad_variable2, broad_variable3, specific_variable_dictionary, user_city):
    result1 = City.objects.filter(city=result1).first()
    result2 = City.objects.filter(city=result2).first()
    result3 = City.objects.filter(city=result3).first()
    result4 = City.objects.filter(city=result4).first()
    result5 = City.objects.filter(city=result5).first()
    result6 = City.objects.filter(city=result6).first()

    # get the first user selected specific variable value for each result
    result1_value1 = City.objects.filter(city=result1.city).values(broad_variable1)[0][broad_variable1]
    result2_value1 = City.objects.filter(city=result2.city).values(broad_variable1)[0][broad_variable1]
    result3_value1 = City.objects.filter(city=result3.city).values(broad_variable1)[0][broad_variable1]
    result4_value1 = City.objects.filter(city=result4.city).values(broad_variable1)[0][broad_variable1]
    result5_value1 = City.objects.filter(city=result5.city).values(broad_variable1)[0][broad_variable1]
    result6_value1 = City.objects.filter(city=result6.city).values(broad_variable1)[0][broad_variable1]

    # assign variables before referencing them
    result1_value2 = None
    result2_value2 = None
    result3_value2 = None
    result4_value2 = None
    result5_value2 = None
    result6_value2 = None

    # check if the user chose a second variable
    # get the second user selected specific variable value for each result
    if broad_variable2 != "Nothing":
        result1_value2 = City.objects.filter(city=result1.city).values(broad_variable2)[0][broad_variable2]
        result2_value2 = City.objects.filter(city=result2.city).values(broad_variable2)[0][broad_variable2]
        result3_value2 = City.objects.filter(city=result3.city).values(broad_variable2)[0][broad_variable2]
        result4_value2 = City.objects.filter(city=result4.city).values(broad_variable2)[0][broad_variable2]
        result5_value2 = City.objects.filter(city=result5.city).values(broad_variable2)[0][broad_variable2]
        result6_value2 = City.objects.filter(city=result6.city).values(broad_variable2)[0][broad_variable2]

    # assign variables before referencing them
    result1_value3 = None
    result2_value3 = None
    result3_value3 = None
    result4_value3 = None
    result5_value3 = None
    result6_value3 = None

    # check if the user chose a third variable
    # get the third user selected specific variable value for each result
    if broad_variable3 != "Nothing":
        result1_value3 = City.objects.filter(city=result1.city).values(broad_variable3)[0][broad_variable3]
        result2_value3 = City.objects.filter(city=result2.city).values(broad_variable3)[0][broad_variable3]
        result3_value3 = City.objects.filter(city=result3.city).values(broad_variable3)[0][broad_variable3]
        result4_value3 = City.objects.filter(city=result4.city).values(broad_variable3)[0][broad_variable3]
        result5_value3 = City.objects.filter(city=result5.city).values(broad_variable3)[0][broad_variable3]
        result6_value3 = City.objects.filter(city=result6.city).values(broad_variable3)[0][broad_variable3]

    # create list of cities
    city_list = [result1.city, result2.city, result3.city, result4.city, result5.city, result6.city]

    # create price list
    prices_list = []

    # set origin for flight
    origin = user_city

    # set headers
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36"
    }

    for city in city_list:

        # set search query
        url = "https://google.com/search?q=" + origin + " to " + city + " Google Flights"

        response = requests.get(url, headers=headers)

        soup = BeautifulSoup(response.text, 'lxml')

        # get price element
        prices = soup.find("span", attrs={"class": "GARawf"})
        if prices != None:
            prices_list.append(prices.text.strip())
        else:
            prices_list.append("Not Available")

    # change string dictionary into actual dictionary
    specific_variable_dictionary = ast.literal_eval(specific_variable_dictionary)

    context = {
        "result1": result1, "result2": result2, "result3": result3, "result4": result4, "result5": result5,
        "result6": result6, "result1_value1": result1_value1, "result2_value1": result2_value1, "result3_value1": result3_value1,
        "result4_value1": result4_value1, "result5_value1": result5_value1, "result6_value1": result6_value1, "result1_value2": result1_value2,
        "result2_value2": result2_value2, "result3_value2": result3_value2, "result4_value2": result4_value2,
        "result5_value2": result5_value2, "result6_value2": result6_value2, "result1_value3": result1_value3, "result2_value3": result2_value3,
        "result3_value3": result3_value3, "result4_value3": result4_value3, "result5_value3": result5_value3, "result6_value3": result6_value3,
        "broad_variable1": broad_variable1, "broad_variable2": broad_variable2, "broad_variable3": broad_variable3,
        "specific_variable_dictionary": specific_variable_dictionary, "prices_list": prices_list
    }
    return render(request, 'Discovery_App/results.html', context)


问:
How to add a libgcc.a library to my keil project
I need to make a library for a customer who is using GCC. I have a working Keil project compiled with the GCC. The next step is to make a library. I removed from the project main file and Keil generated libname.a library file. Now I want to create a new project with the same main and libname.a library. I'm failing to do so. I added this library to Options/Linker tab, added library path and getting "c:/gnu arm embedded toolchain/10p3_2021_10/bin/../lib/gcc/arm-none-eabi/10.3.1/../../../../arm-none-eabi/bin/ld.exe: cannot find -llibname.a
Here is all the options/flags:

-mcpu=cortex-m4 -mthumb -o ./DebugConfig/name_main.elf -L ./DebugConfig *.o -llibname.a -mcpu=cortex-m4 --specs=nosys.specs -Wl,--gc-sections -static -Wl,--start-group -Wl,--end-group --specs=nano.specs -mthumb -Wl,--start-group -lc -lm -Wl,--end-group

Thank you in advance.

答:
All that was needed is to put a colon in front of the name :libname.a ...

I hate fighting with tools.
Here is the solution: I need to add into the misc section separately -L path\lib\one   -l libname
Or -l:name.a

I did not find where it is written that my options are:

-l name    and in this case libname.a file will be searched for;

-l:name.a  and in this case    name.a file is the target library.

Why does it have to be so convoluted and complicated... This is just a rhetorical question, obviously. I hope this will help someone else in the future.


问:
JavaScript arrays with functions
Planned output:

```<code>The array has 10 elements.
The average of the values is 36.1
</code>```

I plan two functions: addNumber() and printInfo().

Function: addNumber() reads a value from a text input field on the HTML document (id="num") and adds it at the end of the array.

Another function: printInfo() outputs the amount of elements in the array to the console, then the average of their values.

HTML document has two buttons for calling the functions.

I wrote:

```<code>let arr = [];
arr.push (function addNumber() {
let element = document.getElementById("num");
})
function printInfo() {
console.log (arr.length );
}
</code>```

How to use buttons for calling the functions in HTML?

How to count average of values in the array?

答:
Hello here is a working example. https://jsfiddle.net/7t41y80m/

HTML Example

```<code><fieldset>
  <legend>Array List</legend>
  <label id="lbl">1,2,3,4,5,6,7,8,9</label>
  <input type="number" id="input">
  <button onclick="AddNumber();">Add Number</button>
</fieldset>
<button onclick="CalculateAvg();">Print Averrage</button>
</code>```

Javascript:

```<code>function CalculateAvg()
{
    const arr = document.getElementById('lbl').innerText.split(',').map(Number);
    const total = arr.reduce((x, y) => x + y, 0);
    const avg = total / arr.length || 0;
    alert(avg);
}

function AddNumber()
{
    document.getElementById('lbl').innerText += `,${document.getElementById('input').value}`;
}
</code>```

Title: JavaScript arrays with functions

Body:
Planned output:

The array has 10 elements.
The average of the values is 36.1

I plan two functions: addNumber() and printInfo().

Function: addNumber() reads a value from a text input field on the HTML document (id="num") and adds it at the end of the array.

Another function: printInfo() outputs the amount of elements in the array to the console, then the average of their values.

HTML document has two buttons for calling the functions.

I wrote:

let arr = [];
arr.push (function addNumber() {
let element = document.getElementById("num");
})
function printInfo() {
console.log (arr.length );
}

How to use buttons for calling the functions in HTML?

How to count average of values in the array?

Body:
Hello here is a working example. https://jsfiddle.net/7t41y80m/

HTML Example

<fieldset>
  <legend>Array List</legend>
  <label id="lbl">1,2,3,4,5,6,7,8,9</label>
  <input type="number" id="input">
  <button onclick="AddNumber();">Add Number</button>
</fieldset>
<button onclick="CalculateAvg();">Print Averrage</button>

Javascript:

function CalculateAvg()
{
    const arr = document.getElementById('lbl').innerText.split(',').map(Number);
    const total = arr.reduce((x, y) => x + y, 0);
    const avg = total / arr.length || 0;
    alert(avg);
}

function AddNumber()
{
    document.getElementById('lbl').innerText += `,${document.getElementById('input').value}`;
}


问:
How can I select all paragraph elements inside nested divs?
I have a reviews that I want to scrape (https://www.consumeraffairs.com/insurance/bluecross_fl.html). The issue that I find is that some reviews aren't stored inside the same structure. In the page you have to press "read full review" and this access another part of the structure that contains the remaining of the review.

The structure for simple reviews is like this:

```<code><div>
   <p>
     review
   </p>
</div>
</code>```

The other reviews structure is like this:

```<code><div>
   <p>
     review
   </p>
   <div>
       <p>
         remaining review
      </p>
   </div>
</div>
</code>```

I have tried something like this but still I'm just getting the first part of the reviews and not the remaining.

response.css('itemprop="reviews"] > div:nth-child(3) > p *::text').extract()

答:
If you use the general child selector you should be able to target all of the p's in divs. Despite the structure.

div > p {
  background-color: #ffd110;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>
    review
  </p>
  <div>
    <p>
      remaining review
    </p>
  </div>
</div>

<div>
  <p>
    review
  </p>
</div></code>```

Edit ~ From requested in the comments, you can concentrate which p gets selected using p:nth-child(2) See below.

div > p:nth-child(2) {
  background-color: #ffd110;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>
    review
  </p>
  <div>
    <p>
      remaining review
    </p>
    <p>review 2</p>
  </div>
</div></code>```

Body:
I have a reviews that I want to scrape (https://www.consumeraffairs.com/insurance/bluecross_fl.html). The issue that I find is that some reviews aren't stored inside the same structure. In the page you have to press "read full review" and this access another part of the structure that contains the remaining of the review.

The structure for simple reviews is like this:

     review

The other reviews structure is like this:

     review

         remaining review

I have tried something like this but still I'm just getting the first part of the reviews and not the remaining.

response.css('itemprop="reviews"] > div:nth-child(3) > p *::text').extract()

Body:
If you use the general child selector you should be able to target all of the p's in divs. Despite the structure.

div > p {
  background-color: #ffd110;
}

<div>
  <p>
    review
  </p>
  <div>
    <p>
      remaining review
    </p>
  </div>
</div>

<div>
  <p>
    review
  </p>
</div>

Edit ~ From requested in the comments, you can concentrate which p gets selected using p:nth-child(2) See below.

div > p:nth-child(2) {
  background-color: #ffd110;
}

<div>
  <p>
    review
  </p>
  <div>
    <p>
      remaining review
    </p>
    <p>review 2</p>
  </div>
</div>


问:
Vue how to search all properties of array
In my vue-app I want to add a search component, so that I can search for different topics.

here is an example of the data:

```<code>persons: [
   {
    name: 'Mr.X',
    gender: 'Male',
    location: {
      address: 'some streetname',
      zipcode: '12345',
      city: 'Berlin',
      lng: 'longitude',
      lat: 'latitude',
    },
    skills: [
     { label: 'foo' },
     { label: 'bar' },
    ],
  },
 ...etc
]
</code>```

Then in my component I use a computed value:

```<code>computed: {
   filteredList() {
     return this.persons.filter((person) => {
       return person.name.toLowerCase().includes(this.search.toLowerCase())
     })
   },
}
</code>```

the HTML is:

```<code><input type="text" v-model="search" />

<div v-for="(person, index) in filteredList" :key="index">
    <p>{{ person.name }}</p>
</div>
</code>```

This of course only searches and returns the name. How can I search on all properties? For example If I search for "Berlin" it should also return the object data.

答:
First of all you need to form an array, which contains all your primitive values, and then filter it.

Here is the function flatten() that puts all values from your structure into the flat array

```<code>const persons = [
   {
    name: 'Mr.X',
    gender: 'Male',
    location: {
      address: 'some streetname',
      zipcode: '12345',
      city: 'Berlin',
      lng: 'longitude',
      lat: 'latitude',
    },
    skills: [
     { label: 'foo' },
     { label: 'bar' },
    ],
  },
]

const flatten = (input) => {
  if (typeof input === 'object') {
    return (Array.isArray(input) ? input : Object.values(input))
      .reduce((acc, x) => acc.concat(flatten(x)), [])
  } else {
    return [input]
  }
}

console.log(flatten(persons))
console.log(flatten(persons).includes('Berlin'))
</code>```

Body:
In my vue-app I want to add a search component, so that I can search for different topics.

here is an example of the data:

persons: [
   {
    name: 'Mr.X',
    gender: 'Male',
    location: {
      address: 'some streetname',
      zipcode: '12345',
      city: 'Berlin',
      lng: 'longitude',
      lat: 'latitude',
    },
    skills: [
     { label: 'foo' },
     { label: 'bar' },
    ],
  },
 ...etc
]

Then in my component I use a computed value:

computed: {
   filteredList() {
     return this.persons.filter((person) => {
       return person.name.toLowerCase().includes(this.search.toLowerCase())
     })
   },
}

the HTML is:

<input type="text" v-model="search" />

{{ person.name }}

This of course only searches and returns the name. How can I search on all properties? For example If I search for "Berlin" it should also return the object data.

Body:
First of all you need to form an array, which contains all your primitive values, and then filter it.

Here is the function flatten() that puts all values from your structure into the flat array

const persons = [
   {
    name: 'Mr.X',
    gender: 'Male',
    location: {
      address: 'some streetname',
      zipcode: '12345',
      city: 'Berlin',
      lng: 'longitude',
      lat: 'latitude',
    },
    skills: [
     { label: 'foo' },
     { label: 'bar' },
    ],
  },
]

const flatten = (input) => {
  if (typeof input === 'object') {
    return (Array.isArray(input) ? input : Object.values(input))
      .reduce((acc, x) => acc.concat(flatten(x)), [])
  } else {
    return [input]
  }
}

console.log(flatten(persons))
console.log(flatten(persons).includes('Berlin'))


问:
Access Database: Averages across two consecutive months
I have a table in an access database with essentially two critical fields: "Period" (as YYYYMM, so e.g. 202111, 202112, 202201 and so on) and, further, a dollar amount as field "Volume Balance". The goal is now to calculate a simple average for every two consecutive months like the bottom table (exemplary numbers, unit is USD):

Input -->

Period
Volume Balance

202101
1

202102
2

202103
3

Desired Result -->

Period
Average Volume Balance

202102
1.5 ((Jan+Feb)/2)

202103
2.5 ((Feb+Mar)/2)

I have played around with the DAvg function but the consecutive period cut-offs are fatal for me. Thank you for any help!

答:
You need a self join:

```<code>SELECT t1.Period,
       (t1.[Volume Balance] + t2.[Volume Balance]) / 2 AS [Average Volume Balance]
FROM tablename AS t1 INNER JOIN tablename AS t2
ON VAL(t1.Period) = VAL(t2.Period) + 1;
</code>```

If the data type of Period is a numeric type then change the ON clause to just:

```<code>ON t1.Period = t2.Period + 1;
</code>```

Body:
You need a self join:

SELECT t1.Period,
       (t1.[Volume Balance] + t2.[Volume Balance]) / 2 AS [Average Volume Balance]
FROM tablename AS t1 INNER JOIN tablename AS t2
ON VAL(t1.Period) = VAL(t2.Period) + 1;

If the data type of Period is a numeric type then change the ON clause to just:

ON t1.Period = t2.Period + 1;


问:
What is the different between using "IN" vs using "=" inside a query?
I'd like to understand the best way to restrict items in a query. For example Query1 returns a list of ID's based of specific detail filters. I would like Query2 to return only items where Query2.ID is the same as Query1.ID.

Which Query2 Detail Filter is better? And why?

Query2.ID IN ( Query1.ID )

Query2.ID = Query1.ID

Note: Using an "=" filter requires Query2's "Cross product allowed" property to be set to "Allow".

答:
IN is usually used to compare against a list, while = compares to a single value.

Examples:

... WHERE id IN (1, 2, 3)
```
<p>vs.</p>
<pre class="lang-sql prettyprint-override"><code>... WHERE id = 1
</code>```

Some documentation regarding Postgresql, which might be useful and similar to the cognos notation.

Body:
IN is usually used to compare against a list, while = compares to a single value.

Examples:

... WHERE id IN (1, 2, 3)

vs.

... WHERE id = 1

Some documentation regarding Postgresql, which might be useful and similar to the cognos notation.


问:
POST REST Call from C#
Trying to do POST rest call to my endpoint, but I want to pass empty body and access token. How can I do that ?

My code is :

```<code>using (var client = new HttpClient())
{
  var endPoint = new Uri("my EndPoint");
  var emptyBody = {}; // Getting an error here, not sure if it is right
  var newPostJson = JsonConvert.SerializeObject(emptyBody);
  var payload = new StringContent(newPostJson, Encoding.UTF8, "application/json");
  var result = client.PostAsync(endPoint, payload).Result.Content.ReadAsStringAsync().Result;
}
</code>```

Can you tell how Can I pass access token and empty body and do you recommend any other change ? It is my first REST CALL.

答:
First, you should only have one instance of HttpClient in your application so that HTTP connections are correctly managed. That class is thread-safe.

Typically, access tokens are passed as an authorization header, like this:

```<code>// Declare HttpClient at the class level
private readonly HttpClient HttpClient = new HttpClient();

// Put this code in your method that needs to make an authenticated request
using var request = new HttpRequestMessage(HttpMethod.Get, myUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await HttpClient.SendAsync(request);

response.EnsureSuccessStatusCode();

var result = await response.Content.ReadAsStringAsync();
</code>```

Title: POST REST Call from C#

Body:
Trying to do POST rest call to my endpoint, but I want to pass empty body and access token. How can I do that ?

My code is :

using (var client = new HttpClient())
{
  var endPoint = new Uri("my EndPoint");
  var emptyBody = {}; // Getting an error here, not sure if it is right
  var newPostJson = JsonConvert.SerializeObject(emptyBody);
  var payload = new StringContent(newPostJson, Encoding.UTF8, "application/json");
  var result = client.PostAsync(endPoint, payload).Result.Content.ReadAsStringAsync().Result;
}

Can you tell how Can I pass access token and empty body and do you recommend any other change ? It is my first REST CALL.

Body:
First, you should only have one instance of HttpClient in your application so that HTTP connections are correctly managed. That class is thread-safe.

Typically, access tokens are passed as an authorization header, like this:

// Declare HttpClient at the class level
private readonly HttpClient HttpClient = new HttpClient();

// Put this code in your method that needs to make an authenticated request
using var request = new HttpRequestMessage(HttpMethod.Get, myUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await HttpClient.SendAsync(request);

response.EnsureSuccessStatusCode();

var result = await response.Content.ReadAsStringAsync();


问:
Least number of stamps needed to pay certain postage
I wrote a C program to solve the stamp and postage problem using brute force. However, it looks really stupid... Is there any better algorithms there to find the fewest number of stamps needed to pay certain postage?</p>
```<code>const int denominations[] = {1, 5, 17, 23, 37, 50};
int stamps[] = {0, 0, 0, 0, 0, 0};

void ALG2(int p) { //p means postage
    int least = p;
    int i[] = {0, 0, 0, 0, 0, 0};

    for (i[0] = 0; i[0] <= p / denominations[0]; i[0]++) {
        for (i[1] = 0; i[1] <= p / denominations[1]; i[1]++) {
            for (i[2] = 0; i[2] <= p / denominations[2]; i[2]++) {
                for (i[3] = 0; i[3] <= p / denominations[3]; i[3]++) {
                    for (i[4] = 0; i[4] <= p / denominations[4]; i[4]++) {
                        for (i[5] = 0; i[5] <= p / denominations[5]; i[5]++) {
                            if (getSum(i) == p) {
                                if (getCount(i) < least) {
                                    least = getCount(i);
                                    for (int j = 0; j < 6; j++)
                                        stamps[j] = i[j];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</code>```

答:
Is there any better algorithms there to find the fewest number of stamps needed to pay certain postage?

Some ideas:

Rather than for (i[n] = 0; i[n] <= p / denominations[n]; i[n]++) {, only need to loop to for (i[n] = 0; i[n] <= (p - current_sum)/ denominations[n]; i[n]++) {

Loop first with largest denomination stamps first.

Quit the loops if the exact sum found.

Body:
I wrote a C program to solve the stamp and postage problem using brute force. However, it looks really stupid... Is there any better algorithms there to find the fewest number of stamps needed to pay certain postage?

const int denominations[] = {1, 5, 17, 23, 37, 50};
int stamps[] = {0, 0, 0, 0, 0, 0};

void ALG2(int p) { //p means postage
    int least = p;
    int i[] = {0, 0, 0, 0, 0, 0};

    for (i[0] = 0; i[0] <= p / denominations[0]; i[0]++) {
        for (i[1] = 0; i[1] <= p / denominations[1]; i[1]++) {
            for (i[2] = 0; i[2] <= p / denominations[2]; i[2]++) {
                for (i[3] = 0; i[3] <= p / denominations[3]; i[3]++) {
                    for (i[4] = 0; i[4] <= p / denominations[4]; i[4]++) {
                        for (i[5] = 0; i[5] <= p / denominations[5]; i[5]++) {
                            if (getSum(i) == p) {
                                if (getCount(i) < least) {
                                    least = getCount(i);
                                    for (int j = 0; j < 6; j++)
                                        stamps[j] = i[j];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}