问:
Flutter - Implementing unread messages in a chat app?
I am building a simple chat app using Flutter and Firestore. I have the app working but I am having difficulty implementing the unread message counter to feed the Navbar. I am using Badges to place a number alongside the Messages icon, but I am not sure of the best way to determine the unread message count from the Chats collection in Firestore.

I know how to determine the unread count from my chat collection, but I am not sure of the most effective way to get the data. I tried to create a Stream but run into challenges implementing that approach.
Here is the code that I used to create the Stream. I am getting the data, but I am having a challenge parsing it so I can determine the unread count. Here is my Stream code:

```<code>FirebaseFirestore.instance.collection('chats')
    .where('users', arrayContains: currentUserReference)
    .snapshots()
    .listen((QuerySnapshot querySnapshot){
      querySnapshot.docs.forEach((document) {
        print(document.data());
      });
  }
);
</code>```

flutter: {user_a: DocumentReference<Map<String, dynamic>>(users/1a305sQhd2MmQsIVsposE0AHto52), last_message_time: Timestamp(seconds=1644323419, nanoseconds=16000000), user_b: DocumentReference<Map<String, dynamic>>(users/277amBvOk4cfydxdEkZvs4Od31C2), last_message_sent_by: DocumentReference<Map<String, dynamic>>(users/1a305sQhd2MmQsIVsposE0AHto52), last_message_seen_by: [DocumentReference<Map<String, dynamic>>(users/277amBvOk4cfydxdEkZvs4Od31C2)], users: [DocumentReference<Map<String, dynamic>>(users/1a305sQhd2MmQsIVsposE0AHto52), DocumentReference<Map<String, dynamic>>(users/277amBvOk4cfydxdEkZvs4Od31C2)], last_message: are you there?}

I am not sure if my Stream approach is correct, and I don't know how to parse the above result so I can determine the unread count. I will determine the unread count by checking the number of instances of where the currentUser id is contained in the 'last_message_seen_by' field.

I would appreciate any guidance on how to approach this task.

答:
That depends,
First of all the question is, the badge number represents the number of unread conversations or unread total number of messages in the conversations (all of them combined)?

If it represents the number of unread conversations, one approach can be, for the metadata of each conversation you can set a variable(bool) to check if the conversation is unread or not...and as much i presume you're using a listview to display those conversations which has a build method which returns each element of list after creating it...you can check for the variable's value there and increment or decrement the counter respectively.

And if the badge represents the number of unread messages of all the conversations combined...I've a similar approach in mind like previous one, in the metadata of the each conversations have an integer to store the number of unread messages and while building the conversations in the listview add them all up.

I'm novice so my approach, I'm not sure will be the optimal one or not but i think it should work (obviously nothing comes for free, even mine might have future complications).

Body:
I am building a simple chat app using Flutter and Firestore. I have the app working but I am having difficulty implementing the unread message counter to feed the Navbar. I am using Badges to place a number alongside the Messages icon, but I am not sure of the best way to determine the unread message count from the Chats collection in Firestore.

I know how to determine the unread count from my chat collection, but I am not sure of the most effective way to get the data. I tried to create a Stream but run into challenges implementing that approach.
Here is the code that I used to create the Stream. I am getting the data, but I am having a challenge parsing it so I can determine the unread count. Here is my Stream code:

FirebaseFirestore.instance.collection('chats')
    .where('users', arrayContains: currentUserReference)
    .snapshots()
    .listen((QuerySnapshot querySnapshot){
      querySnapshot.docs.forEach((document) {
        print(document.data());
      });
  }
);

flutter: {user_a: DocumentReference<Map<String, dynamic>>(users/1a305sQhd2MmQsIVsposE0AHto52), last_message_time: Timestamp(seconds=1644323419, nanoseconds=16000000), user_b: DocumentReference<Map<String, dynamic>>(users/277amBvOk4cfydxdEkZvs4Od31C2), last_message_sent_by: DocumentReference<Map<String, dynamic>>(users/1a305sQhd2MmQsIVsposE0AHto52), last_message_seen_by: [DocumentReference<Map<String, dynamic>>(users/277amBvOk4cfydxdEkZvs4Od31C2)], users: [DocumentReference<Map<String, dynamic>>(users/1a305sQhd2MmQsIVsposE0AHto52), DocumentReference<Map<String, dynamic>>(users/277amBvOk4cfydxdEkZvs4Od31C2)], last_message: are you there?}

I am not sure if my Stream approach is correct, and I don't know how to parse the above result so I can determine the unread count. I will determine the unread count by checking the number of instances of where the currentUser id is contained in the 'last_message_seen_by' field.

I would appreciate any guidance on how to approach this task.


来源: stackexchange

问:
Can I make dataframe that summarises/aggregates data from a much larger one?
I've got a horrendously large dataframe (covering hundreds of days worth of data) that contains data of the following pattern:

```<code>df = data.frame(date = c('2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09'),
                category = c(UKS, USD, UKS, UKS, USD, USD, UKS, USD, UKZ, UKY),
                time = c(07:59:53, 08:00:03, 08:00:03, 08:00:03, 08:00:03, 08:00:04, 08:00:08, 08:00:11, 08:00:14, 08:00:15)
                quantity = c(0.001, 0.003, 0.018, 0.010, 0.043, 0.005, 0.023, 0.005, 0.001, 0.008)
                cumvol = c(0.001, 0.004, 0.022, 0.032, 0.075, 0.080, 0.103, 0.108, 0.109, 0.117)
                type = c(TSV, OSN, TSS, TSV, TSS, TSS, OSN, TSV, OSN, TSS)
</code>```

This dataframe cannot be changed, however what I would like to do is create a 'summary' dataframe from this one that sums together the total quantity for each category and type per day, as well as providing a total quantity on that day.

So using the above example:

```<code>For 2021-01-09
Total Quantity = 0.117
Total UKS = 0.052
Total USD = 0.056
Total UKZ = 0.001
Total UKY = 0.008
</code>```

Does anyone have any advice on how to achieve this for all the days I have data for?

ContentLicense: CC BY-SA 4.0

Body:
I've got a horrendously large dataframe (covering hundreds of days worth of data) that contains data of the following pattern:

df = data.frame(date = c('2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09'),
                category = c(UKS, USD, UKS, UKS, USD, USD, UKS, USD, UKZ, UKY),
                time = c(07:59:53, 08:00:03, 08:00:03, 08:00:03, 08:00:03, 08:00:04, 08:00:08, 08:00:11, 08:00:14, 08:00:15)
                quantity = c(0.001, 0.003, 0.018, 0.010, 0.043, 0.005, 0.023, 0.005, 0.001, 0.008)
                cumvol = c(0.001, 0.004, 0.022, 0.032, 0.075, 0.080, 0.103, 0.108, 0.109, 0.117)
                type = c(TSV, OSN, TSS, TSV, TSS, TSS, OSN, TSV, OSN, TSS)

This dataframe cannot be changed, however what I would like to do is create a 'summary' dataframe from this one that sums together the total quantity for each category and type per day, as well as providing a total quantity on that day.

So using the above example:

For 2021-01-09
Total Quantity = 0.117
Total UKS = 0.052
Total USD = 0.056
Total UKZ = 0.001
Total UKY = 0.008

Does anyone have any advice on how to achieve this for all the days I have data for?

Body:
Here's one way you could do it using sqldf.  I think the sql language is pretty easy to understand for beginners and gives you another generalized tool to utilize.  Here the UNION is key to join the 'total' answer and the 'category' answer.  BTW, I slightly modified your data.frame to work.

df = data.frame(date = c('2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09'),
                category = c('UKS', 'USD', 'UKS', 'UKS', 'USD', 'USD', 'UKS', 'USD', 'UKZ', 'UKY'),
                time = c('07:59:53', '08:00:03', '08:00:03', '08:00:03', '08:00:03', '08:00:04', '08:00:08', '08:00:11', '08:00:14', '08:00:15'),
                quantity = c(0.001, 0.003, 0.018, 0.010, 0.043, 0.005, 0.023, 0.005, 0.001, 0.008),
                cumvol = c(0.001, 0.004, 0.022, 0.032, 0.075, 0.080, 0.103, 0.108, 0.109, 0.117),
                type = c('TSV', 'OSN', 'TSS', 'TSV', 'TSS', 'TSS', 'OSN', 'TSV', 'OSN', 'TSS'))

library('sqldf')

sqldf("select Date, 'ALL' as [Category],
             sum(quantity) as [Quantity]
      from df
      group by Date
      UNION
      select Date, Category,
             sum(quantity) as [Quantity]
      from df
      group by Date, category
      order by sum(Quantity) desc")

OUTPUT:

        date Category Quantity
1 2021-01-09      ALL    0.117
2 2021-01-09      USD    0.056
3 2021-01-09      UKS    0.052
4 2021-01-09      UKY    0.008
5 2021-01-09      UKZ    0.001


问:
read file in php and insert into ec2 amazon server mysql database
actually im having list of medicine in a file and i want to insert it on ec2 amazon server database which is mysql.I run this file on localhost.when im trying my code, which is in php it show an error as follows:im not getting.

Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on 'ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com' (10060) in C:\websites\medicine\filehandling.php on line 17
Can't connect to MySQL
This is a servername:ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com
here is my code... and let me know where im wrong.

```<code><?php

$hostname='http://ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com';
//$port='3306';
$user='root';//// specify username
$pass='bitnami'; //// specify password
$dbase='fortis'; //// specify database name
set_time_limit(1000);
$connection = mysql_connect("$hostname" , "$user" , "$pass" ,"$port")
or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database.");
$file = fopen("med4","r") or exit ("File not found");
$c =0 ;
      while (!feof($file)){
            ++$c;
        $val = fgets($file);
        mysql_query("insert into patientinfo_medicines (medicine) values ('$val')");
      }
fclose($file);
echo $c;
?>
</code>```

答:
I'm getting

```<code>ERROR 2005 (HY000): Unknown MySQL server host 'http://ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com/' (1)
</code>```

What about to try change your "hosname" to IP adress? Would it help ?

When I'm trying to ping it, it's unreachable

ContentLicense: CC BY-SA 3.0

Body:
actually im having list of medicine in a file and i want to insert it on ec2 amazon server database which is mysql.I run this file on localhost.when im trying my code, which is in php it show an error as follows:im not getting.

Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on 'ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com' (10060) in C:\websites\medicine\filehandling.php on line 17
Can't connect to MySQL
This is a servername:ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com
here is my code... and let me know where im wrong.

<?php

$hostname='http://ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com';
//$port='3306';
$user='root';//// specify username
$pass='bitnami'; //// specify password
$dbase='fortis'; //// specify database name
set_time_limit(1000);
$connection = mysql_connect("$hostname" , "$user" , "$pass" ,"$port")
or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database.");
$file = fopen("med4","r") or exit ("File not found");
$c =0 ;
      while (!feof($file)){
            ++$c;
        $val = fgets($file);
        mysql_query("insert into patientinfo_medicines (medicine) values ('$val')");
      }
fclose($file);
echo $c;
?>

Body:
I'm getting

ERROR 2005 (HY000): Unknown MySQL server host 'http://ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com/' (1)

What about to try change your "hosname" to IP adress? Would it help ?

When I'm trying to ping it, it's unreachable


问:
How to convert from float to std::wstring
I want to know the proper way to convert from "Float" to "std::wstring".

Xaml file

```<code><Page
    x:Class="TD2_WinUI3.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TD2_WinUI3"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">

        <Slider AutomationProperties.Name="Slider with ticks" Header="headerString" Width="300" TickFrequency="10" TickPlacement="Outside" ValueChanged="slider_ValueChanged" />
        <TextBlock x:Name="textBlock1" Margin="0,0,0,10" Text="Current value: 0" />

    </StackPanel>

</Page>
</code>```

Cpp File

```<code>void MainPage::slider_ValueChanged(Windows::Foundation::IInspectable const&, Microsoft::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs const& args)
{
    std::wstring msg = static_cast<float>(L"Current value: {0:s}", args.NewValue());
    textBlock1().Text(msg);

}
</code>```

That's my piece of code throwing me that error:

```<code>E0415   no suitable constructor exists to convert from "float" to "std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t>>"
</code>```

答:
```<code>#include <sstream>
std::wstringstream wss;
wss << 1.4f;
auto result = wss.str(); // what you want
</code>```

Body:
I want to know the proper way to convert from "Float" to "std::wstring".

Xaml file

<Page
    x:Class="TD2_WinUI3.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TD2_WinUI3"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">

        <Slider AutomationProperties.Name="Slider with ticks" Header="headerString" Width="300" TickFrequency="10" TickPlacement="Outside" ValueChanged="slider_ValueChanged" />
        <TextBlock x:Name="textBlock1" Margin="0,0,0,10" Text="Current value: 0" />

    </StackPanel>

</Page>

Cpp File

void MainPage::slider_ValueChanged(Windows::Foundation::IInspectable const&, Microsoft::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs const& args)
{
    std::wstring msg = static_cast<float>(L"Current value: {0:s}", args.NewValue());
    textBlock1().Text(msg);

}

That's my piece of code throwing me that error:

E0415   no suitable constructor exists to convert from "float" to "std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t>>"


问:
Classpath resource not found when running as jar
Having this problem both in Spring Boot 1.1.5 and 1.1.6 - I'm loading a classpath resource using an @Value annotation, which works just fine when I run the application from within STS (3.6.0, Windows). However, when I run a mvn package and then try to run the jar, I get FileNotFound exceptions.

The resource, message.txt, is in src/main/resources. I've inspected the jar and verified that it contains the file "message.txt" at the top level (same level as application.properties).

Here's the application:

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application implements CommandLineRunner {

    private static final Logger logger = Logger.getLogger(Application.class);

    @Value("${message.file}")
    private Resource messageResource;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... arg0) throws Exception {
        // both of these work when running as Spring boot app from STS, but
        // fail after mvn package, and then running as java -jar
        testResource(new ClassPathResource("message.txt"));
        testResource(this.messageResource);
    }

    private void testResource(Resource resource) {
        try {
            resource.getFile();
            logger.debug("Found the resource " + resource.getFilename());
        } catch (IOException ex) {
            logger.error(ex.toString());
        }
    }
}
```

<p>The exception:</p>

```c:\Users\glyoder\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-proble
m\target>java -jar demo-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.1.5.RELEASE)

2014-09-16 08:46:34.635  INFO 5976 --- [           main] demo.Application
                  : Starting Application on 8W59XV1 with PID 5976 (C:\Users\glyo
der\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-problem\target\demo
-0.0.1-SNAPSHOT.jar started by glyoder in c:\Users\glyoder\Documents\workspace-s
ts-3.5.1.RELEASE\classpath-resource-problem\target)
2014-09-16 08:46:34.640 DEBUG 5976 --- [           main] demo.Application
                  : Running with Spring Boot v1.1.5.RELEASE, Spring v4.0.6.RELEA
SE
2014-09-16 08:46:34.681  INFO 5976 --- [           main] s.c.a.AnnotationConfigA
pplicationContext : Refreshing org.springframework.context.annotation.Annotation
ConfigApplicationContext@1c77b086: startup date [Tue Sep 16 08:46:34 EDT 2014];
root of context hierarchy
2014-09-16 08:46:35.196  INFO 5976 --- [           main] o.s.j.e.a.AnnotationMBe
anExporter        : Registering beans for JMX exposure on startup
2014-09-16 08:46:35.210 ERROR 5976 --- [           main] demo.Application
                  : java.io.FileNotFoundException: class path resource [message.
txt] cannot be resolved to absolute file path because it does not reside in the
file system: jar:file:/C:/Users/glyoder/Documents/workspace-sts-3.5.1.RELEASE/cl
asspath-resource-problem/target/demo-0.0.1-SNAPSHOT.jar!/message.txt
2014-09-16 08:46:35.211 ERROR 5976 --- [           main] demo.Application
                  : java.io.FileNotFoundException: class path resource [message.
txt] cannot be resolved to absolute file path because it does not reside in the
file system: jar:file:/C:/Users/glyoder/Documents/workspace-sts-3.5.1.RELEASE/cl
asspath-resource-problem/target/demo-0.0.1-SNAPSHOT.jar!/message.txt
2014-09-16 08:46:35.215  INFO 5976 --- [           main] demo.Application
                  : Started Application in 0.965 seconds (JVM running for 1.435)

2014-09-16 08:46:35.217  INFO 5976 --- [       Thread-2] s.c.a.AnnotationConfigA
pplicationContext : Closing org.springframework.context.annotation.AnnotationCon
figApplicationContext@1c77b086: startup date [Tue Sep 16 08:46:34 EDT 2014]; roo
t of context hierarchy
2014-09-16 08:46:35.218  INFO 5976 --- [       Thread-2] o.s.j.e.a.AnnotationMBe
anExporter        : Unregistering JMX-exposed beans on shutdown
```

答:
I had faced same issue while running with "java -jar <file_name.jar". When i run it in STS it was working fine.
The below line helped me to resolve the issue
String templateFilePath = "/templates/Itemized_Report_2021_V1.xlsx";
InputStream resourceFile = **getClass().getResourceAsStream(templateFilePath)

excel report file template path ./templates/Itemized_Report_2021_V1.xlsx
java.io.FileNotFoundException: D:\STS%20WORKSPACE\app\target\classes\templates\Itemized_Report_2021_V1.xlsx (The system cannot find the path specified)

Solution:
@Override
public void exportExcelReport(HttpServletResponse response, List contexts)
throws IOException, URISyntaxException {
String templateFilePath = "/templates/Itemized_Report_2021_V1.xlsx";
InputStream resourceFile = getClass().getResourceAsStream(templateFilePath);
if (resourceFile == null) {
throw new IllegalArgumentException("Template file not found!. " + templateFilePath);
} else {
ServletOutputStream outputStream = null;
try {
log.info("Combined report with Competency excel report file template path {}", templateFilePath);
this.workbook = new XSSFWorkbook(resourceFile);
prepareCompetencyReport(contexts);
prepareItemizedReport(contexts);

```<code>            // Return as octet-stream format in the rest response
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            workbook.close();
            if (outputStream != null)
                outputStream.close();
        }
    }
}
</code>```

Body:
Having this problem both in Spring Boot 1.1.5 and 1.1.6 - I'm loading a classpath resource using an @Value annotation, which works just fine when I run the application from within STS (3.6.0, Windows). However, when I run a mvn package and then try to run the jar, I get FileNotFound exceptions.

The resource, message.txt, is in src/main/resources. I've inspected the jar and verified that it contains the file "message.txt" at the top level (same level as application.properties).

Here's the application:

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application implements CommandLineRunner {

    private static final Logger logger = Logger.getLogger(Application.class);

    @Value("${message.file}")
    private Resource messageResource;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... arg0) throws Exception {
        // both of these work when running as Spring boot app from STS, but
        // fail after mvn package, and then running as java -jar
        testResource(new ClassPathResource("message.txt"));
        testResource(this.messageResource);
    }

    private void testResource(Resource resource) {
        try {
            resource.getFile();
            logger.debug("Found the resource " + resource.getFilename());
        } catch (IOException ex) {
            logger.error(ex.toString());
        }
    }
}

The exception:

c:\Users\glyoder\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-proble
m\target>java -jar demo-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.1.5.RELEASE)

2014-09-16 08:46:34.635  INFO 5976 --- [           main] demo.Application
                  : Starting Application on 8W59XV1 with PID 5976 (C:\Users\glyo
der\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-problem\target\demo
-0.0.1-SNAPSHOT.jar started by glyoder in c:\Users\glyoder\Documents\workspace-s
ts-3.5.1.RELEASE\classpath-resource-problem\target)
2014-09-16 08:46:34.640 DEBUG 5976 --- [           main] demo.Application
                  : Running with Spring Boot v1.1.5.RELEASE, Spring v4.0.6.RELEA
SE
2014-09-16 08:46:34.681  INFO 5976 --- [           main] s.c.a.AnnotationConfigA
pplicationContext : Refreshing org.springframework.context.annotation.Annotation
ConfigApplicationContext@1c77b086: startup date [Tue Sep 16 08:46:34 EDT 2014];
root of context hierarchy
2014-09-16 08:46:35.196  INFO 5976 --- [           main] o.s.j.e.a.AnnotationMBe
anExporter        : Registering beans for JMX exposure on startup
2014-09-16 08:46:35.210 ERROR 5976 --- [           main] demo.Application
                  : java.io.FileNotFoundException: class path resource [message.
txt] cannot be resolved to absolute file path because it does not reside in the
file system: jar:file:/C:/Users/glyoder/Documents/workspace-sts-3.5.1.RELEASE/cl
asspath-resource-problem/target/demo-0.0.1-SNAPSHOT.jar!/message.txt
2014-09-16 08:46:35.211 ERROR 5976 --- [           main] demo.Application
                  : java.io.FileNotFoundException: class path resource [message.
txt] cannot be resolved to absolute file path because it does not reside in the
file system: jar:file:/C:/Users/glyoder/Documents/workspace-sts-3.5.1.RELEASE/cl
asspath-resource-problem/target/demo-0.0.1-SNAPSHOT.jar!/message.txt
2014-09-16 08:46:35.215  INFO 5976 --- [           main] demo.Application
                  : Started Application in 0.965 seconds (JVM running for 1.435)

2014-09-16 08:46:35.217  INFO 5976 --- [       Thread-2] s.c.a.AnnotationConfigA
pplicationContext : Closing org.springframework.context.annotation.AnnotationCon
figApplicationContext@1c77b086: startup date [Tue Sep 16 08:46:34 EDT 2014]; roo
t of context hierarchy
2014-09-16 08:46:35.218  INFO 5976 --- [       Thread-2] o.s.j.e.a.AnnotationMBe
anExporter        : Unregistering JMX-exposed beans on shutdown

Body:
I had faced same issue while running with "java -jar <file_name.jar". When i run it in STS it was working fine.
The below line helped me to resolve the issue
String templateFilePath = "/templates/Itemized_Report_2021_V1.xlsx";
InputStream resourceFile = **getClass().getResourceAsStream(templateFilePath)

excel report file template path ./templates/Itemized_Report_2021_V1.xlsx
java.io.FileNotFoundException: D:\STS%20WORKSPACE\app\target\classes\templates\Itemized_Report_2021_V1.xlsx (The system cannot find the path specified)

Solution:
@Override
public void exportExcelReport(HttpServletResponse response, List contexts)
throws IOException, URISyntaxException {
String templateFilePath = "/templates/Itemized_Report_2021_V1.xlsx";
InputStream resourceFile = getClass().getResourceAsStream(templateFilePath);
if (resourceFile == null) {
throw new IllegalArgumentException("Template file not found!. " + templateFilePath);
} else {
ServletOutputStream outputStream = null;
try {
log.info("Combined report with Competency excel report file template path {}", templateFilePath);
this.workbook = new XSSFWorkbook(resourceFile);
prepareCompetencyReport(contexts);
prepareItemizedReport(contexts);

            // Return as octet-stream format in the rest response
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            workbook.close();
            if (outputStream != null)
                outputStream.close();
        }
    }
}


问:
Printing multiple specific keys from a nested dictionary in Python
Ok, this is just a portion of a large program.

```<code>In [1]: event = {
   ...:     "Records": [
   ...:         {
   ...:             "EventSource": "aws:sns",
   ...:             "EventVersion": "1.0",
   ...:             "EventSubscriptionArn": "arn:aws:sns:eu-XXX-1:XXXXX:aws_XXX",
   ...:             "Sns": {
   ...:                 "Type": "Notification",
   ...:                 "MessageId": "95XXXXX-eXXX-5XXX-9XXX-4cXXXXXXX",
   ...:                 "TopicArn": "arn:aws:sns:us-XXX-1:XXXXXXX:EXXXXXTXXX",
   ...:                 "Subject": "example subject",
   ...:                 "Message": "example message",
   ...:                 "Timestamp": "1970-01-01T00:00:00.000Z",
   ...:                 "SignatureVersion": "1",
   ...:                 "Signature": "EXAMPLE",
   ...:                 "SigningCertUrl": "EXAMPLE",
   ...:                 "UnsubscribeUrl": "EXAMPLE",
   ...:                 "MessageAttributes": {
   ...:                     "Test": {"Type": "String", "Value": "TestString"},
   ...:                     "TestBinary": {"Type": "Binary", "Value": "TestBinary"},
   ...:                 },
   ...:             },
   ...:         }
   ...:     ]
   ...: }
</code>```

I am able to print single key value inside the nested dictionary Sns like this:

```<code>In [29]: event["Records"][0]["Sns"]["Subject"]
Out[29]: 'example subject'
</code>```

But how to print multiple key values of it?.

The following way fails.

```<code>In [38]: event["Records"][0]["Sns"](["Timestamp"], ["Subject"], ["Message"])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [38], in <module>
----> 1 event["Records"][0]["Sns"](["Timestamp"], ["Subject"], ["Message"])

TypeError: 'dict' object is not callable
</code>```

答:
You get your values in a list:

```<code>print([event["Records"][0]["Sns"][k] for k in ["Timestamp", "Subject", "Message"]])
</code>```

In a dict:

```<code>print({k:event["Records"][0]["Sns"][k] for k in ["Timestamp", "Subject", "Message"]})
</code>```

You can also unpack them like:

```<code>a, b, c = [event["Records"][0]["Sns"][k] for k in ["Timestamp", "Subject", "Message"]]
</code>```

Body:
Ok, this is just a portion of a large program.

In [1]: event = {
   ...:     "Records": [
   ...:         {
   ...:             "EventSource": "aws:sns",
   ...:             "EventVersion": "1.0",
   ...:             "EventSubscriptionArn": "arn:aws:sns:eu-XXX-1:XXXXX:aws_XXX",
   ...:             "Sns": {
   ...:                 "Type": "Notification",
   ...:                 "MessageId": "95XXXXX-eXXX-5XXX-9XXX-4cXXXXXXX",
   ...:                 "TopicArn": "arn:aws:sns:us-XXX-1:XXXXXXX:EXXXXXTXXX",
   ...:                 "Subject": "example subject",
   ...:                 "Message": "example message",
   ...:                 "Timestamp": "1970-01-01T00:00:00.000Z",
   ...:                 "SignatureVersion": "1",
   ...:                 "Signature": "EXAMPLE",
   ...:                 "SigningCertUrl": "EXAMPLE",
   ...:                 "UnsubscribeUrl": "EXAMPLE",
   ...:                 "MessageAttributes": {
   ...:                     "Test": {"Type": "String", "Value": "TestString"},
   ...:                     "TestBinary": {"Type": "Binary", "Value": "TestBinary"},
   ...:                 },
   ...:             },
   ...:         }
   ...:     ]
   ...: }

I am able to print single key value inside the nested dictionary Sns like this:

In [29]: event["Records"][0]["Sns"]["Subject"]
Out[29]: 'example subject'

But how to print multiple key values of it?.

The following way fails.

In [38]: event["Records"][0]["Sns"](["Timestamp"], ["Subject"], ["Message"])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [38], in <module>
----> 1 event["Records"][0]["Sns"](["Timestamp"], ["Subject"], ["Message"])

TypeError: 'dict' object is not callable

Body:
You get your values in a list:

print([event["Records"][0]["Sns"][k] for k in ["Timestamp", "Subject", "Message"]])

In a dict:

print({k:event["Records"][0]["Sns"][k] for k in ["Timestamp", "Subject", "Message"]})

You can also unpack them like:

a, b, c = [event["Records"][0]["Sns"][k] for k in ["Timestamp", "Subject", "Message"]]


问:
Terraform code for GCP private cluster not working
I have the terraform code for GCP private cluster and it was working one month back, but today I am trying it and it's giving error now.

```<code>Error: googleapi: Error 400: Alias IP addresses are required for private cluster, please make sure you enable alias IPs when creating a cluster., badRequest

  on modules/gke-cluster/main.tf line 20, in resource "google_container_cluster" "cluster":
  20: resource "google_container_cluster" "cluster" {
</code>```

Am I missing somthing. Help will be appreciated

答:
To enable IP aliasing, you need to use the ip_allocation_policy property

The block can be left empty as all arguments inside are optional.

Body:
I have the terraform code for GCP private cluster and it was working one month back, but today I am trying it and it's giving error now.

Error: googleapi: Error 400: Alias IP addresses are required for private cluster, please make sure you enable alias IPs when creating a cluster., badRequest

  on modules/gke-cluster/main.tf line 20, in resource "google_container_cluster" "cluster":
  20: resource "google_container_cluster" "cluster" {

Am I missing somthing. Help will be appreciated


问:
how to use a django variable in an  tag's href?
I want to create a list of entries in which each entry is linked to its page like this: wiki/entry-title. I'm using a for loop to add
s to HTML. here's the code:

```<code><ul>
  {% for entry in entries %}
    <li><a href="">{{ entry }}</a></li>
  {% endfor %}
</ul>
</code>```

urlpattern:

```<code>path('wiki/<str:title>', views.entry, name='entry')
</code>```

what should I type in href to link the
 to wiki/entry?

答:
There is a clear example in the django docs</p>
```<code><ul>
  {% for yearvar in year_list %}
    <li><a href="{% url 'news-year-archive' yearvar %}">{{ yearvar }} Archive</a></li>
  {% endfor %}
</ul>
</code>```

Title: how to use a django variable in an <a> tag's href?

Body:
I want to create a list of entries in which each entry is linked to its page like this: wiki/entry-title. I'm using a for loop to add
s to HTML. here's the code:

  {% for entry in entries %}

{{ entry }}

  {% endfor %}

urlpattern:

path('wiki/<str:title>', views.entry, name='entry')

what should I type in href to link the
 to wiki/entry?

Body:
There is a clear example in the django docs

<ul>
  {% for yearvar in year_list %}
    <li><a href="{% url 'news-year-archive' yearvar %}">{{ yearvar }} Archive</a></li>
  {% endfor %}
</ul>


问:
Update state when input value doesn't match the pattern
I want to update the state "errorFlag" when the user entered values that doesn't match the pattern, how can this be done to validate the input value?

```<code>         const [errorFlag, setErrorFlag] = useState(false);
         <Input
              name='E-Mail-Address'
              type='email'
              pattern="^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]$"
              errorMessage="* Invalid E-Mail-Address"
              onChange={setEmail1}
              error={email1 === ''}
              required={true}
          />
</code>```

FormInput

```<code>import React from "react";

export interface InputProps {
  ....
 onChange?: (value: string) => void;
}

export class Input extends React.Component<InputProps, {
  value: string;
}> {
  constructor(props: InputProps) {
    super(props);
    this.state = { value: '' };
  }
  private onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ value: event.target.value });
    this.props.onChange?.(event.target.value);
  }
  render() {
    return (
      <div key="form-name" className="formrow" style={{...this.props.style}}>
        <input
          type={this.props.type??"text"} placeholder={' '} id={id} className="forminput" pattern={this.props.pattern} onChange={this.onChange} required={this.props.required}
          />
        <span id="formInput-errorspan" className="errorSpan">{this.props.errorMessage}</span>
      </div>
    );
  }
}
</code>```

答:
You can use checkValidity method simply return true or false.

```<code>export default function App() {

  const [errorFlag, setErrorFlag] = useState(false);
  const [email, setEmail] = useState("");
  const onChange = (e) => {
    setErrorFlag(e.target.checkValidity());
    setEmail(e.target.value);
  };

  return (
    <div className="App">
      {errorFlag ? "Valid" : "Invalid"}
      <br />
      <Input
        name="E-Mail-Address"
        type="email"
        pattern="^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]$"
        errorMessage="* Invalid E-Mail-Address"
        onChange={onChange}
        required={true}
      />
      {email}
    </div>
  );
}
</code>```

Input

```<code>...
private onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ value: event.target.value });
    this.props.onChange(event);
 }
 ...
</code>```

Demo

Body:
I want to update the state "errorFlag" when the user entered values that doesn't match the pattern, how can this be done to validate the input value?

         const [errorFlag, setErrorFlag] = useState(false);
         <Input
              name='E-Mail-Address'
              type='email'
              pattern="^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]$"
              errorMessage="* Invalid E-Mail-Address"
              onChange={setEmail1}
              error={email1 === ''}
              required={true}
          />

FormInput

import React from "react";

export interface InputProps {
  ....
 onChange?: (value: string) => void;
}

export class Input extends React.Component<InputProps, {
  value: string;
}> {
  constructor(props: InputProps) {
    super(props);
    this.state = { value: '' };
  }
  private onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ value: event.target.value });
    this.props.onChange?.(event.target.value);
  }
  render() {
    return (

        <input
          type={this.props.type??"text"} placeholder={' '} id={id} className="forminput" pattern={this.props.pattern} onChange={this.onChange} required={this.props.required}
          />
        {this.props.errorMessage}

    );
  }
}

Body:
You can use checkValidity method simply return true or false.

export default function App() {

  const [errorFlag, setErrorFlag] = useState(false);
  const [email, setEmail] = useState("");
  const onChange = (e) => {
    setErrorFlag(e.target.checkValidity());
    setEmail(e.target.value);
  };

  return (
    <div className="App">
      {errorFlag ? "Valid" : "Invalid"}
      <br />
      <Input
        name="E-Mail-Address"
        type="email"
        pattern="^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]$"
        errorMessage="* Invalid E-Mail-Address"
        onChange={onChange}
        required={true}
      />
      {email}
    </div>
  );
}

Input

...
private onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ value: event.target.value });
    this.props.onChange(event);
 }
 ...

Demo


问:
How can I make JavaScript code more "clean"
I have made this functions

```<code>
let buttonOne = true;
    let buttonTwo = false;
    let buttonThree = false;
    let buttonFour = false;
    let buttonFive = false;

    const handleButtonOne = () => {
        buttonOne = true;
        buttonTwo = false;
        buttonThree = false;
        buttonFour = false;
        buttonFive = false;
    };

    const handleButtonTwo = () => {
        buttonTwo = true;
        buttonOne = false;
        buttonThree = false;
        buttonFour = false;
        buttonFive = false;
    };

    const handleButtonThree = () => {
        buttonTwo = false;
        buttonOne = false;
        buttonThree = true;
        buttonFour = false;
        buttonFive = false;
    };

    const handleButtonFour = () => {
        buttonTwo = false;
        buttonOne = false;
        buttonThree = false;
        buttonFour = true;
        buttonFive = false;
    };

    const handleButtonFive = () => {
        buttonTwo = false;
        buttonOne = false;
        buttonThree = false;
        buttonFour = false;
        buttonFive = true;
    };

</code>```

This functions are to change the state of the different buttons and show different content to the user when the state of button is true. This works well, however, I thinks it's not the right way to do it.

My question is. How can I do the same with less code and more elegant way? Any tips?

答:
This is a possible solution:

let buttons = {
  one: true,
  two: false,
  three: false,
  four: false,
  five: false
}
let trueButton = "one"

const handleButton = (key /* eg. "one"*/) => {
    buttons[trueButton] = false
    buttons[key] = true
    trueButton = key
};```

Body:
I have made this functions

let buttonOne = true;
    let buttonTwo = false;
    let buttonThree = false;
    let buttonFour = false;
    let buttonFive = false;

    const handleButtonOne = () => {
        buttonOne = true;
        buttonTwo = false;
        buttonThree = false;
        buttonFour = false;
        buttonFive = false;
    };

    const handleButtonTwo = () => {
        buttonTwo = true;
        buttonOne = false;
        buttonThree = false;
        buttonFour = false;
        buttonFive = false;
    };

    const handleButtonThree = () => {
        buttonTwo = false;
        buttonOne = false;
        buttonThree = true;
        buttonFour = false;
        buttonFive = false;
    };

    const handleButtonFour = () => {
        buttonTwo = false;
        buttonOne = false;
        buttonThree = false;
        buttonFour = true;
        buttonFive = false;
    };

    const handleButtonFive = () => {
        buttonTwo = false;
        buttonOne = false;
        buttonThree = false;
        buttonFour = false;
        buttonFive = true;
    };

This functions are to change the state of the different buttons and show different content to the user when the state of button is true. This works well, however, I thinks it's not the right way to do it.

My question is. How can I do the same with less code and more elegant way? Any tips?


问:
Djnago : AttributeError: module 'django.views.generic' has no attribute 'Detail'
where can I import the detail attribute from?

views.py:

```<code>from django.shortcuts import render
from django.views import generic

from . import models

class Index(generic.TemplateView):

   template_name='catalog/index.html'

   def get_context_data(self, **kwargs):
       context = super().get_context_data(**kwargs)
       context['num_books'] = models.Book.objects.all().count()
       context['num_instances'] = models.BookInstance.objects.all().count()
       context['num_instances_available'] = models.BookInstance.objects.filter(status__exact='a').count()
       context['num_authors'] = models.Author.objects.count()

       return context

class BookListView(generic.ListView):

   model = models.Book
   template_name = 'catalog/book_list.html'

class BookDetialView(generic.Detail.View):

   model= models.Book
   template_name = 'catalog/book_detail.html'
</code>```

urls.py

```<code>from django.urls import include, path, re_path
from . import views
from django.views.generic import TemplateView

app_name='catalog'
urlpatterns = [
   path(r'', views.Index.as_view(), name='index'),
   re_path(r'^$', views.Index.as_view(), name='index')
]

urlpatterns = [
   path(r'^$', views.index, name='index'),
   path(r'^books/$', views.BookListView.as_view(), name='books'),
   path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'),
]
</code>```

but the result:

class BookDetialView(generic.Detail.View):

AttributeError: module 'django.views.generic' has no attribute 'Detail'

答:
In your BookDetailView you used generic.Detail.View instead of DetailView[Djano-doc].

Change your BookDetailView as

```<code>from django.views import generic

class BookDetialView(generic.DetailView): #<---  change here

   model= models.Book
   template_name = 'catalog/book_detail.html'
</code>```

Body:
where can I import the detail attribute from?

views.py:

from django.shortcuts import render
from django.views import generic

from . import models

class Index(generic.TemplateView):

   template_name='catalog/index.html'

   def get_context_data(self, **kwargs):
       context = super().get_context_data(**kwargs)
       context['num_books'] = models.Book.objects.all().count()
       context['num_instances'] = models.BookInstance.objects.all().count()
       context['num_instances_available'] = models.BookInstance.objects.filter(status__exact='a').count()
       context['num_authors'] = models.Author.objects.count()

       return context

class BookListView(generic.ListView):

   model = models.Book
   template_name = 'catalog/book_list.html'

class BookDetialView(generic.Detail.View):

   model= models.Book
   template_name = 'catalog/book_detail.html'

urls.py

from django.urls import include, path, re_path
from . import views
from django.views.generic import TemplateView

app_name='catalog'
urlpatterns = [
   path(r'', views.Index.as_view(), name='index'),
   re_path(r'^$', views.Index.as_view(), name='index')
]

urlpatterns = [
   path(r'^$', views.index, name='index'),
   path(r'^books/$', views.BookListView.as_view(), name='books'),
   path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'),
]

but the result:

class BookDetialView(generic.Detail.View):

AttributeError: module 'django.views.generic' has no attribute 'Detail'

Body:
In your BookDetailView you used generic.Detail.View instead of DetailView[Djano-doc].

Change your BookDetailView as

from django.views import generic

class BookDetialView(generic.DetailView): #<---  change here

   model= models.Book
   template_name = 'catalog/book_detail.html'


问:
Sign Up and Sign In with 'Terms of Use' prompt - Internal Error Server
I've been debugging this internal server error using application insights it's been hours now and I believe it's time to ask for help. My custom policy is been enhanced with 'Terms of Use' consent and my goal is simply to adapt the existing sample on it to my policy scenario. Easier said than done!

The error happens after the "SelfAsserted-Input-ToU-SignIn" technical profile is called, which is, at the Sign-In with extension_termsOfUseConsentDateTime being prior to the date configured at IsTermsOfUseConsentRequiredForDateTime.

Here is a piece of the user journey:

...

          <OrchestrationStep Order="8" Type="ClaimsExchange">
            <ClaimsExchanges>
              <ClaimsExchange Id="AADUserReadWithObjectId" TechnicalProfileReferenceId="AAD-UserReadUsingObjectId" />
            </ClaimsExchanges>
          </OrchestrationStep>

          <OrchestrationStep Order="9" Type="ClaimsExchange">
            <ClaimsExchanges>
              <ClaimsExchange Id="Check-TOU-Status" TechnicalProfileReferenceId="Check-TOU-Status" />
            </ClaimsExchanges>
          </OrchestrationStep>

         <OrchestrationStep Order="10" Type="ClaimsExchange">
          <Preconditions>

            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>newUser</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
            <Precondition Type="ClaimEquals" ExecuteActionsIf="false">
              <Value>termsOfUseConsentRequired</Value>
              <Value>True</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="ShowToUConsentPageForNewUser" TechnicalProfileReferenceId="SelfAsserted-Input-ToU-SignIn" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="11" Type="ClaimsExchange">
          <Preconditions>

            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>newUser</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="RESTAuthB2CSignIn" TechnicalProfileReferenceId="REST-AuthB2CSignIn" />
          </ClaimsExchanges>
...
```
<p>Application Insights does not show anything meaningful to me. No exceptions, no missing claims, etc., and the error message from the browser inner HTML doesn't help much as well, here one can see part of it:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
--
  | <!-- Build: 1.0.2493.0 -->
  | <!-- StateVersion: 2.1.1 -->
  | <!-- DeploymentMode: Development -->
  | <!-- CorrelationId: ea9e5f4d-7e67-4253-8b1b-3f9ef32e43aa -->
  | <!-- DataCenter: SAN -->
  | <!-- Slice: 001-000 -->
  | <html lang="en-US"><head><link rel="icon" href="data:;base64,iVBORw0KGgo="><script data-container="true" nonce="uckM+NtdqgKmNou1EkScIg==">var GLOBALEX = {
  | "CorrelationId": "ea9e5f4d-7e67-4253-8b1b-3f9ef32e43aa",
  | "Timestamp": "2022-02-08 18:59:26Z",
  | "Detail": "AADB2C: An exception has occurred."
  | };
  |
  |
  | var CONTENT = {
  | "contact-none": "Your administrator hasn't provided any contact details.",
  | "contact-number-label": "Telephone",
  | "contact-email-label": "Email",
  | "error-title": "Sorry, but we're having trouble signing you in.",
  | "error-help": "We track these errors automatically, but if the problem persists feel free to contact us. In the meantime, please try again."
  | };
</code>```

What might be happening here?

All the involved policies + a full log file from application insights from the user journey can be found here.

Really appreciate your input on it. Thank you!

答:
It turns out that I was missing output claims on the Update-TOU-Status technical profile.

<OutputClaims>
   <OutputClaim ClaimTypeReferenceId="termsOfUseConsentRequired" DefaultValue="false" AlwaysUseDefaultValue="true" />
</OutputClaims>
```

Body:
I've been debugging this internal server error using application insights it's been hours now and I believe it's time to ask for help. My custom policy is been enhanced with 'Terms of Use' consent and my goal is simply to adapt the existing sample on it to my policy scenario. Easier said than done!

The error happens after the "SelfAsserted-Input-ToU-SignIn" technical profile is called, which is, at the Sign-In with extension_termsOfUseConsentDateTime being prior to the date configured at IsTermsOfUseConsentRequiredForDateTime.

Here is a piece of the user journey:

...

          <OrchestrationStep Order="8" Type="ClaimsExchange">
            <ClaimsExchanges>
              <ClaimsExchange Id="AADUserReadWithObjectId" TechnicalProfileReferenceId="AAD-UserReadUsingObjectId" />
            </ClaimsExchanges>
          </OrchestrationStep>

          <OrchestrationStep Order="9" Type="ClaimsExchange">
            <ClaimsExchanges>
              <ClaimsExchange Id="Check-TOU-Status" TechnicalProfileReferenceId="Check-TOU-Status" />
            </ClaimsExchanges>
          </OrchestrationStep>

         <OrchestrationStep Order="10" Type="ClaimsExchange">
          <Preconditions>

            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>newUser</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
            <Precondition Type="ClaimEquals" ExecuteActionsIf="false">
              <Value>termsOfUseConsentRequired</Value>
              <Value>True</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="ShowToUConsentPageForNewUser" TechnicalProfileReferenceId="SelfAsserted-Input-ToU-SignIn" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="11" Type="ClaimsExchange">
          <Preconditions>

            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>newUser</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="RESTAuthB2CSignIn" TechnicalProfileReferenceId="REST-AuthB2CSignIn" />
          </ClaimsExchanges>
...

Application Insights does not show anything meaningful to me. No exceptions, no missing claims, etc., and the error message from the browser inner HTML doesn't help much as well, here one can see part of it:

<!DOCTYPE html>
--
  |
  |
  |
  |
  |
  |
  | <link rel="icon" href="data:;base64,iVBORw0KGgo=">


答:
Give each button a name or id, and have something like this, when name === the button name, it's true, otherwise it's false.

```<code>let currentButton = 'button1';

handleButtonClick(name) {
    currentButton = name;
}
</code>```

Title: How can I make JavaScript code more "clean"

Body:
Give each button a name or id, and have something like this, when name === the button name, it's true, otherwise it's false.

let currentButton = 'button1';

handleButtonClick(name) {
    currentButton = name;
}


问:
How to get each letter of word list python
```<code>l = ['hello', 'world', 'monday']
        for i in range(n):
            word = input()
            l.append(word)
        for j in l[0]:
            print(j)
    Output : h e l l o
</code>```

I would like to do it for every word in l.

I want to keep my list intact because i would need to get len() of each word and i won't know the number of word that i could possibly get.
I don't know if i'm clear enough, if you need more informations let me know, thanks !

答:
from itertools import chain

lst = ['hello', 'world', 'monday']

# Print all letters of all words seperated by spaces
print(*chain.from_iterable(lst))

# Print all letters of all words seperated by spaces
# for each word on a new line
for word in lst:
    print(*word)
```

Body:
l = ['hello', 'world', 'monday']
        for i in range(n):
            word = input()
            l.append(word)
        for j in l[0]:
            print(j)
    Output : h e l l o

I would like to do it for every word in l.

I want to keep my list intact because i would need to get len() of each word and i won't know the number of word that i could possibly get.
I don't know if i'm clear enough, if you need more informations let me know, thanks !


问:
How to get Map object in react-leaflet on zoom change event
I am using react-leaflet for showing non-geographical map.
I also added some event for zoom changing. (onZoomEnd())

I wonder how to access map object or map component and get current zoom level. Or other maps props?

```<code>  <Map
                center={this.getCalculatedCenterFromState()}
                zoom={this.getCalculatedZoomFromState()}
                minZoom={this.getCalculatedMinZoomFromState()}
                maxZoom={2}
                onZoomEnd={this.mapService.handleZoomstart(/* map.object */)}

               >
</Map
</code>```

I need to access map object in handler method

```<code>handleZoomstart = (map) => {
        // TODO handle move event
    };
</code>```

答:
Solutions under didn't work for me. If you use react-leaflet v3 you can use this.
One note, hook useMapEvents you need call from children component "MapContainer" it's impotant!</p>
```<code>import {useMapEvents} from "react-leaflet";
import {useState} from "react";

function MyComponent() {
    const [zoomLevel, setZoomLevel] = useState(5); // initial zoom level provided for MapContainer

    const mapEvents = useMapEvents({
        zoomend: () => {
            setZoomLevel(mapEvents.getZoom());
        },
    });

    console.log(zoomLevel);

    return null
}

function MyMapComponent() {
    return (
        <MapContainer center={[50.5, 30.5]} zoom={5}>
            <MyComponent />
        </MapContainer>
    )
}
</code>```

Body:
I am using react-leaflet for showing non-geographical map.
I also added some event for zoom changing. (onZoomEnd())

I wonder how to access map object or map component and get current zoom level. Or other maps props?

  <Map
                center={this.getCalculatedCenterFromState()}
                zoom={this.getCalculatedZoomFromState()}
                minZoom={this.getCalculatedMinZoomFromState()}
                maxZoom={2}
                onZoomEnd={this.mapService.handleZoomstart(/* map.object */)}

               >
</Map

I need to access map object in handler method

handleZoomstart = (map) => {
        // TODO handle move event
    };

Body:
Solutions under didn't work for me. If you use react-leaflet v3 you can use this.
One note, hook useMapEvents you need call from children component "MapContainer" it's impotant!

import {useMapEvents} from "react-leaflet";
import {useState} from "react";

function MyComponent() {
    const [zoomLevel, setZoomLevel] = useState(5); // initial zoom level provided for MapContainer

    const mapEvents = useMapEvents({
        zoomend: () => {
            setZoomLevel(mapEvents.getZoom());
        },
    });

    console.log(zoomLevel);

    return null
}

function MyMapComponent() {
    return (
        <MapContainer center={[50.5, 30.5]} zoom={5}>
            <MyComponent />
        </MapContainer>
    )
}


问:
Overloading class name with integer variable
I am learning C++ using the books listed here. In particular, i read about overloading. So after reading i am trying out different examples to clear my concept further. One such example whose output i am unable to understand is given below:

```<code>int Name = 0;

class Name
{
    int x[2];
};
void func()
{
    std::cout << sizeof(Name) << std::endl; //My question is: Why here Name refers to the integer variable Name and not class named Name
}

int main()
{
    func();

}
</code>```

When i call func, then in the statement std::cout << sizeof(Name) << std::endl;, Name refers to the int Name and not class named Name. Why is this so? I expected that this would give me ambiguity error because there are two(different) entities with the same name. But the program works without any error and sizeof is applied to int Name instead of class named Name. I have read about function overloading in the books. But not about this kind of overloading. What is it called and what is happening here.

PS: I know that i can write std::cout<< sizeof(class Name); where sizeof will applied to the class named Name instead of variable int Name. Also, the example is for academic purposes. I know that use of global variable should be avoided. The question is not about how to solve this(say by not using same name for those two entities) but about what is happening.

答:
Since you added the language-lawyer tag:

When a class and a variable of the same name are declared in the same scope, then the variable name hides the class name whenever name lookup would find both of them, see [basic.scope.hiding]/2 of the post-C++20 standard draft. (Note that there was significant rework of the wording for name lookup in the current standard draft for C++23, but it should have the same effect.)

I think this behavior, instead of making it an error to declare both a class and a variable of the same name in the same scope, was chosen for compatibility with C. In C the names of structs are in a separate namespace from variable names, so they are never ambiguous. For example with

```<code>int Name = 0;

struct Name
{
    int x[2];
};
</code>```

in C, whenever you write just Name it refers to the variable. If you want to refer to the type you must use struct Name. C++ eliminates the requirement to use the struct prefix to refer to unambiguous structs, but with the rules as they are, name lookup for both Name and struct Name will have the same results in C and C++.

Body:
I am learning C++ using the books listed here. In particular, i read about overloading. So after reading i am trying out different examples to clear my concept further. One such example whose output i am unable to understand is given below:

int Name = 0;

class Name
{
    int x[2];
};
void func()
{
    std::cout << sizeof(Name) << std::endl; //My question is: Why here Name refers to the integer variable Name and not class named Name
}

int main()
{
    func();

}

When i call func, then in the statement std::cout << sizeof(Name) << std::endl;, Name refers to the int Name and not class named Name. Why is this so? I expected that this would give me ambiguity error because there are two(different) entities with the same name. But the program works without any error and sizeof is applied to int Name instead of class named Name. I have read about function overloading in the books. But not about this kind of overloading. What is it called and what is happening here.

PS: I know that i can write std::cout<< sizeof(class Name); where sizeof will applied to the class named Name instead of variable int Name. Also, the example is for academic purposes. I know that use of global variable should be avoided. The question is not about how to solve this(say by not using same name for those two entities) but about what is happening.

Body:
Since you added the language-lawyer tag:

When a class and a variable of the same name are declared in the same scope, then the variable name hides the class name whenever name lookup would find both of them, see [basic.scope.hiding]/2 of the post-C++20 standard draft. (Note that there was significant rework of the wording for name lookup in the current standard draft for C++23, but it should have the same effect.)

I think this behavior, instead of making it an error to declare both a class and a variable of the same name in the same scope, was chosen for compatibility with C. In C the names of structs are in a separate namespace from variable names, so they are never ambiguous. For example with

int Name = 0;

struct Name
{
    int x[2];
};

in C, whenever you write just Name it refers to the variable. If you want to refer to the type you must use struct Name. C++ eliminates the requirement to use the struct prefix to refer to unambiguous structs, but with the rules as they are, name lookup for both Name and struct Name will have the same results in C and C++.


问:
Flask: ImportError: attempted relative import with no known parent package
I really tried to solve this error with google, but could not find a solution that works. Maybe one of you has an idea.

My structure is this:

```<code>app/
 |- static/
 |    |- js/
 |    `- styles/
 |- templates/
 |- app.py
 |- auth.py
 |- db.sqlite
 |- main.py
 |- models.py
 `- requirements.txt
</code>```

app.py:

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app():

    app = Flask(__name__)

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db.init_app(app)
    return app

app = create_app()
</code>```

models.py:

```<code>from flask_login import UserMixin
from . import db

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    fname = db.Column(db.String(100))
    lname = db.Column(db.String(100))
    email = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(100))
</code>```

As an error i got this one:

```<code>File "C:\path\Flask_app\app\models.py", line 2, in <module>
    from . import db
ImportError: attempted relative import with no known parent package
</code>```

I dont know what to change.
In main.py i got a notice:

```<code>"db" is not accessed
</code>```

答:
You are missing an __init__.py to mark your project as a proper python package:

```<code>.
├── app
│   ├── app.py
│   ├── auth.py
│   ├── db.sqlite
│   ├── __init__.py
│   ├── main.py
│   ├── models.py
│   ├── static
│   │   ├── js
│   │   └── styles
│   └── templates
└── requirements.txt
</code>```

works with python -m app.app or python app/app.py from the project root. But still, you likely want a setup.py or a pyproject.toml, e.g. to actually specify that you want to distribute your static/ files (and from the looks of it a sqlite-database?) with your package.

Body:
I really tried to solve this error with google, but could not find a solution that works. Maybe one of you has an idea.

My structure is this:

app/
 |- static/
 |    |- js/
 |    `- styles/
 |- templates/
 |- app.py
 |- auth.py
 |- db.sqlite
 |- main.py
 |- models.py
 `- requirements.txt

app.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app():

    app = Flask(__name__)

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db.init_app(app)
    return app

app = create_app()

models.py:

from flask_login import UserMixin
from . import db

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    fname = db.Column(db.String(100))
    lname = db.Column(db.String(100))
    email = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(100))

As an error i got this one:

File "C:\path\Flask_app\app\models.py", line 2, in <module>
    from . import db
ImportError: attempted relative import with no known parent package

I dont know what to change.
In main.py i got a notice:

"db" is not accessed

Body:
You are missing an __init__.py to mark your project as a proper python package:

.
├── app
│   ├── app.py
│   ├── auth.py
│   ├── db.sqlite
│   ├── __init__.py
│   ├── main.py
│   ├── models.py
│   ├── static
│   │   ├── js
│   │   └── styles
│   └── templates
└── requirements.txt

works with python -m app.app or python app/app.py from the project root. But still, you likely want a setup.py or a pyproject.toml, e.g. to actually specify that you want to distribute your static/ files (and from the looks of it a sqlite-database?) with your package.


答:
You have a couple of issues here.

(1) In your views you spell your view name as BookDetialView and in your url definition you spell it BookDetailView.

(2) I believe the correct inheritance is generic.DetailView instead of generic.Detail.View

Title: Djnago : AttributeError: module 'django.views.generic' has no attribute 'Detail'


问:
Find first file in directory with Java
I have some sort of batch program that should pick up a file from a directory and process it.

Since this program is supposed to:

run on JDK 5,

be small (no external libraries)

and fast! (with a bang)

...what is the best way to only pick one file from the directory - without using File.list() (might be hundreds of files)?

答:
Use a FileFilter (or FilenameFilter) written to accept only once, for example:

```<code>File dir = new File("/some/dir");
File[] files = dir.listFiles(new FileFilter() {
    boolean first = true;
    public boolean accept(final File pathname) {
        if (first) {
            first = false;
            return true;
        }
        return false;
    }
});
</code>```

Title: Find first file in directory with Java

Body:
Use a FileFilter (or FilenameFilter) written to accept only once, for example:

File dir = new File("/some/dir");
File[] files = dir.listFiles(new FileFilter() {
    boolean first = true;
    public boolean accept(final File pathname) {
        if (first) {
            first = false;
            return true;
        }
        return false;
    }
});


问:
Can I use select_related Django QuerySet method in reverse relationships?

class A(Model):
  pass

class B(Model):
  a = ForeignKey(A)

B.objects.select_related("a")  # this works
A.objects.select_related("b")  # this doesn't
```

How do I make the second line work? Are there any ways to do the same thing in some other ways?

答:
You need to use prefetch_related since there could be multiple B instances referencing the same A instance

A.objects.prefetch_related("b_set")

https://stackoverflow.com/a/31237071/3862325

https://docs.djangoproject.com/en/4.0/ref/models/querysets/#prefetch-related

Body:
class A(Model):
  pass

class B(Model):
  a = ForeignKey(A)

B.objects.select_related("a")  # this works
A.objects.select_related("b")  # this doesn't

How do I make the second line work? Are there any ways to do the same thing in some other ways?


问:
Python 3 while loop can't show list keys?
Ok so i am trying to do some basic while loop to show text formated in this way:

A - 80%-100%

B - 60%-80%

C - 50-60%

D - less then 50%

with this code:

```<code>dictionary={'A':'80%-100%','B':'60%-80%','C':'50-60%','D':'less then 50%'}
klucze=list(dictionary.keys())
q=0
while q<4:
print(klucze[q]," - ",dictionary[q])
q+=1
</code>```

It's working with klucze[q] only, but when i try to print dictionary[q] too, i get the error

答:
Try this one. I replaced ' with " inside dict items.

```<code>dictionary={"A":"80%-100%","B":"60%-80%","C":"50-60%","D":"less then 50%"}
klucze=list(dictionary.keys())
q=0
while q<4:
    print(klucze[q]," - ",list(dictionary.values())[q])
    q+=1

</code>```

Body:
Ok so i am trying to do some basic while loop to show text formated in this way:

A - 80%-100%

B - 60%-80%

C - 50-60%

D - less then 50%

with this code:

dictionary={'A':'80%-100%','B':'60%-80%','C':'50-60%','D':'less then 50%'}
klucze=list(dictionary.keys())
q=0
while q<4:
print(klucze[q]," - ",dictionary[q])
q+=1

It's working with klucze[q] only, but when i try to print dictionary[q] too, i get the error

Body:
Try this one. I replaced ' with " inside dict items.

dictionary={"A":"80%-100%","B":"60%-80%","C":"50-60%","D":"less then 50%"}
klucze=list(dictionary.keys())
q=0
while q<4:
    print(klucze[q]," - ",list(dictionary.values())[q])
    q+=1


问:
Missing geocoding parametr
This is my dataframe view

```<code>from cartoframes.data.services import Geocoding

gc = Geocoding()

london_stations_gdf, london_stations_metadata = gc.geocode(
        df,
        street='Borough',
        city={'value': 'London'},
        country={'value': 'United Kingdom'}
    )
</code>```

ValueError: Credentials attribute is required. Please pass a Credentials instance or use the set_default_credentials function.

Error relate with Geocoding parametrs. however use gc = Geocoding(credentials=None), return me same error.

答:
Assuming you have creds (username and api_key)

If you need to create the creds.json file, run the following

```<code>from cartoframes.auth import Credentials

Credentials('my_username', 'my_api_key').save('creds.json')
</code>```

then modify your code to set your default credentials

```<code>from cartoframes.auth import set_default_credentials
from cartoframes.data.services import Geocoding

# set your default creds
set_default_credentials('path/to/your/creds.json')

gc = Geocoding()

london_stations_gdf, london_stations_metadata = gc.geocode(
        df,
        street='Borough',
        city={'value': 'London'},
        country={'value': 'United Kingdom'}
    )
</code>```

Title: Missing geocoding parametr

Body:
This is my dataframe view

from cartoframes.data.services import Geocoding

gc = Geocoding()

london_stations_gdf, london_stations_metadata = gc.geocode(
        df,
        street='Borough',
        city={'value': 'London'},
        country={'value': 'United Kingdom'}
    )

ValueError: Credentials attribute is required. Please pass a Credentials instance or use the set_default_credentials function.

Error relate with Geocoding parametrs. however use gc = Geocoding(credentials=None), return me same error.

Body:
Assuming you have creds (username and api_key)

If you need to create the creds.json file, run the following

from cartoframes.auth import Credentials

Credentials('my_username', 'my_api_key').save('creds.json')

then modify your code to set your default credentials

from cartoframes.auth import set_default_credentials
from cartoframes.data.services import Geocoding

# set your default creds
set_default_credentials('path/to/your/creds.json')

gc = Geocoding()

london_stations_gdf, london_stations_metadata = gc.geocode(
        df,
        street='Borough',
        city={'value': 'London'},
        country={'value': 'United Kingdom'}
    )


问:
Detect when a child form is closed
I have he following Form:

An Initialize Function that is called when the Form1 is created.

A button that opens another Form (Form2)

What I need is to call Initialize() not only when Form1 is created, but whenever Form2 is closed, since Form2 might have modified some stuff that makes Initialize need to be called again.

How can I detect when the form2 is closed?

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Initialize();
    }

    void Initialize()
    {
        // Read a config file and initialize some stuff
    }

    // Clicking this button will open a Form2
    private void button1_Click(object sender, EventArgs e)
    {
        var form2 = new Form2().Show();
    }
}

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
        // some stuff that Form2 does which involves modifying the config file
    }
}
</code>```

答:
You just need to add an event handler for the FormClosing event, this handler could be in your first form class and here you can call every internal method of that class</p>
```<code>private void button1_Click(object sender, EventArgs e)
{
    var form2 = new Form2();
    form2.FormClosing += childClosing;
    form2.Show();
}
private void childClosing(object sender, FormClosingEventArgs e)
{
    Initialize();
    ....
}
</code>```

Title: Detect when a child form is closed

Body:
I have he following Form:

An Initialize Function that is called when the Form1 is created.

A button that opens another Form (Form2)

What I need is to call Initialize() not only when Form1 is created, but whenever Form2 is closed, since Form2 might have modified some stuff that makes Initialize need to be called again.

How can I detect when the form2 is closed?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Initialize();
    }

    void Initialize()
    {
        // Read a config file and initialize some stuff
    }

    // Clicking this button will open a Form2
    private void button1_Click(object sender, EventArgs e)
    {
        var form2 = new Form2().Show();
    }
}

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
        // some stuff that Form2 does which involves modifying the config file
    }
}

Body:
You just need to add an event handler for the FormClosing event, this handler could be in your first form class and here you can call every internal method of that class

private void button1_Click(object sender, EventArgs e)
{
    var form2 = new Form2();
    form2.FormClosing += childClosing;
    form2.Show();
}
private void childClosing(object sender, FormClosingEventArgs e)
{
    Initialize();
    ....
}


问:
How to prevent the FolderBrowserDialog description from wrapping?
We are using a WinForms FolderBrowserDialog in a WPF/C# Application using some and we have a sentence we have added to the Description property on the FolderBrowserDialog (I'm going to change the text for the sake of the screenshot but our message is ABOUT the same length, ignore the text though it's completely different from ours).

I was wondering if there is a way to prevent this from wrapping, I'll show how the Description is set and what the dialog looks like. After upgrading to .NET 5 it also changed the look of the dialog completely.

```<code>Description = "Select the folder that contains the particular types of documents you would like to import.",
</code>```

答:
Use AutoUpgradeEnabled = false; in .NET 5 to get the WinForms FolderBrowserDialog to use the old style of dialog.

The wrapping was caused by the change in style of dialog when upgrading from .NET 4.8 to .NET 5.0.

Body:
We are using a WinForms FolderBrowserDialog in a WPF/C# Application using some and we have a sentence we have added to the Description property on the FolderBrowserDialog (I'm going to change the text for the sake of the screenshot but our message is ABOUT the same length, ignore the text though it's completely different from ours).

I was wondering if there is a way to prevent this from wrapping, I'll show how the Description is set and what the dialog looks like. After upgrading to .NET 5 it also changed the look of the dialog completely.

Description = "Select the folder that contains the particular types of documents you would like to import.",


问:
Need a simple explanation of the inject method
```<code>[1, 2, 3, 4].inject(0) { |result, element| result + element } # => 10
</code>```

I'm looking at this code but my brain is not registering how the number 10 can become the result. Would someone mind explaining what's happening here?

答:
You can think of the first block argument as an accumulator: the result of each run of the block is stored in the accumulator and then passed to the next execution of the block. In the case of the code shown above, you are defaulting the accumulator, result, to 0. Each run of the block adds the given number to the current total and then stores the result back into the accumulator. The next block call has this new value, adds to it, stores it again, and repeats.

At the end of the process, inject returns the accumulator, which in this case is the sum of all the values in the array, or 10.

Here's another simple example to create a hash from an array of objects, keyed by their string representation:

```<code>[1,"a",Object.new,:hi].inject({}) do |hash, item|
  hash[item.to_s] = item
  hash
end
</code>```

In this case, we are defaulting our accumulator to an empty hash, then populating it each time the block executes. Notice we must return the hash as the last line of the block, because the result of the block will be stored back in the accumulator.

OwnerDisplayName: hightide

ContentLicense: CC BY-SA 2.5

Body:
[1, 2, 3, 4].inject(0) { |result, element| result + element } # => 10

I'm looking at this code but my brain is not registering how the number 10 can become the result. Would someone mind explaining what's happening here?

Body:
You can think of the first block argument as an accumulator: the result of each run of the block is stored in the accumulator and then passed to the next execution of the block. In the case of the code shown above, you are defaulting the accumulator, result, to 0. Each run of the block adds the given number to the current total and then stores the result back into the accumulator. The next block call has this new value, adds to it, stores it again, and repeats.

At the end of the process, inject returns the accumulator, which in this case is the sum of all the values in the array, or 10.

Here's another simple example to create a hash from an array of objects, keyed by their string representation:

[1,"a",Object.new,:hi].inject({}) do |hash, item|
  hash[item.to_s] = item
  hash
end

In this case, we are defaulting our accumulator to an empty hash, then populating it each time the block executes. Notice we must return the hash as the last line of the block, because the result of the block will be stored back in the accumulator.

OwnerDisplayName: Drew Olson

LastEditorDisplayName: Drew Olson


问:
Restart application after closing program
I'm developed a program on C#.
in my program, when user save personal setting the program can be following rules.
1- save settings.
2- after saving close all form and program.
3- and restart program.

I'm done 1. and 2. steps

How can i done 3. steps?
thanks for patience.

答: You can use Application.Restart() method to restart your application, if you don't like to use that method, here is a custom method that I used for restarting.</p>


问:
How to remove a partition key in Postgres
I have the following table in PostgreSQL:

```<code>CREATE TABLE foo (
   bar text NOT NULL
   ...
)
PARTITION BY LIST (bar);
</code>```

How can the whole partition key be removed from the table? It is possible to remove a single partition table with DETACH PARTITION, but I can't find a way to drop the partitioning itself.

答:
You cannot drop partitioning. If you want to use an unpartitioned table instead, you have to move a lot of data. That is unavoidable, because the data are actually stored in the partitions.

You'll have to do something along the lines of

```<code>CREATE TABLE new_foo (LIKE foo);
INSERT INTO new_foo SELECT * FROM foo;
DROP TABLE foo;
ALTER TABLE new_foo RENAME TO foo;
</code>```

The details may vary: you will have to take care of constraints and indexes, you can parallelize by running several inserts concurrently (for example for different partitions), and so on.

In any event it will be a longer down time. The only way I know o avoid this is to set up logical replication for the whole database and use an unpartitioned table on the standby side. Once replication has caught up, you can switch over to the standby database.

Body:
I have the following table in PostgreSQL:

CREATE TABLE foo (
   bar text NOT NULL
   ...
)
PARTITION BY LIST (bar);

How can the whole partition key be removed from the table? It is possible to remove a single partition table with DETACH PARTITION, but I can't find a way to drop the partitioning itself.

Body:
You cannot drop partitioning. If you want to use an unpartitioned table instead, you have to move a lot of data. That is unavoidable, because the data are actually stored in the partitions.

You'll have to do something along the lines of

CREATE TABLE new_foo (LIKE foo);
INSERT INTO new_foo SELECT * FROM foo;
DROP TABLE foo;
ALTER TABLE new_foo RENAME TO foo;

The details may vary: you will have to take care of constraints and indexes, you can parallelize by running several inserts concurrently (for example for different partitions), and so on.

In any event it will be a longer down time. The only way I know o avoid this is to set up logical replication for the whole database and use an unpartitioned table on the standby side. Once replication has caught up, you can switch over to the standby database.


问:
How to check if screen saver is running?
I have a script written in bash, which I need to take different route in case screensaver is currently running. This is Linux with Xorg and KDE. Script is called from cron, and it connects to DISPLAY=:0.

Any hint/idea how to check for state of screensaver?

答:
On Gnome 40 you can use

```<code>dbus-send --session --print-reply=literal --dest=org.gnome.ScreenSaver /org/gnome/ScreenSaver org.gnome.ScreenSaver.GetActive
</code>```

It will print something like this

```<code>   boolean false
</code>```

Body:
On Gnome 40 you can use

dbus-send --session --print-reply=literal --dest=org.gnome.ScreenSaver /org/gnome/ScreenSaver org.gnome.ScreenSaver.GetActive

It will print something like this

   boolean false


问:
Printing multiple specific keys from a nested dictionary in Python
Ok, this is just a portion of a large program.

```<code>In [1]: event = {
   ...:     "Records": [
   ...:         {
   ...:             "EventSource": "aws:sns",
   ...:             "EventVersion": "1.0",
   ...:             "EventSubscriptionArn": "arn:aws:sns:eu-XXX-1:XXXXX:aws_XXX",
   ...:             "Sns": {
   ...:                 "Type": "Notification",
   ...:                 "MessageId": "95XXXXX-eXXX-5XXX-9XXX-4cXXXXXXX",
   ...:                 "TopicArn": "arn:aws:sns:us-XXX-1:XXXXXXX:EXXXXXTXXX",
   ...:                 "Subject": "example subject",
   ...:                 "Message": "example message",
   ...:                 "Timestamp": "1970-01-01T00:00:00.000Z",
   ...:                 "SignatureVersion": "1",
   ...:                 "Signature": "EXAMPLE",
   ...:                 "SigningCertUrl": "EXAMPLE",
   ...:                 "UnsubscribeUrl": "EXAMPLE",
   ...:                 "MessageAttributes": {
   ...:                     "Test": {"Type": "String", "Value": "TestString"},
   ...:                     "TestBinary": {"Type": "Binary", "Value": "TestBinary"},
   ...:                 },
   ...:             },
   ...:         }
   ...:     ]
   ...: }
</code>```

I am able to print single key value inside the nested dictionary Sns like this:

```<code>In [29]: event["Records"][0]["Sns"]["Subject"]
Out[29]: 'example subject'
</code>```

But how to print multiple key values of it?.

The following way fails.

```<code>In [38]: event["Records"][0]["Sns"](["Timestamp"], ["Subject"], ["Message"])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [38], in <module>
----> 1 event["Records"][0]["Sns"](["Timestamp"], ["Subject"], ["Message"])

TypeError: 'dict' object is not callable
</code>```

答:
On separate lines:

```<code>for x in ("Timestamp", "Subject", "Message"):
    print(event["Records"][0]["Sns"][x])
</code>```

On one line but stored as an array:

```<code>a = []
for x in ("Timestamp", "Subject", "Message"):
    a.append(event["Records"][0]["Sns"][x])
print(a)
</code>```

You could run a for loop, looping through the elements you want to print multiple imbedded elements in the dictionary.

Body:
Ok, this is just a portion of a large program.

In [1]: event = {
   ...:     "Records": [
   ...:         {
   ...:             "EventSource": "aws:sns",
   ...:             "EventVersion": "1.0",
   ...:             "EventSubscriptionArn": "arn:aws:sns:eu-XXX-1:XXXXX:aws_XXX",
   ...:             "Sns": {
   ...:                 "Type": "Notification",
   ...:                 "MessageId": "95XXXXX-eXXX-5XXX-9XXX-4cXXXXXXX",
   ...:                 "TopicArn": "arn:aws:sns:us-XXX-1:XXXXXXX:EXXXXXTXXX",
   ...:                 "Subject": "example subject",
   ...:                 "Message": "example message",
   ...:                 "Timestamp": "1970-01-01T00:00:00.000Z",
   ...:                 "SignatureVersion": "1",
   ...:                 "Signature": "EXAMPLE",
   ...:                 "SigningCertUrl": "EXAMPLE",
   ...:                 "UnsubscribeUrl": "EXAMPLE",
   ...:                 "MessageAttributes": {
   ...:                     "Test": {"Type": "String", "Value": "TestString"},
   ...:                     "TestBinary": {"Type": "Binary", "Value": "TestBinary"},
   ...:                 },
   ...:             },
   ...:         }
   ...:     ]
   ...: }

I am able to print single key value inside the nested dictionary Sns like this:

In [29]: event["Records"][0]["Sns"]["Subject"]
Out[29]: 'example subject'

But how to print multiple key values of it?.

The following way fails.

In [38]: event["Records"][0]["Sns"](["Timestamp"], ["Subject"], ["Message"])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [38], in <module>
----> 1 event["Records"][0]["Sns"](["Timestamp"], ["Subject"], ["Message"])

TypeError: 'dict' object is not callable

Body:
On separate lines:

for x in ("Timestamp", "Subject", "Message"):
    print(event["Records"][0]["Sns"][x])

On one line but stored as an array:

a = []
for x in ("Timestamp", "Subject", "Message"):
    a.append(event["Records"][0]["Sns"][x])
print(a)

You could run a for loop, looping through the elements you want to print multiple imbedded elements in the dictionary.


问:
Cocoa get current running path of SIMBL Plugin
I am working on a SIMBL Plugin that is loaded by a 3rd-party host application on macOS. It is almost entirely written in C++ and has only minimal objective-c components. (The UI is largely provided by API calls into the host app.) One of the requirements is that the plugin bundle can be loaded multiple times from different sub-directories. It is a Lua interpreter, and the goal is for each instance to host a different configuration of lua scripts that appear in separate menus on the host application. Third parties could bundle this plugin with a custom configuration for their script(s) and they would appear as separate items in the app's plugin menu.

This issue I have is this: I need to find out what directory my plugin is executing in. I could create a special class called MY_BUNDLE_ID_CLASS and use:

[NSBundle bundleForClass:[MY_BUNDLE_ID_CLASS class]];
```

Once I have the correct NSBundle, getting the file path is trivial.

The problem is that if multiple instances of my bundle are loaded (from different folders), Cocoa complains that the class MY_BUNDLE_ID_CLASS is defined in multiple locations and won't guarantee me which one was used. For other similar classes this would be fine for my plugin, because my unique class names are macros that equate to a mangled name that includes the version number, but in this case it isn't okay. It would potentially be multiple instances of the same version. Is there any other way to find out the folder my plugin code is executing from? It seems like a simple request, but I am coming up empty. I welcome suggestions.

答:
Given an address in an executable, the dladdr function can be used to query the dynamic linker about the dynamically-linked image containing that address; i.e., given a reference to a symbol in your plugin, dladdr can give you the dynamic linking information about your plugin.

The runtime lookup can look as follows:

// Sample: BundleClass.m, the principal class for the plugin

#import "BundleClass.h"
#import <dlfcn.h>

// We'll be using a reference to this variable compiled into the plugin,
// but we can just as easily use a function pointer or similar -- anything
// that will be statically compiled into the plugin.
int someVariable = 0;

@implementation BundleClass

+ (void)load {
    Dl_info info;
    if (dladdr(&someVariable, &info) != 0) {
        NSLog(@"Plugin loaded from %s", info.dli_fname);
    } else {
        // Handle lookup failure.
    }
}

@end
```
<p>Instead of <code>&someSymbol</code>, you can also use a reference to a function (e.g. <code>&someFunctionDefinedInThePlugin</code>), but you should be careful not to pass in a pointer that could be dynamically allocated — since that will likely either fail, or point you to the memory space of the host process.</p>
<p>On my machine, with a trivial macOS host app setup, the following loading code:</p>
<pre class="lang-objectivec prettyprint-override"><code>- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:@"DynamicBundle" withExtension:@"bundle"];
    if (!bundleURL) {
        NSLog(@"Failed to find bundle!");
        return;
    }

    NSLog(@"Bundle class before loading: %@", NSClassFromString(@"BundleClass"));

    NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
    NSError *error = nil;
    if (![bundle loadAndReturnError:&error]) {
        NSLog(@"Failed to load bundle: %@", error);
        return;
    }

    NSLog(@"Bundle class after loading: %@", NSClassFromString(@"BundleClass"));
}
</code>```

successfully produces

```<code>Bundle class before loading: (null)
Loaded plugin from /Volumes/ExtSSD/Developer/Xcode/DerivedData/HostApp/Build/Products/Debug/HostApp.app/Contents/Resources/DynamicBundle.bundle/Contents/MacOS/DynamicBundle
Bundle class after loading: BundleClass
</code>```

which is indeed the path to the plugin on disk.

Body:
I am working on a SIMBL Plugin that is loaded by a 3rd-party host application on macOS. It is almost entirely written in C++ and has only minimal objective-c components. (The UI is largely provided by API calls into the host app.) One of the requirements is that the plugin bundle can be loaded multiple times from different sub-directories. It is a Lua interpreter, and the goal is for each instance to host a different configuration of lua scripts that appear in separate menus on the host application. Third parties could bundle this plugin with a custom configuration for their script(s) and they would appear as separate items in the app's plugin menu.

This issue I have is this: I need to find out what directory my plugin is executing in. I could create a special class called MY_BUNDLE_ID_CLASS and use:

[NSBundle bundleForClass:[MY_BUNDLE_ID_CLASS class]];

Once I have the correct NSBundle, getting the file path is trivial.

The problem is that if multiple instances of my bundle are loaded (from different folders), Cocoa complains that the class MY_BUNDLE_ID_CLASS is defined in multiple locations and won't guarantee me which one was used. For other similar classes this would be fine for my plugin, because my unique class names are macros that equate to a mangled name that includes the version number, but in this case it isn't okay. It would potentially be multiple instances of the same version. Is there any other way to find out the folder my plugin code is executing from? It seems like a simple request, but I am coming up empty. I welcome suggestions.

Body:
Given an address in an executable, the dladdr function can be used to query the dynamic linker about the dynamically-linked image containing that address; i.e., given a reference to a symbol in your plugin, dladdr can give you the dynamic linking information about your plugin.

The runtime lookup can look as follows:

// Sample: BundleClass.m, the principal class for the plugin

#import "BundleClass.h"
#import <dlfcn.h>

// We'll be using a reference to this variable compiled into the plugin,
// but we can just as easily use a function pointer or similar -- anything
// that will be statically compiled into the plugin.
int someVariable = 0;

@implementation BundleClass

+ (void)load {
    Dl_info info;
    if (dladdr(&someVariable, &info) != 0) {
        NSLog(@"Plugin loaded from %s", info.dli_fname);
    } else {
        // Handle lookup failure.
    }
}

@end

Instead of &someSymbol, you can also use a reference to a function (e.g. &someFunctionDefinedInThePlugin), but you should be careful not to pass in a pointer that could be dynamically allocated — since that will likely either fail, or point you to the memory space of the host process.

On my machine, with a trivial macOS host app setup, the following loading code:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:@"DynamicBundle" withExtension:@"bundle"];
    if (!bundleURL) {
        NSLog(@"Failed to find bundle!");
        return;
    }

    NSLog(@"Bundle class before loading: %@", NSClassFromString(@"BundleClass"));

    NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
    NSError *error = nil;
    if (![bundle loadAndReturnError:&error]) {
        NSLog(@"Failed to load bundle: %@", error);
        return;
    }

    NSLog(@"Bundle class after loading: %@", NSClassFromString(@"BundleClass"));
}

successfully produces

Bundle class before loading: (null)
Loaded plugin from /Volumes/ExtSSD/Developer/Xcode/DerivedData/HostApp/Build/Products/Debug/HostApp.app/Contents/Resources/DynamicBundle.bundle/Contents/MacOS/DynamicBundle
Bundle class after loading: BundleClass

which is indeed the path to the plugin on disk.


问:
WITH queries with INSERT in MySQL
I'm trying to do something that I'm almost positive works in Postgresql:

```<code>WITH cte AS (SELECT something FROM something WHERE something.name='reference')
INSERT INTO somewhere (id, name)
SELECT cte.id, 'John'
UNION ALL
SELECT cte.id, 'Frank'
UNION ALL
SELECT cte.id, 'Thomas'
;
</code>```

In other words, I want to grab the "something" row to be used for a bunch of new rows in "somwhere". Each new entry should have a reference (like  foreign key value) back to the same "something" row in the cte, mostly just to avoid a mess. However, MySQL is giving me that "blank stare" syntax error mechanism. Does MySQL allow WITH ... INSERT ...;?

Here's the actual code; it's just setting up test data:

```<code>WITH
  pr AS (SELECT pr_id from property AS p WHERE p.pr_name = 'Royal Oaks Plaza'),
  u AS (SELECT pr.pr_id AS pr_id, utyp.utyp_name AS utyp_name, utyp.utyp_id AS utyp_id FROM unit_type AS utyp, pr)
    INSERT INTO unit (pr_id, unt_number, utyp_id, unt_size)
    SELECT pr_id, '100', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'BEAUTY'
    UNION ALL
    SELECT pr_id, '110', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'RESTAURANT'
;
</code>```

答:
In MySQL the INSERT goes before the CTE definition, i.e.

```<code>INSERT INTO somewhere (id, name)
WITH cte AS (SELECT id FROM something WHERE something.name='reference')
SELECT cte.id, 'John' FROM cte
UNION ALL
SELECT cte.id, 'Frank' FROM cte
UNION ALL
SELECT cte.id, 'Thomas' FROM cte;
</code>```

Example on DB Fiddle

So I think the following would work:

```<code>INSERT INTO unit (pr_id, unt_number, utyp_id, unt_size)
WITH
  pr AS (SELECT pr_id from property AS p WHERE p.pr_name = 'Royal Oaks Plaza'),
  u AS (SELECT pr.pr_id AS pr_id, utyp.utyp_name AS utyp_name, utyp.utyp_id AS utyp_id FROM unit_type AS utyp, pr)
    SELECT pr_id, '100', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'BEAUTY'
    UNION ALL
    SELECT pr_id, '110', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'RESTAURANT'
;
</code>```

Title: WITH queries with INSERT in MySQL

Body:
I'm trying to do something that I'm almost positive works in Postgresql:

WITH cte AS (SELECT something FROM something WHERE something.name='reference')
INSERT INTO somewhere (id, name)
SELECT cte.id, 'John'
UNION ALL
SELECT cte.id, 'Frank'
UNION ALL
SELECT cte.id, 'Thomas'
;

In other words, I want to grab the "something" row to be used for a bunch of new rows in "somwhere". Each new entry should have a reference (like  foreign key value) back to the same "something" row in the cte, mostly just to avoid a mess. However, MySQL is giving me that "blank stare" syntax error mechanism. Does MySQL allow WITH ... INSERT ...;?

Here's the actual code; it's just setting up test data:

WITH
  pr AS (SELECT pr_id from property AS p WHERE p.pr_name = 'Royal Oaks Plaza'),
  u AS (SELECT pr.pr_id AS pr_id, utyp.utyp_name AS utyp_name, utyp.utyp_id AS utyp_id FROM unit_type AS utyp, pr)
    INSERT INTO unit (pr_id, unt_number, utyp_id, unt_size)
    SELECT pr_id, '100', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'BEAUTY'
    UNION ALL
    SELECT pr_id, '110', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'RESTAURANT'
;

Body:
In MySQL the INSERT goes before the CTE definition, i.e.

INSERT INTO somewhere (id, name)
WITH cte AS (SELECT id FROM something WHERE something.name='reference')
SELECT cte.id, 'John' FROM cte
UNION ALL
SELECT cte.id, 'Frank' FROM cte
UNION ALL
SELECT cte.id, 'Thomas' FROM cte;

Example on DB Fiddle

So I think the following would work:

INSERT INTO unit (pr_id, unt_number, utyp_id, unt_size)
WITH
  pr AS (SELECT pr_id from property AS p WHERE p.pr_name = 'Royal Oaks Plaza'),
  u AS (SELECT pr.pr_id AS pr_id, utyp.utyp_name AS utyp_name, utyp.utyp_id AS utyp_id FROM unit_type AS utyp, pr)
    SELECT pr_id, '100', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'BEAUTY'
    UNION ALL
    SELECT pr_id, '110', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'RESTAURANT'
;


问:
Handle Authentication in NextJS
I am setting up a new web application and I wanted some advices for handling my authentication workflow.

I am fetching the user's data from a custom backend. Once the user is logged in, I got the access token and the refresh token as well.

I choose NextJs for my front-end with all the benefits it gives. My question is :

Should I handle the Authentication workflow with NextAuth or Redux ?
In the first case with NextAuth, I have never implemented the session hook.
In the redux case, I just dispatch actions and handle the authentication data in the global state of the application.

Thank you for your advices.

答:
I have been used the Next-Auth, It has many problems!
Then I created a new custom API for Google-auth with a token and a CSRF token for every ssr page that update every page loading.

If you want, I can upload it on git for free :)

Title: Handle Authentication in NextJS