问:
Showing particular row data as column
My table is as follows:

Date
Code
Price
MA5
MA20

2022-01-01
APPLE
1000
1080
1090

2022-01-02
APPLE
1100
1084
1100

2022-01-03
APPLE
1200
1090
1100

2022-01-01
MICROSOFT
7
9
10

2022-01-02
MICROSOFT
7.5
8
9.5

2022-01-03
MICROSOFT
8
8.5
9

...
...
...
...
...

2022-01-01
NASDAQ
14400
15600
16700

2022-01-02
NASDAQ
14500
15200
16100

2022-01-03
NASDAQ
14600
15000
16000

I'm currently saving NASDAQ values and stock data on the same table using MariaDB.

However, I want to show NASDAQ's MA values as new column fields into rest of the field, as NASDAQ_MA5, NASDAQ_MA20.

My question is, how do I select nasdaq's MA5 and MA20 values and put it as the values according to the matching dates? My desired output is as follows:

Date
Code
Price
MA5
MA20
NASDAQ_MA5
NASDAQ_MA20

2022-01-01
APPLE
1000
1080
1090
15600
16700

2022-01-02
APPLE
1100
1084
1100
15200
16100

2022-01-03
APPLE
1200
1090
1100
15000
16000

2022-01-01
MICROSOFT
7
9
10
15600
16700

2022-01-02
MICROSOFT
7.5
8
9.5
15200
16100

2022-01-03
MICROSOFT
8
8.5
9
15000
16000

I've been trying the following:

```<code>        SELECT *,
        (PARTITION BY DATE, case when (code='NASDAQ') then MA5 else NULL end) as 'NASDAQ_MA5',
        (PARTITION BY DATE, case when (code='NASDAQ') then MA20 else NULL end) as 'NASDAQ_MA20'
        FROM TABLE
</code>```

Your help will be very appreciated.

答:
You need to join the two distinct sets of data. It probably makes sense to define a CTE to keep the definitions clear, then join with your main table - either an inner join if there's always a corresponding date or left join if there might not be.

This assumes there's only a single nasdaq code for each date, if that's not the case you can aggregate in the CTE as required.

```<code>with nasdaq as (
    select date, MA5 NASDAQ_MA5, MA20 NASDAQ_MA20
    from t
    where code = 'NASDAQ'
)
select t.*, n.NASDAQ_MA5, n.NASDAQ_MA20
from t
left join nasdaq n on n.date=t.date
where t.code != 'NASDAQ';
</code>```

Title: Showing particular row data as column

Body:
My table is as follows:

Date
Code
Price
MA5
MA20

2022-01-01
APPLE
1000
1080
1090

2022-01-02
APPLE
1100
1084
1100

2022-01-03
APPLE
1200
1090
1100

2022-01-01
MICROSOFT
7
9
10

2022-01-02
MICROSOFT
7.5
8
9.5

2022-01-03
MICROSOFT
8
8.5
9

...
...
...
...
...

2022-01-01
NASDAQ
14400
15600
16700

2022-01-02
NASDAQ
14500
15200
16100

2022-01-03
NASDAQ
14600
15000
16000

I'm currently saving NASDAQ values and stock data on the same table using MariaDB.

However, I want to show NASDAQ's MA values as new column fields into rest of the field, as NASDAQ_MA5, NASDAQ_MA20.

My question is, how do I select nasdaq's MA5 and MA20 values and put it as the values according to the matching dates? My desired output is as follows:

Date
Code
Price
MA5
MA20
NASDAQ_MA5
NASDAQ_MA20

2022-01-01
APPLE
1000
1080
1090
15600
16700

2022-01-02
APPLE
1100
1084
1100
15200
16100

2022-01-03
APPLE
1200
1090
1100
15000
16000

2022-01-01
MICROSOFT
7
9
10
15600
16700

2022-01-02
MICROSOFT
7.5
8
9.5
15200
16100

2022-01-03
MICROSOFT
8
8.5
9
15000
16000

I've been trying the following:

        SELECT *,
        (PARTITION BY DATE, case when (code='NASDAQ') then MA5 else NULL end) as 'NASDAQ_MA5',
        (PARTITION BY DATE, case when (code='NASDAQ') then MA20 else NULL end) as 'NASDAQ_MA20'
        FROM TABLE

Your help will be very appreciated.

Body:
You need to join the two distinct sets of data. It probably makes sense to define a CTE to keep the definitions clear, then join with your main table - either an inner join if there's always a corresponding date or left join if there might not be.

This assumes there's only a single nasdaq code for each date, if that's not the case you can aggregate in the CTE as required.

with nasdaq as (
    select date, MA5 NASDAQ_MA5, MA20 NASDAQ_MA20
    from t
    where code = 'NASDAQ'
)
select t.*, n.NASDAQ_MA5, n.NASDAQ_MA20
from t
left join nasdaq n on n.date=t.date
where t.code != 'NASDAQ';


来源: stackexchange

问:
Brownie doesn't automatically attach to local ganache when I have Ganache open in the background. It is stuck with ganache-cli
Brownie doesn't automatically attach to local ganache when I have Ganache open in the background. It is stuck with ganache-cli (1st image) (2nd image is what I am looking for). Can someone help?

答:
The other solution is adding your local Ganache GUI account to the brownie networks list. To do that first you need to gather your host and chainid:

```<code>brownie networks add {network_class} {your_network_name} host={your_host} chainid={your_chaid}
</code>```

Here, you have to change values between {}. For instance:

```<code>brownie networks add Ethereum ganache-local host=http://0.0.0.0:8545 chainid=1337
</code>```

This command creates a new local network named 'ganache-local' on host 'http://0.0.0.0:8545' with '1337' chainid value in Ethereum class

To use this network on brownie commands, you need to set network flag to you network name. For instance I've created a network with the name of 'ganache-local' I can use this network like:

```<code>brownie run scripts/deploy.py --network ganache-local
</code>```

With this way, you also can track your deployments on this network in deployments folder.

ContentLicense: CC BY-SA 4.0

Body:
The other solution is adding your local Ganache GUI account to the brownie networks list. To do that first you need to gather your host and chainid:

brownie networks add {network_class} {your_network_name} host={your_host} chainid={your_chaid}

Here, you have to change values between {}. For instance:

brownie networks add Ethereum ganache-local host=http://0.0.0.0:8545 chainid=1337

This command creates a new local network named 'ganache-local' on host 'http://0.0.0.0:8545' with '1337' chainid value in Ethereum class

To use this network on brownie commands, you need to set network flag to you network name. For instance I've created a network with the name of 'ganache-local' I can use this network like:

brownie run scripts/deploy.py --network ganache-local

With this way, you also can track your deployments on this network in deployments folder.


问:
Pass of user details from Spring security config to Controller Class
Suggestion required after authentication from security config needs to pass the every user details to the APIs request.</p>

答:
The idea is that you can customise your authentication process such that after successful authentication , it will store the user object inside Authentication which can be retrieved by calling  Authentication.getPrincipal().

Then in the controller method , you can access the user object representing the current user by :

//You have cast the user to the type of the user that you customzie manually
MyCustomUser user = (MyCustomUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

```
<p>Or use <code>@AuthenticationPrincipal</code> to access it :</p>
<pre class="lang-java prettyprint-override"><code>@GetMapping("/foo")
public String getFoo(@AuthenticationPrincipal MyCustomUser user) {

}
</code>```

Body:
The idea is that you can customise your authentication process such that after successful authentication , it will store the user object inside Authentication which can be retrieved by calling  Authentication.getPrincipal().

Then in the controller method , you can access the user object representing the current user by :

//You have cast the user to the type of the user that you customzie manually
MyCustomUser user = (MyCustomUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

Or use @AuthenticationPrincipal to access it :

@GetMapping("/foo")
public String getFoo(@AuthenticationPrincipal MyCustomUser user) {

}


问:
How to compute the mean with null treated as zero
In Snowflake how can I return the mean of a column, where null values are treated as zero. So, if we have 3 values: 1, 2, NULL, I would like to return 1, not 1.5 as returned by AVG function.</p>

答:
This can be done using COALESCE to replace null values with 0:

```<code>CREATE OR REPLACE TABLE foo AS
  SELECT $1
    FROM VALUES ( 1 ), ( 2 ), ( NULL);

SELECT AVG(COALESCE($1, 0)) FROM foo;

</code>```

Body:
This can be done using COALESCE to replace null values with 0:

CREATE OR REPLACE TABLE foo AS
  SELECT $1
    FROM VALUES ( 1 ), ( 2 ), ( NULL);

SELECT AVG(COALESCE($1, 0)) FROM foo;


问:
How to use appsettings.json in Asp.net core 6 Program.cs file
I'm trying to access appsettings.json in my Asp.net core v6 application Program.cs file, but in this version of .Net the Startup class and Program class are merged together and the using and another statements are simplified and removed from Program.cs. In this situation, How to access IConfiguration or how to use dependency injection for example ?

Code

Here is my default Program.cs that Asp.net 6 created for me

```<code>var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
});

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
</code>```

For example , I want to use appsettings.json instead of hard typed connectionstring in this line :

```<code>options.Configuration = "localhost:6379";
</code>```

答:
In Program.cs, try this code:

```<code>var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

ConfigurationManager configuration = builder.Configuration;

var rabbitMQSection = configuration.GetSection("RabbitMQ");
var rabbitMQConnectionUrl = rabbitMQSection["ConnectionUrl"];
</code>```

where the appsettings.json file is:

```<code>"AllowedHosts": "*",
"RabbitMQ": {
    "ConnectionUrl": "amqp://guest:guest@localhost:5672/"
}
</code>```

Body:
I'm trying to access appsettings.json in my Asp.net core v6 application Program.cs file, but in this version of .Net the Startup class and Program class are merged together and the using and another statements are simplified and removed from Program.cs. In this situation, How to access IConfiguration or how to use dependency injection for example ?

Code

Here is my default Program.cs that Asp.net 6 created for me

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
});

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

For example , I want to use appsettings.json instead of hard typed connectionstring in this line :

options.Configuration = "localhost:6379";

Body:
In Program.cs, try this code:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

ConfigurationManager configuration = builder.Configuration;

var rabbitMQSection = configuration.GetSection("RabbitMQ");
var rabbitMQConnectionUrl = rabbitMQSection["ConnectionUrl"];

where the appsettings.json file is:

"AllowedHosts": "*",
"RabbitMQ": {
    "ConnectionUrl": "amqp://guest:guest@localhost:5672/"
}


问:
Does XCUITest type text function send a keyboard input?
Does the XCUITest typetext function actually send a keyboard event through the iOS keyboard or does it simple copy the value provided to it directly into the text box?

I tried to send in Chinese through the typeText Function while the keyboard was of English type, the text box was populated correctly with Chinese characters. But this according to me shows that the typeText function just copies the text given to it to the text box and does not send a keyboard event.

Is my understanding correct?

I have also tried out frameworks like appium but they too internally use typeText provided by XCUITest.

I have also asked this question in the apple dev forum but no replies. Hope the StackOverflow community has an answer :)

答:
For those of you stuck on this problem,

I found an answer here

There is a method called app.key['character shown on keyboard'].tap() that taps on the keyboard instead of simply copying the text and pasting it in the text box like typeText function does.


问:
Why isn't SwiftUI "Toggle.onChange" firing?
I have a toggle UI element in a List, and I need to execute code when the toggle state changes. As I understand it, that's accomplished by using a binding on the toggle, and then adding a ".onChange:of:" on the binding variable.

Done:

```<code>//

import Foundation
import SwiftUI

struct User : Hashable, Identifiable {

    var isToggled = false

    var id: String
    var firstName: String?
    var lastName: String?
    var loggedIn: Bool = false
    var loggedInSince: String?
    var isActive: Bool?
    var isAdmin: Bool?

}

struct ListRow: View {
 @EnvironmentObject var userListModel: UserListModel

 @Binding var user: User

 var body: some View {
     Toggle(isOn: $user.loggedIn) {
         VStack {
           Text("\(user.firstName!) \(user.lastName!)")
             if user.loggedIn {
                 Text("Logged in since \(user.loggedInSince!)")
                     .font(Font.system(size: 10))
             }
             else {
                 Text("Logged out since \(user.loggedInSince!)")
                     .font(Font.system(size: 10))
             }
         }
     }
     .disabled(self.cantLogInOut())
     .onChange(of: user.loggedIn) { value in  // THIS ISN'T WORKING, IT'S NOT GETTING CALLED
         // action...
         print(value)
         userListModel.changeLogStatus(user: user)
     }
 }
</code>```

So, the code in the onChange ("print", "userListModel.changeLogStatus") is never called.

I'm getting this in the console:

```<code>2022-02-12 22:56:39.860044-0500 TimeCard[10104:4072116] invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.
</code>```

I have no idea what that means, googling it isn't helpful, and when I put a Symbolic breakpoint on that error, nothing useful is shown in the debugger (it shows a stack trace that is two assembly code segments out of main.)

答:
You’re trying to bind the Toggle to the model but also have a side effect that also changes the model, that isn’t going to work.

You’ll have to replace the Toggle with a Button and in the handler call userListModel.changeLogStatus. And remove onChange. That way the model can stay as logged out when the log in Button is pressed and after the log in action is completed and the model is changed, body will be recomputed due to the change and the Button will be updated to show log out. You can also change @Binding var user to let user because you no longer need write access.

Body:
I have a toggle UI element in a List, and I need to execute code when the toggle state changes. As I understand it, that's accomplished by using a binding on the toggle, and then adding a ".onChange:of:" on the binding variable.

Done:

//

import Foundation
import SwiftUI

struct User : Hashable, Identifiable {

    var isToggled = false

    var id: String
    var firstName: String?
    var lastName: String?
    var loggedIn: Bool = false
    var loggedInSince: String?
    var isActive: Bool?
    var isAdmin: Bool?

}

struct ListRow: View {
 @EnvironmentObject var userListModel: UserListModel

 @Binding var user: User

 var body: some View {
     Toggle(isOn: $user.loggedIn) {
         VStack {
           Text("\(user.firstName!) \(user.lastName!)")
             if user.loggedIn {
                 Text("Logged in since \(user.loggedInSince!)")
                     .font(Font.system(size: 10))
             }
             else {
                 Text("Logged out since \(user.loggedInSince!)")
                     .font(Font.system(size: 10))
             }
         }
     }
     .disabled(self.cantLogInOut())
     .onChange(of: user.loggedIn) { value in  // THIS ISN'T WORKING, IT'S NOT GETTING CALLED
         // action...
         print(value)
         userListModel.changeLogStatus(user: user)
     }
 }

So, the code in the onChange ("print", "userListModel.changeLogStatus") is never called.

I'm getting this in the console:

2022-02-12 22:56:39.860044-0500 TimeCard[10104:4072116] invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.

I have no idea what that means, googling it isn't helpful, and when I put a Symbolic breakpoint on that error, nothing useful is shown in the debugger (it shows a stack trace that is two assembly code segments out of main.)


问:
timeIntervalSinceDate gives exc_bad_access or autorelease errors
So I have an object which represents a line drawn on the iPhone screen.  I also have a ball moving around on the screen, and when the ball and the line intersect, the string is given a life.  For my current build I am receiving this error constantly, with no crashes, but the ball stops moving on the screen:

2011-08-18 11:00:05.436 myProgram[192:5e03] * __NSAutoreleaseNoPool(): Object 0x1531c0 of class NSCFString autoreleased with no pool in place - just leaking

Line.h:
    @interface Line : NSObject {

```<code>//time properties
NSTimeInterval life;
NSDate *startTime;
NSDate *currentTime;
}

//time properties
@property (nonatomic, retain) NSDate *startTime;

-(void) updateLife;

-(void) beginLifeTracking;

@end
</code>```

Line.m

```<code>@synthesize startTime;

-(void)beginLifeTracking {
[self.startTime release]; //not sure if self is necessary here but startTime is released
                          //in case the same string is hit again
self.startTime = [NSDate date];
startTime = [NSDate dateWithTimeIntervalSince1970:0];
//NSLog(@"Time Interval: %f",startTime);
}

-(void) updateLife {
currentTime = [[NSDate date] retain];
NSLog(@"breakpoint1");
life = [currentTime timeIntervalSinceDate:self.startTime];
[currentTime release];
}
</code>```

I'm assuming this is some sort of memory management error, but all my attempts to remedy it have failed.  I'd really appreciate an explanation of what I'm doing wrong here. Thanks!

答:
When you call [self.startTime release], you're over-releasing. It's the job of the accessor (setStartTime:) to do this release.

The code doesn't make any sense, and is dangerous since it leaves a dangling ivar:

```<code>currentTime = [[NSDate date] retain];
NSLog(@"breakpoint1");
life = [currentTime timeIntervalSinceDate:self.startTime];
[currentTime release];
</code>```

This should be:

```<code>self.life = [[NSDate date] timeIntervalSinceDate:self.startTime];
</code>```

The fact that you're getting an autoreleasepool error suggests you're running this on a background thread. Your code is not thread-safe, so that would be a problem.

EDIT Regarding threading code, how are you calling beginLifeTracking? That would be where I would suspect you're getting onto the wrong thread. I would be very concerned about this autoreleasepool warning.

ContentLicense: CC BY-SA 3.0

Body:
So I have an object which represents a line drawn on the iPhone screen.  I also have a ball moving around on the screen, and when the ball and the line intersect, the string is given a life.  For my current build I am receiving this error constantly, with no crashes, but the ball stops moving on the screen:

2011-08-18 11:00:05.436 myProgram[192:5e03] * __NSAutoreleaseNoPool(): Object 0x1531c0 of class NSCFString autoreleased with no pool in place - just leaking

Line.h:
    @interface Line : NSObject {

//time properties
NSTimeInterval life;
NSDate *startTime;
NSDate *currentTime;
}

//time properties
@property (nonatomic, retain) NSDate *startTime;

-(void) updateLife;

-(void) beginLifeTracking;

@end

Line.m

@synthesize startTime;

-(void)beginLifeTracking {
[self.startTime release]; //not sure if self is necessary here but startTime is released
                          //in case the same string is hit again
self.startTime = [NSDate date];
startTime = [NSDate dateWithTimeIntervalSince1970:0];
//NSLog(@"Time Interval: %f",startTime);
}

-(void) updateLife {
currentTime = [[NSDate date] retain];
NSLog(@"breakpoint1");
life = [currentTime timeIntervalSinceDate:self.startTime];
[currentTime release];
}

I'm assuming this is some sort of memory management error, but all my attempts to remedy it have failed.  I'd really appreciate an explanation of what I'm doing wrong here. Thanks!

Body:
When you call [self.startTime release], you're over-releasing. It's the job of the accessor (setStartTime:) to do this release.

The code doesn't make any sense, and is dangerous since it leaves a dangling ivar:

currentTime = [[NSDate date] retain];
NSLog(@"breakpoint1");
life = [currentTime timeIntervalSinceDate:self.startTime];
[currentTime release];

This should be:

self.life = [[NSDate date] timeIntervalSinceDate:self.startTime];

The fact that you're getting an autoreleasepool error suggests you're running this on a background thread. Your code is not thread-safe, so that would be a problem.

EDIT Regarding threading code, how are you calling beginLifeTracking? That would be where I would suspect you're getting onto the wrong thread. I would be very concerned about this autoreleasepool warning.


问:
SpringBoot - Derby Runtime Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured
I have this below pom.xml file. I am getting this error message while trying to run my application.
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

I googled and few resources say that this problem should not come for the in-memory database version like H2, Derby etc. Yet, I am running into this problem.

Tried updating application.properties with

```<code>#PROFILES
spring.profiles.active=dev
#JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration)
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database=default
spring.jpa.show-sql=true
#DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.continue-on-error=false
spring.datasource.generate-unique-name=false
</code>```

and with

```<code>spring.datasource.url=jdbc:derby:memory:local;create=true
spring.datasource.username=derbyuser
spring.datasource.password=password
</code>```

but no respite. Please let me know what/where I am missing.

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>io.firehose</groupId>
    <artifactId>SpringBootJPA</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.5.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.3.10</version>
        </dependency>

        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <version>10.15.2.0</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <properties>
        <maven.compiler.source>14</maven.compiler.source>
        <maven.compiler.target>14</maven.compiler.target>
    </properties>

</project>
</code>```

答:
I had similar problem while creating a project locally. Have resolved it using below:</p>
```<code>@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
</code>```

Body:
I have this below pom.xml file. I am getting this error message while trying to run my application.
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

I googled and few resources say that this problem should not come for the in-memory database version like H2, Derby etc. Yet, I am running into this problem.

Tried updating application.properties with

#PROFILES
spring.profiles.active=dev
#JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration)
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database=default
spring.jpa.show-sql=true
#DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.continue-on-error=false
spring.datasource.generate-unique-name=false

and with

spring.datasource.url=jdbc:derby:memory:local;create=true
spring.datasource.username=derbyuser
spring.datasource.password=password

but no respite. Please let me know what/where I am missing.

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>io.firehose</groupId>
    <artifactId>SpringBootJPA</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.5.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.3.10</version>
        </dependency>

        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <version>10.15.2.0</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <properties>
        <maven.compiler.source>14</maven.compiler.source>
        <maven.compiler.target>14</maven.compiler.target>
    </properties>

</project>

Body:
I had similar problem while creating a project locally. Have resolved it using below:

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})


问:
how to solve the problem(@id needs to be declared) in sqladapter.InsertCommand c# ado.net
I keep getting this error

System.Data.SqlClient.SqlException: La variable scalaire "@id" doit être déclarée.

on the adapter's insert command, even if my value is declared in the parameters

What should I do?

Here is the code

```<code>private void BT_Add_Click(object sender, EventArgs e)
{
    adapter.SelectCommand.Parameters.AddWithValue("@id", txtID.Text);
    adapter.SelectCommand.Parameters.AddWithValue("@name", txtName.Text);
    adapter.SelectCommand.Parameters.AddWithValue("@lastname", txtLastName.Text);
    adapter.SelectCommand.Parameters.AddWithValue("@adress", txtAdress.Text);
    adapter.SelectCommand.Parameters.AddWithValue("@email", txtEmail.Text);
    connection.Open();
    adapter.InsertCommand = new SqlCommand("insert into client values(@id,@name,@lastname,@adress,@email)", connection);
    adapter.InsertCommand.ExecuteNonQuery();
    MessageBox.Show("Row inserted !! ");
}
</code>```

答:
You've added parameters to the SelectCommand; this does not automatically add them to the InsertCommand. The two commands are different things

You don't need an adapter here; just make a new SqlCommand, set the SQL, add the parameters to it and execute it

Body:
I keep getting this error

System.Data.SqlClient.SqlException: La variable scalaire "@id" doit être déclarée.

on the adapter's insert command, even if my value is declared in the parameters

What should I do?

Here is the code

private void BT_Add_Click(object sender, EventArgs e)
{
    adapter.SelectCommand.Parameters.AddWithValue("@id", txtID.Text);
    adapter.SelectCommand.Parameters.AddWithValue("@name", txtName.Text);
    adapter.SelectCommand.Parameters.AddWithValue("@lastname", txtLastName.Text);
    adapter.SelectCommand.Parameters.AddWithValue("@adress", txtAdress.Text);
    adapter.SelectCommand.Parameters.AddWithValue("@email", txtEmail.Text);
    connection.Open();
    adapter.InsertCommand = new SqlCommand("insert into client values(@id,@name,@lastname,@adress,@email)", connection);
    adapter.InsertCommand.ExecuteNonQuery();
    MessageBox.Show("Row inserted !! ");
}


问:
Can't add rows to grouped data frames
This is a follow-up question of this How to add a row to a dataframe modifying only some columns.

After solving this question I wanted to apply the solution provided by stefan to a larger dataframe with group_by:

My dataframe:

```<code>df <- structure(list(test_id = c(1, 1, 1, 1, 1, 1, 1, 1), test_nr = c(1,
1, 1, 1, 2, 2, 2, 2), region = c("A", "B", "C", "D", "A", "B",
"C", "D"), test_value = c(3, 1, 1, 2, 4, 2, 4, 1)), class = "data.frame", row.names = c(NA,
-8L))

  test_id test_nr region test_value
1       1       1      A          3
2       1       1      B          1
3       1       1      C          1
4       1       1      D          2
5       1       2      A          4
6       1       2      B          2
7       1       2      C          4
8       1       2      D          1

</code>```

I now want to add a new row to each group with this code, which gives an error:

```<code>df %>%
  group_by(test_nr) %>%
  add_row(test_id = .$test_id[1], test_nr = .$test_nr[1], region = "mean", test_value = mean(.$test_value))

Error: Can't add rows to grouped data frames.
Run `rlang::last_error()` to see where the error occurred.

</code>```

My expected output would be:

```<code>   test_id test_nr region test_value
1        1       1      A       3.00
2        1       1      B       1.00
3        1       1      C       1.00
4        1       1      D       2.00
5        1       1   MEAN       1.75
6        1       2      A       4.00
7        1       2      B       2.00
8        1       2      C       4.00
9        1       2      D       1.00
10       1       2   MEAN       2.75
</code>```

I have tried so far:

```<code>library(tidyverse)

df %>%
  group_by(test_nr) %>%
  group_split() %>%
  map_dfr(~ .x %>%
            add_row(!!! map(.[4], mean)))

   test_id test_nr region test_value
     <dbl>   <dbl> <chr>       <dbl>
 1       1       1 A            3
 2       1       1 B            1
 3       1       1 C            1
 4       1       1 D            2
 5      NA      NA NA           1.75
 6       1       2 A            4
 7       1       2 B            2
 8       1       2 C            4
 9       1       2 D            1
10      NA      NA NA           2.75

</code>```

How could I modify column 1 to 3 to place my values there?

答:
I actually recently made a little helper function for exactly this. The idea
is to use group_modify() to take the group data, and
bind_rows() the summary statistics calculated with summarise().

This is what it looks like in code:

add_summary_rows <- function(.data, ...) {
  group_modify(.data, function(x, y) bind_rows(x, summarise(x, ...)))
}
```
<p>And here’s how that would work with your data:</p>
<pre class="lang-r prettyprint-override"><code>library(dplyr, warn.conflicts = FALSE)

df <- data.frame(
  test_id = c(1, 1, 1, 1, 1, 1, 1, 1),
  test_nr = c(1, 1, 1, 1, 2, 2, 2, 2),
  region = c("A", "B", "C", "D", "A", "B", "C", "D"),
  test_value = c(3, 1, 1, 2, 4, 2, 4, 1)
)

df %>%
  group_by(test_id, test_nr) %>%
  add_summary_rows(
    region = "MEAN",
    test_value = mean(test_value)
  )
#> # A tibble: 10 x 4
#> # Groups:   test_id, test_nr [2]
#>    test_id test_nr region test_value
#>      <dbl>   <dbl> <chr>       <dbl>
#>  1       1       1 A            3
#>  2       1       1 B            1
#>  3       1       1 C            1
#>  4       1       1 D            2
#>  5       1       1 MEAN         1.75
#>  6       1       2 A            4
#>  7       1       2 B            2
#>  8       1       2 C            4
#>  9       1       2 D            1
#> 10       1       2 MEAN         2.75
</code>```

Title: Can't add rows to grouped data frames

Body:
This is a follow-up question of this How to add a row to a dataframe modifying only some columns.

After solving this question I wanted to apply the solution provided by stefan to a larger dataframe with group_by:

My dataframe:

df <- structure(list(test_id = c(1, 1, 1, 1, 1, 1, 1, 1), test_nr = c(1,
1, 1, 1, 2, 2, 2, 2), region = c("A", "B", "C", "D", "A", "B",
"C", "D"), test_value = c(3, 1, 1, 2, 4, 2, 4, 1)), class = "data.frame", row.names = c(NA,
-8L))

  test_id test_nr region test_value
1       1       1      A          3
2       1       1      B          1
3       1       1      C          1
4       1       1      D          2
5       1       2      A          4
6       1       2      B          2
7       1       2      C          4
8       1       2      D          1

I now want to add a new row to each group with this code, which gives an error:

df %>%
  group_by(test_nr) %>%
  add_row(test_id = .$test_id[1], test_nr = .$test_nr[1], region = "mean", test_value = mean(.$test_value))

Error: Can't add rows to grouped data frames.
Run `rlang::last_error()` to see where the error occurred.

My expected output would be:

   test_id test_nr region test_value
1        1       1      A       3.00
2        1       1      B       1.00
3        1       1      C       1.00
4        1       1      D       2.00
5        1       1   MEAN       1.75
6        1       2      A       4.00
7        1       2      B       2.00
8        1       2      C       4.00
9        1       2      D       1.00
10       1       2   MEAN       2.75

I have tried so far:

library(tidyverse)

df %>%
  group_by(test_nr) %>%
  group_split() %>%
  map_dfr(~ .x %>%
            add_row(!!! map(.[4], mean)))

   test_id test_nr region test_value
     <dbl>   <dbl> <chr>       <dbl>
 1       1       1 A            3
 2       1       1 B            1
 3       1       1 C            1
 4       1       1 D            2
 5      NA      NA NA           1.75
 6       1       2 A            4
 7       1       2 B            2
 8       1       2 C            4
 9       1       2 D            1
10      NA      NA NA           2.75

How could I modify column 1 to 3 to place my values there?

Body:
I actually recently made a little helper function for exactly this. The idea
is to use group_modify() to take the group data, and
bind_rows() the summary statistics calculated with summarise().

This is what it looks like in code:

add_summary_rows <- function(.data, ...) {
  group_modify(.data, function(x, y) bind_rows(x, summarise(x, ...)))
}

And here’s how that would work with your data:

library(dplyr, warn.conflicts = FALSE)

df <- data.frame(
  test_id = c(1, 1, 1, 1, 1, 1, 1, 1),
  test_nr = c(1, 1, 1, 1, 2, 2, 2, 2),
  region = c("A", "B", "C", "D", "A", "B", "C", "D"),
  test_value = c(3, 1, 1, 2, 4, 2, 4, 1)
)

df %>%
  group_by(test_id, test_nr) %>%
  add_summary_rows(
    region = "MEAN",
    test_value = mean(test_value)
  )
#> # A tibble: 10 x 4
#> # Groups:   test_id, test_nr [2]
#>    test_id test_nr region test_value
#>      <dbl>   <dbl> <chr>       <dbl>
#>  1       1       1 A            3
#>  2       1       1 B            1
#>  3       1       1 C            1
#>  4       1       1 D            2
#>  5       1       1 MEAN         1.75
#>  6       1       2 A            4
#>  7       1       2 B            2
#>  8       1       2 C            4
#>  9       1       2 D            1
#> 10       1       2 MEAN         2.75


问:
Breakpoints in JRE System Library in Eclipse
I tried to make breakpoint in the class from JRE System Library, but when I started debug I recieved message: "Unable to install breakpoint at ... due to missing line number attributes. Modify compiler options to generate line number attributes."
So what should I do: recompile JRE System Library from sources with debug information and use it? Or there is some more simple way?</p>

答: The simplest thing to do is get the equivalent JDK and target that instead.</p>


问:
-bash: matlab: command not found
I am a bit surprised, but I can't run matlab by the terminal of my Mac.
I am trying the command

```<code>/Applications/MATLAB_R2015b.app/bin/matlab
</code>```

but I get the error

```<code>-bash: matlab: command not found
</code>```

Listing the contenents of the folder /Applications/MATLAB_R2015b.app/bin/ I can see the word matlab which is supposed to be the executable.
I don't know what's happening.

答:
It works fine, however, if you used the default folder it would be something like export PATH=/usr/local/MATLAB/R2021b/bin/:$PATH
Additionally, remember about activating matlab before via running the activate_matlab.sh script located in the installation folder

Title: -bash: matlab: command not found

Body:
I am a bit surprised, but I can't run matlab by the terminal of my Mac.
I am trying the command

/Applications/MATLAB_R2015b.app/bin/matlab

but I get the error

-bash: matlab: command not found

Listing the contenents of the folder /Applications/MATLAB_R2015b.app/bin/ I can see the word matlab which is supposed to be the executable.
I don't know what's happening.


问:
Operator in variable Swift
I am trying to make a function to see if all my textfields are filled in, I pass it an array, Let's say var array = ["1", "2", "3"]

And I want to check the if statement if array[0].isEmpty || array[1].isEmpty || array[2].isEmpty

But it has to be variable, so I thought about using a for loop and using the operator as a variable, that doesn't work, at least not how I am doing it, does anyone have an idea for this?

```<code>var op = false

    for field in array {
        op += field.isEmpty
        op += ||
    }

    if op {

    }
</code>```

Kind regards
Daan

答:
Try</p>
```<code>array.allSatisfy{ !$0.isEmpty } // false => means that one or more items is/are empty
</code>```

Title: Operator in variable Swift

Body:
I am trying to make a function to see if all my textfields are filled in, I pass it an array, Let's say var array = ["1", "2", "3"]

And I want to check the if statement if array[0].isEmpty || array[1].isEmpty || array[2].isEmpty

But it has to be variable, so I thought about using a for loop and using the operator as a variable, that doesn't work, at least not how I am doing it, does anyone have an idea for this?

var op = false

    for field in array {
        op += field.isEmpty
        op += ||
    }

    if op {

    }

Kind regards
Daan

Body:
Try

array.allSatisfy{ !$0.isEmpty } // false => means that one or more items is/are empty


问:
Put labels in Coolprop Chart
Following the idea of Sino-Atrial Node (link):

```<code>from CoolProp.Plots import PropertyPlot

plot = PropertyPlot("Water", 'Ph')
plot.calc_isolines()
ax = plot.axis
ax.text(2000, 100, ' 1', fontsize=10, rotation=45, color='r')
plot.show()
</code>```

I try to reproduce it, to introduce labels in the Coolprop chart in these lines of code, but without result.

Any idea how to achieve this goal?
It is possible to improve the code. Improvements and changes will be welcome.

These are the lines of code:

```<code>#pyimport("sys").executable
from numpy import shape as size
from matplotlib import pyplot as plt
from CoolProp import CoolProp as CP
from CoolProp.Plots import PropertyPlot as CPP #StateContainer
from CoolProp.Plots import SimpleCompressionCycle as CPPSCC

TT =( [[55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55],
[33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])

n=size(TT)[1]

for i in range(size(TT)[1]):
 pp = CPP("R32", "PH", unit_system="KSI")
 #pp.title("R32 log p-h Diagramm_"+str(i))
 pp.set_axis_limits([-40, 700, 0, 15000])
 pp.xlabel("h [kJ/kg]")
 pp.ylabel("P [kPa]")
 pp.calc_isolines(CP.iQ, num=11)
 cycle = CPPSCC("R32", "PH", unit_system="KSI")
 T0 = TT[1][i]+273.15
 pp.state.update(CP.QT_INPUTS,0.0,T0-0.02)
 p0 = pp.state.keyed_output(CP.iP)
 T2 = TT[0][i]+273.15
 pp.state.update(CP.QT_INPUTS,1.0,T2+0.02)
 p2 = pp.state.keyed_output(CP.iP)
 pp.calc_isolines(CP.iT, [T0 ,T2 ], num=2)
 pp.props[CP.iT]['color'] = 'green'
 pp.props[CP.iT]['lw'] = '0.5'
 txt ="T0 {:.2f}K /P0 {:.2f}MPa \n T2 {:.2f}K /P2 {:.2f}MPa".format(T0,p0/1e6,T2,p2/1e6)
 pp.title("R32 log p-h Diagramm \n "+txt)

 pa=0.996424*100000
 h=CP.PropsSI("H","P",pa,"T",T0,"R32")

 cycle.simple_solve(T0, p0, T2, p2, 0.7, SI=True)
 cycle.steps =50
 sc = cycle.get_state_changes()
 #label 1
 pp.draw_process(sc,line_opts={'color':'blue', 'lw':1.5})
 pp.grid()
 ax = pp.axis
 lb1="{:.2f}K".format(T0)
 ax.text(h, pa, lb1, fontsize=10, rotation=45, color='r')

 plt.close(cycle.figure)
 pp.show()

</code>```

答:
In my example, shown above, the labels cannot be displayed because the calculation units do not match those of the graph.
To be able to visualize the units and values use the property: _cycle_states.

```<code>from numpy import shape as size
from matplotlib import pyplot as plt
from CoolProp import CoolProp as CP
from CoolProp.Plots import PropertyPlot as CPP #StateContainer
from CoolProp.Plots import SimpleCompressionCycle as CPPSCC

import matplotlib.transforms as mtransforms

TT =( [[55, 55, 55, 55, 55],
    [33, 34, 35, 36, 37]])

n=size(TT)[1]

for i in range(size(TT)[1]):
 pp = CPP("R32", "PH", unit_system="KSI")
 #pp.title("R32 log p-h Diagramm_"+str(i))
 pp.set_axis_limits([-40, 700, 0, 15000])
 pp.xlabel("h [kJ/kg]")
 pp.ylabel("P [kPa]")
 pp.calc_isolines(CP.iQ, num=11)
 cycle = CPPSCC("R32", "PH", unit_system="KSI")
 T0 = TT[1][i]+273.15
 pp.state.update(CP.QT_INPUTS,0.0,T0-0.02)
 p0 = pp.state.keyed_output(CP.iP)
 T2 = TT[0][i]+273.15
 pp.state.update(CP.QT_INPUTS,1.0,T2+0.02)
 p2 = pp.state.keyed_output(CP.iP)
 pp.calc_isolines(CP.iT, [T0 ,T2 ], num=2)
 pp.props[CP.iT]['color'] = 'green'
 pp.props[CP.iT]['lw'] = '0.5'
 pp.title("R32 log p-h Diagramm ")

 cycle.simple_solve(T0, p0, T2, p2, 0.7, SI=True)
 cycle.steps =50
 sc = cycle.get_state_changes()
 pp.draw_process(sc,line_opts={'color':'blue', 'lw':1.5})
 pp.grid()
 #View the values and units used in the calculation
 print(cycle._cycle_states)
 #LABELS
 fig = pp.figure
 ax = pp.axis
 trans_offset = mtransforms.offset_copy(ax.transData, fig=fig,
                                       x=-0.12, y=0.10, units='inches')

 #label 1
 T0=cycle._cycle_states[0,"T"]
 pa=0.996424#Pressure value selected to place the labels
 h=CP.PropsSI("H","P",pa,"T",T0,"R32")/1000
 lb1="{:.2f}K".format(T0)
 ax.text(h, pa, lb1, fontsize=10, rotation=90, color='r',transform=trans_offset,horizontalalignment='left',verticalalignment='baseline')
 #label 2
 T2=cycle._cycle_states[2,"T"]
 pa=0.996424##Pressure value selected to place the labels
 h=CP.PropsSI("H","P",pa,"T",T2,"R32")/1000
 lb2="{:.2f}K".format(T2)
 ax.text(h, pa, lb2, fontsize=10, rotation=90, color='r',transform=trans_offset,horizontalalignment='left',verticalalignment='baseline')

 #Pressures
 trans_offset = mtransforms.offset_copy(ax.transData, fig=fig,
                                       x=0, y=0.02, units='inches')
 #label p1
 p0=cycle._cycle_states[0,"P"]/1000
 h03=(sum(cycle._cycle_states.H[[0,3]])/2)/1000
 lbp0="{:.2f}KPa".format(p0)
 ax.text(h03, p0, lbp0, fontsize=10, rotation=0, color='b',horizontalalignment='center',transform=trans_offset)
 #label p2
 p1=cycle._cycle_states[1,"P"]/1000
 h12=(sum(cycle._cycle_states.H[[1,2]])/2)/1000
 lbp1="{:.2f}KPa".format(p1)
 ax.text(h12, p1, lbp1, fontsize=10, rotation=0, color='b',horizontalalignment='center',transform=trans_offset)

 plt.close(cycle.figure)
 pp.show()

</code>```

The results are shown in the graph.

Title: Put labels in Coolprop Chart

Body:
Following the idea of Sino-Atrial Node (link):

from CoolProp.Plots import PropertyPlot

plot = PropertyPlot("Water", 'Ph')
plot.calc_isolines()
ax = plot.axis
ax.text(2000, 100, ' 1', fontsize=10, rotation=45, color='r')
plot.show()

I try to reproduce it, to introduce labels in the Coolprop chart in these lines of code, but without result.

Any idea how to achieve this goal?
It is possible to improve the code. Improvements and changes will be welcome.

These are the lines of code:

#pyimport("sys").executable
from numpy import shape as size
from matplotlib import pyplot as plt
from CoolProp import CoolProp as CP
from CoolProp.Plots import PropertyPlot as CPP #StateContainer
from CoolProp.Plots import SimpleCompressionCycle as CPPSCC

TT =( [[55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55],
[33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])

n=size(TT)[1]

for i in range(size(TT)[1]):
 pp = CPP("R32", "PH", unit_system="KSI")
 #pp.title("R32 log p-h Diagramm_"+str(i))
 pp.set_axis_limits([-40, 700, 0, 15000])
 pp.xlabel("h [kJ/kg]")
 pp.ylabel("P [kPa]")
 pp.calc_isolines(CP.iQ, num=11)
 cycle = CPPSCC("R32", "PH", unit_system="KSI")
 T0 = TT[1][i]+273.15
 pp.state.update(CP.QT_INPUTS,0.0,T0-0.02)
 p0 = pp.state.keyed_output(CP.iP)
 T2 = TT[0][i]+273.15
 pp.state.update(CP.QT_INPUTS,1.0,T2+0.02)
 p2 = pp.state.keyed_output(CP.iP)
 pp.calc_isolines(CP.iT, [T0 ,T2 ], num=2)
 pp.props[CP.iT]['color'] = 'green'
 pp.props[CP.iT]['lw'] = '0.5'
 txt ="T0 {:.2f}K /P0 {:.2f}MPa \n T2 {:.2f}K /P2 {:.2f}MPa".format(T0,p0/1e6,T2,p2/1e6)
 pp.title("R32 log p-h Diagramm \n "+txt)

 pa=0.996424*100000
 h=CP.PropsSI("H","P",pa,"T",T0,"R32")

 cycle.simple_solve(T0, p0, T2, p2, 0.7, SI=True)
 cycle.steps =50
 sc = cycle.get_state_changes()
 #label 1
 pp.draw_process(sc,line_opts={'color':'blue', 'lw':1.5})
 pp.grid()
 ax = pp.axis
 lb1="{:.2f}K".format(T0)
 ax.text(h, pa, lb1, fontsize=10, rotation=45, color='r')

 plt.close(cycle.figure)
 pp.show()

Body:
In my example, shown above, the labels cannot be displayed because the calculation units do not match those of the graph.
To be able to visualize the units and values use the property: _cycle_states.

from numpy import shape as size
from matplotlib import pyplot as plt
from CoolProp import CoolProp as CP
from CoolProp.Plots import PropertyPlot as CPP #StateContainer
from CoolProp.Plots import SimpleCompressionCycle as CPPSCC

import matplotlib.transforms as mtransforms

TT =( [[55, 55, 55, 55, 55],
    [33, 34, 35, 36, 37]])

n=size(TT)[1]

for i in range(size(TT)[1]):
 pp = CPP("R32", "PH", unit_system="KSI")
 #pp.title("R32 log p-h Diagramm_"+str(i))
 pp.set_axis_limits([-40, 700, 0, 15000])
 pp.xlabel("h [kJ/kg]")
 pp.ylabel("P [kPa]")
 pp.calc_isolines(CP.iQ, num=11)
 cycle = CPPSCC("R32", "PH", unit_system="KSI")
 T0 = TT[1][i]+273.15
 pp.state.update(CP.QT_INPUTS,0.0,T0-0.02)
 p0 = pp.state.keyed_output(CP.iP)
 T2 = TT[0][i]+273.15
 pp.state.update(CP.QT_INPUTS,1.0,T2+0.02)
 p2 = pp.state.keyed_output(CP.iP)
 pp.calc_isolines(CP.iT, [T0 ,T2 ], num=2)
 pp.props[CP.iT]['color'] = 'green'
 pp.props[CP.iT]['lw'] = '0.5'
 pp.title("R32 log p-h Diagramm ")

 cycle.simple_solve(T0, p0, T2, p2, 0.7, SI=True)
 cycle.steps =50
 sc = cycle.get_state_changes()
 pp.draw_process(sc,line_opts={'color':'blue', 'lw':1.5})
 pp.grid()
 #View the values and units used in the calculation
 print(cycle._cycle_states)
 #LABELS
 fig = pp.figure
 ax = pp.axis
 trans_offset = mtransforms.offset_copy(ax.transData, fig=fig,
                                       x=-0.12, y=0.10, units='inches')

 #label 1
 T0=cycle._cycle_states[0,"T"]
 pa=0.996424#Pressure value selected to place the labels
 h=CP.PropsSI("H","P",pa,"T",T0,"R32")/1000
 lb1="{:.2f}K".format(T0)
 ax.text(h, pa, lb1, fontsize=10, rotation=90, color='r',transform=trans_offset,horizontalalignment='left',verticalalignment='baseline')
 #label 2
 T2=cycle._cycle_states[2,"T"]
 pa=0.996424##Pressure value selected to place the labels
 h=CP.PropsSI("H","P",pa,"T",T2,"R32")/1000
 lb2="{:.2f}K".format(T2)
 ax.text(h, pa, lb2, fontsize=10, rotation=90, color='r',transform=trans_offset,horizontalalignment='left',verticalalignment='baseline')

 #Pressures
 trans_offset = mtransforms.offset_copy(ax.transData, fig=fig,
                                       x=0, y=0.02, units='inches')
 #label p1
 p0=cycle._cycle_states[0,"P"]/1000
 h03=(sum(cycle._cycle_states.H[[0,3]])/2)/1000
 lbp0="{:.2f}KPa".format(p0)
 ax.text(h03, p0, lbp0, fontsize=10, rotation=0, color='b',horizontalalignment='center',transform=trans_offset)
 #label p2
 p1=cycle._cycle_states[1,"P"]/1000
 h12=(sum(cycle._cycle_states.H[[1,2]])/2)/1000
 lbp1="{:.2f}KPa".format(p1)
 ax.text(h12, p1, lbp1, fontsize=10, rotation=0, color='b',horizontalalignment='center',transform=trans_offset)

 plt.close(cycle.figure)
 pp.show()

The results are shown in the graph.


问:
React: Rendering a list of components by passing the list as a prop
I'm currently following a tutorial on React and am interested as to how this is possible:

```<code>class Counters extends Component {
  state = {
    counters: [
      { id: 0, value: 0 },
      { id: 1, value: 4 },
      { id: 2, value: 5 },
      { id: 3, value: 9 },
    ],
  };

  handleDelete = (counterID) => {
      console.log("Event handler called", counterID);
      const counters = this.state.counters.filter((c) => c.id !== counterID);
      this.setState({ counters });
  };

render() {
    return (
      <React.Fragment>
        {this.state.counters.map((counters) => (
          <Counter
            key={counters.id}
            counters={counters}
            onDelete={this.handleDelete}
          ></Counter>
        ))}
      </React.Fragment>
    );
  }
</code>```

I am using the "Counters" to keep track of my individual "Counter" (notice the singular noun) components. I am interested to know why is it that I can simply pass the entire array as a prop into "Counter" with this line:

```<code>counters={counters}
</code>```

and with the following code in the "Counter" class:

```<code>class Counter extends Component {
  state = {
    value: this.props.counters.value,
    tags: ["tag1", "tag2", "tag3"],
  };

  styles = {
    fontSize: "50px",
    fontWeight: "bolder",
  };

  handleIncrement() {
    console.log("Increment clicked.");
    this.setState({ value: this.state.count + 1 });
  }

  render() {
    console.log(this.props);
    return (
      <React.Fragment>
        <h4>Counter #{this.props.counters.id}</h4>
        <span style={{ fontSize: "25px" }} className={this.getBadgeClasses()}>
          {this.formatCount()}
        </span>
        <button
          onClick={() => this.handleIncrement()}
          className="btn btn-secondary btn-sm m-2"
        >
          Increment
        </button>
        <button
          onClick={() => this.props.onDelete(this.props.counters.id)}
          className="btn btn-danger btn-sm m-2"
        >
          Delete
        </button>
        {this.renderTags()}
      </React.Fragment>
    );
  }

  getTags() {
    let tags = this.state.tags;
    return tags === undefined || tags.length <= 0 ? (
      <p>"The tag list is empty."</p>
    ) : (
      tags.map((tag) => <li key={tag}>{tag}</li>)
    );
  }

  renderTags() {
    return <ul>{this.getTags()}</ul>;
  }

  getBadgeClasses() {
    let classes = "badge m-2 badge-";
    classes += this.state.value === 0 ? "warning" : "primary";
    return classes;
  }

  formatCount() {
    const value = this.state.value;
    return value === 0 ? "Zero" : value;
  }
}

export default Counter;
</code>```

I am able to get an entire list of "Counter" components rendered? I was under the impression I only declared a single  in the "Counters" class, yet by passing a list I am able to render an entire list of Counters. How is this possible? What concept am I missing here?

答:
If you want past the entire list on Counter component :

```<code>counters={this.state.counters}
</code>```

Because with counter={counters} you past in fact one element (method map send on item by one item). So in fact, when you write this.state.counters.map((counters) => ..., you should write this.state.counters.map((counter) =>... because it's just one element of array counters.

Body:
I'm currently following a tutorial on React and am interested as to how this is possible:

class Counters extends Component {
  state = {
    counters: [
      { id: 0, value: 0 },
      { id: 1, value: 4 },
      { id: 2, value: 5 },
      { id: 3, value: 9 },
    ],
  };

  handleDelete = (counterID) => {
      console.log("Event handler called", counterID);
      const counters = this.state.counters.filter((c) => c.id !== counterID);
      this.setState({ counters });
  };

render() {
    return (
      <React.Fragment>
        {this.state.counters.map((counters) => (
          <Counter
            key={counters.id}
            counters={counters}
            onDelete={this.handleDelete}
          ></Counter>
        ))}
      </React.Fragment>
    );
  }

I am using the "Counters" to keep track of my individual "Counter" (notice the singular noun) components. I am interested to know why is it that I can simply pass the entire array as a prop into "Counter" with this line:

counters={counters}

and with the following code in the "Counter" class:

class Counter extends Component {
  state = {
    value: this.props.counters.value,
    tags: ["tag1", "tag2", "tag3"],
  };

  styles = {
    fontSize: "50px",
    fontWeight: "bolder",
  };

  handleIncrement() {
    console.log("Increment clicked.");
    this.setState({ value: this.state.count + 1 });
  }

  render() {
    console.log(this.props);
    return (
      <React.Fragment>

Counter #{this.props.counters.id}

          {this.formatCount()}

        <button
          onClick={() => this.handleIncrement()}
          className="btn btn-secondary btn-sm m-2"
        >
          Increment
        </button>
        <button
          onClick={() => this.props.onDelete(this.props.counters.id)}
          className="btn btn-danger btn-sm m-2"
        >
          Delete
        </button>
        {this.renderTags()}
      </React.Fragment>
    );
  }

  getTags() {
    let tags = this.state.tags;
    return tags === undefined || tags.length <= 0 ? (

"The tag list is empty."

    ) : (
      tags.map((tag) =>
{tag}
)
    );
  }

  renderTags() {
    return
{this.getTags()}
;
  }

  getBadgeClasses() {
    let classes = "badge m-2 badge-";
    classes += this.state.value === 0 ? "warning" : "primary";
    return classes;
  }

  formatCount() {
    const value = this.state.value;
    return value === 0 ? "Zero" : value;
  }
}

export default Counter;

I am able to get an entire list of "Counter" components rendered? I was under the impression I only declared a single  in the "Counters" class, yet by passing a list I am able to render an entire list of Counters. How is this possible? What concept am I missing here?

Body:
If you want past the entire list on Counter component :

counters={this.state.counters}

Because with counter={counters} you past in fact one element (method map send on item by one item). So in fact, when you write this.state.counters.map((counters) => ..., you should write this.state.counters.map((counter) =>... because it's just one element of array counters.


问:
Docker + Django + Postgres Add-on + Heroku
So I'm running through the following:

Created a Dockerfile and a docker-compose.yml to develop a django app locally, nothing to do here, everything works just fine.

Dockerfile

FROM python:3

ENV PYTHONUNBUFFERED 1

RUN mkdir /code

WORKDIR /code

ADD requirements.txt /code/

RUN pip install -r requirements.txt

ADD . /code/

All it does is fetches python3 image, copies the code from my source folder to the docker image

Then I'm trying to deploy this to heroku, so I added postgres add-on on heroku apps, and configured it using dj_database_url, with the following command on my settings.py file :
DATABASES = {}
DATABASES['default'] = dj_database_url.config()

After that I pushed my application to heroku using heroku container:push web and it got pushed to my app no problem at all...

The final piece is when I open my application using heroku open it says I got an error: Application error
An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.

This is what get printed on the heroku website

Now, when I log using heroku logs -t, it says that exited with code 0, then it crashes

What am I missing?

Plus: when I run heroku run web python manage.py migrate it migrates the data on the heroku app

Plus 2: when I run  heroku run web python manage.py runserver it says is running on 127.0.0.1:8000

EDIT 1:
If you want to reproduce the problem you can clone all my code in the following git repo: https://github.com/giovanniKleinCampigoto/djangoherokuproblem.git

EDIT 2:

In this official tutorial: https://devcenter.heroku.com/articles/deploying-python , says to use virtualenv, but I'm using docker, so I don't really know how to proceed...

EDIT 3:
 Also, I noticed that when I push the image to heroku using: heroku container:push web, the server re-deploys, but instead of running whatever is on the procfile it just logs this:
 Starting process with command python3]

EDIT 4:
When running heroku local web, and editing the Procfile to run docker-compose up works just fine, the problem is with the upload to heroku's server...not sure if I should edit the file to just python manage.py runserver...

docker-compose.yml

```<code>version: '2'

services:
  web:
    build: .
    env_file: composeexample/.env
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
</code>```

答: also Don't forget to add your application domain:"app-name.herokuapp.com" in ALLOWED_HOST = ['app-name.herokuapp.com'] in project settings.py.</p>

Body:
So I'm running through the following:

Created a Dockerfile and a docker-compose.yml to develop a django app locally, nothing to do here, everything works just fine.

Dockerfile

FROM python:3

ENV PYTHONUNBUFFERED 1

RUN mkdir /code

WORKDIR /code

ADD requirements.txt /code/

RUN pip install -r requirements.txt

ADD . /code/

All it does is fetches python3 image, copies the code from my source folder to the docker image

Then I'm trying to deploy this to heroku, so I added postgres add-on on heroku apps, and configured it using dj_database_url, with the following command on my settings.py file :
DATABASES = {}
DATABASES['default'] = dj_database_url.config()

After that I pushed my application to heroku using heroku container:push web and it got pushed to my app no problem at all...

The final piece is when I open my application using heroku open it says I got an error: Application error
An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.

This is what get printed on the heroku website

Now, when I log using heroku logs -t, it says that exited with code 0, then it crashes

What am I missing?

Plus: when I run heroku run web python manage.py migrate it migrates the data on the heroku app

Plus 2: when I run  heroku run web python manage.py runserver it says is running on 127.0.0.1:8000

EDIT 1:
If you want to reproduce the problem you can clone all my code in the following git repo: https://github.com/giovanniKleinCampigoto/djangoherokuproblem.git

EDIT 2:

In this official tutorial: https://devcenter.heroku.com/articles/deploying-python , says to use virtualenv, but I'm using docker, so I don't really know how to proceed...

EDIT 3:
 Also, I noticed that when I push the image to heroku using: heroku container:push web, the server re-deploys, but instead of running whatever is on the procfile it just logs this:
 Starting process with command python3]

EDIT 4:
When running heroku local web, and editing the Procfile to run docker-compose up works just fine, the problem is with the upload to heroku's server...not sure if I should edit the file to just python manage.py runserver...

docker-compose.yml

version: '2'

services:
  web:
    build: .
    env_file: composeexample/.env
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"


问:
Upgrade appearance of VS6 MFC dialog application to VS2008
I'm updating a VS6 MFC dialog application to VS2008.  Updating the code has been easy, but the dialog still has the old fashioned VS6 appearance to it.  For example, the Group Boxes have square edges and are dark grey.  Instead of the rounded corners and light grey of a VS2008 application Group Box.

How can I force my application to use the more modern appearance of VS2008 MFC dialog applications?

答:
A new MFC project will add the following to stdafx.h:

```<code>// Define manifest directives to match platform
#ifdef _UNICODE
#if defined _M_IX86
    #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_X64
    #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
    #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
#endif
</code>```

I also add the following to my projects to explictedly link to the UXTHEME.LIB which sub-classes basic controls to add theme support:

```<code>#ifdef _UXTHEME_H_
#pragma message( "Including uxtheme.lib for linking" )
#pragma comment(lib, "uxtheme.lib")
#endif
</code>```

Body:
A new MFC project will add the following to stdafx.h:

// Define manifest directives to match platform
#ifdef _UNICODE
#if defined _M_IX86
    #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_X64
    #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
    #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
#endif

I also add the following to my projects to explictedly link to the UXTHEME.LIB which sub-classes basic controls to add theme support:

#ifdef _UXTHEME_H_
#pragma message( "Including uxtheme.lib for linking" )
#pragma comment(lib, "uxtheme.lib")
#endif


问:
Timeout issue in django with nginx and gunicorn
I have few rest API,s in django that take more then one minute to get Data. Because there are more then 20 million records in database. But It show time out after one minute . How to increase timeout ?. I have searched the internet and made changes in Nginx and Gunicorn accordingly but It still show time out after one minute when i hit the API with postman.

Nginx Config file -

```<code>    location / {

proxy_set_header Host $http_host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_set_header X-Forwarded-Proto $scheme;

proxy_pass http://unix:/home/neeraj/run/gunicorn.sock;

proxy_connect_timeout 500;

proxy_read_timeout 500s;  }
</code>```

Gunicorn.service file -

```<code>ExecStart=/home/neeraj/cashvenv/bin/gunicorn --error-logfile /home/neeraj/run/gerror.log --workers 3 --timeout 500 --bind unix:/home/neeraj/run/gunicorn.sock Cash.wsgi:application
</code>```

edit nginx logs

```<code> - - [13/Feb/2022:15:49:25 +0530] "POST /reporting/dashboard/cards HTTP/1.1" 499 0 "-" "PostmanRuntime/7.28.4" "
</code>```

Please help me out with this.

答: it was the issue from AWS Side. my server had a Load Balancers attached to it in which time out was set for 60 sec .</p>

Body:
I have few rest API,s in django that take more then one minute to get Data. Because there are more then 20 million records in database. But It show time out after one minute . How to increase timeout ?. I have searched the internet and made changes in Nginx and Gunicorn accordingly but It still show time out after one minute when i hit the API with postman.

Nginx Config file -

    location / {

proxy_set_header Host $http_host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_set_header X-Forwarded-Proto $scheme;

proxy_pass http://unix:/home/neeraj/run/gunicorn.sock;

proxy_connect_timeout 500;

proxy_read_timeout 500s;  }

Gunicorn.service file -

ExecStart=/home/neeraj/cashvenv/bin/gunicorn --error-logfile /home/neeraj/run/gerror.log --workers 3 --timeout 500 --bind unix:/home/neeraj/run/gunicorn.sock Cash.wsgi:application

edit nginx logs

 - - [13/Feb/2022:15:49:25 +0530] "POST /reporting/dashboard/cards HTTP/1.1" 499 0 "-" "PostmanRuntime/7.28.4" "

Please help me out with this.


问:
How do I use fluent validation to validate an object which contains more objects of the same type?
I have a class Action which has a collection of more Action objects. Something like this:

```<code>public class Action
{
    ICollection<Action> SubActions;
}
</code>```

This basically forms a tree structure (I make sure there are no cycles). I used Fluent Validation to write a validator for this class. Here is my Validator attempt:

```<code>public class ActionValidator : AbstractValidator<Action>
{
    public ActionValidator()
    {
        RuleFor(x => x.SubActions).SetCollectionValidator(new ActionValidator());
    }
}
</code>```

Unity blows up when I try to resolve anything which depends on ActionValidator. More specifically, LINQPad crashes when it tries to resolve a service which depends on ActionValidator, presumably from a stack overflow.

There are other members in my Action class that I'm validating, but I've just put the important part for brevity. If I comment out the rule I've listed here, it works fine (except it's not validating subactions anymore).

I get the problem with my approach. I'm recursively constructing validators until something dies. But I'm just not sure how I'm to tell Fluent Validation to validate sub-objects this way.

答:
Change the rule that validates the same type to:</p>

```<code>Rulefor(x => x.SubActions).SetCollectionValidator(this);
</code>```

Body:
I have a class Action which has a collection of more Action objects. Something like this:

public class Action
{
    ICollection<Action> SubActions;
}

This basically forms a tree structure (I make sure there are no cycles). I used Fluent Validation to write a validator for this class. Here is my Validator attempt:

public class ActionValidator : AbstractValidator<Action>
{
    public ActionValidator()
    {
        RuleFor(x => x.SubActions).SetCollectionValidator(new ActionValidator());
    }
}

Unity blows up when I try to resolve anything which depends on ActionValidator. More specifically, LINQPad crashes when it tries to resolve a service which depends on ActionValidator, presumably from a stack overflow.

There are other members in my Action class that I'm validating, but I've just put the important part for brevity. If I comment out the rule I've listed here, it works fine (except it's not validating subactions anymore).

I get the problem with my approach. I'm recursively constructing validators until something dies. But I'm just not sure how I'm to tell Fluent Validation to validate sub-objects this way.

Body:
Change the rule that validates the same type to:

Rulefor(x => x.SubActions).SetCollectionValidator(this);


问:
Reading values from a key within a Directory within a List from a JSON file using Python
I've got a rather ML ugly JSON file that I'm trying to pull values from.

Below is the first entry on the list: [ {"ID":"ckzjqmtvf3ltd0z7yhogt3ttm", "DataRow ID":"ckzjq9ry03hfp0zux8xwkhkvv", "Label":{"objects": [{"featureId":"ckzjqnrn600012469dfbkfr1q", "schemaId":"ckzjqkttm3m8v0z78e7rdbkda", "color":"#1CE6FF", "title":"Weed", "value":"weed", "bbox":{"top":1003, "left":810, "height":848, "width":881}, {"featureId":"ckzjqo6iy000724690onwpxax", "schemaId":"ckzjqkttm3m8v0z78e7rdbkda", "color":"#1CE6FF", "title":"Weed", "value":"weed", "bbox"{"top":1780, "left":410, "height":264, "width":254}, {"featureId":"ckzjqobrv000a24697tc84nrr", "schemaId":"ckzjqkttm3m8v0z78e7rdbkda", "color":"#1CE6FF", "title":"Weed", "value":"weed", "bbox":{"top":1060, "left":1799, "height":471, "width":523},]

I am trying to extract the title and bbox information.

I have tried data["Label"][0]["title"], but I get:

KeyError: 0

Any help would be amazing!

答:
Problem is in data itself, because json is not properly closed. I had to remove "," and add "]". After that data.json was valid.</p>
```<code>import json

with open("data.json") as file:
    data = json.load(file)

    objects = data[0]["Label"]["objects"]
    for object in objects:
        title = object["title"]
        bbox = object["bbox"]
        print(title)
        print(bbox)
</code>```

Body:
Problem is in data itself, because json is not properly closed. I had to remove "," and add "]". After that data.json was valid.

import json

with open("data.json") as file:
    data = json.load(file)

    objects = data[0]["Label"]["objects"]
    for object in objects:
        title = object["title"]
        bbox = object["bbox"]
        print(title)
        print(bbox)


问:
how to find the length of each element in a list python? then i need to calculate how many of them have more than 5 words
```<code>def counts(lst):
    count = 0
    for elem in lst:
        if len(elem) > 5:
            count += 1
    return count

lst = []
num = int(input("How Many Elements You Need To Add: "))
for i in range(num):
    ele = input()
    lst.append(ele)

print(counts(lst))
</code>```

答:
By the looks of it , You already have the right code, Although I could not find any issue in your code as it is not formatted.

Below is a working example ( just indented code a bit )

```<code>def counts(lst):
    count = 0
    for elem in lst:
        if len(elem) > 5:
            count += 1
    return count

lst = []
num = int(input("How Many Elements You Need To Add: "))
for i in range(num):
    ele = input(f'Enter Element {i+1}:')
    lst.append(ele)

print(f"total elements greater than five : {counts(lst)}")

</code>```

You can run the code online here

Body:
By the looks of it , You already have the right code, Although I could not find any issue in your code as it is not formatted.

Below is a working example ( just indented code a bit )

def counts(lst):
    count = 0
    for elem in lst:
        if len(elem) > 5:
            count += 1
    return count

lst = []
num = int(input("How Many Elements You Need To Add: "))
for i in range(num):
    ele = input(f'Enter Element {i+1}:')
    lst.append(ele)

print(f"total elements greater than five : {counts(lst)}")

You can run the code online here


问:
Google sheet custom function return editing problem
I am trying to make a custom function in google sheet that take two argument and fill the cell from where it was called and its adjacent cell also will be fill. Adjacent cell also need to accept other value. I use

```<code>function replaceAdjacent(a,b) {
    let c=[a,b];
    return [c];
}

</code>```

This function fill both cell by provide argument but when i try edit the adjacent cell than it show  #REFerror.

How can I avoid this error with adjacent cell make editable?

答:
A cell value must be set manually or calculated by a formula, it cannot be both, that is why you get the overwrite data error.

You can call your function using a button and update the cell values using setValues(), this way you can set data manually or by calling your function.

Body:
I am trying to make a custom function in google sheet that take two argument and fill the cell from where it was called and its adjacent cell also will be fill. Adjacent cell also need to accept other value. I use

function replaceAdjacent(a,b) {
    let c=[a,b];
    return [c];
}

This function fill both cell by provide argument but when i try edit the adjacent cell than it show  #REFerror.

How can I avoid this error with adjacent cell make editable?


问:
Declaring a temperature type variable in SwiftUI
I want to create a universal converter for temperature, distance and time. In each of the sub-main views the user should be able to choose the units they want to convert and those which they want to receive. I struggle with initializing default values for the input though, getting an error:

```<code>Type 'Unit' has no member 'celsius'
</code>```

The code:

```<code>import SwiftUI
import Combine

private final class TempConverterViewState: ObservableObject {
     @Published var temperatureInput = Measurement(value: 0, unit: .celsius) }
</code>```

Can you help me initialize this variable, please or point me to some further reading?

答:
```<code>temperatureInput = Measurement(value: 0, unit: UnitTemperature.celsius)
</code>```

Body:
I want to create a universal converter for temperature, distance and time. In each of the sub-main views the user should be able to choose the units they want to convert and those which they want to receive. I struggle with initializing default values for the input though, getting an error:

Type 'Unit' has no member 'celsius'

The code:

import SwiftUI
import Combine

private final class TempConverterViewState: ObservableObject {
     @Published var temperatureInput = Measurement(value: 0, unit: .celsius) }

Can you help me initialize this variable, please or point me to some further reading?


问:
Using eslint with typescript - Unable to resolve path to module
I have this import in my file app.spec.ts:

```<code>import app from './app';
</code>```

Which causes this Typescript error

```<code>2:17  error  Unable to resolve path to module './app'  import/no-unresolved
</code>```

./app.ts does exist, but I have not compiled the .ts file into a .js file. As soon as I compile the .ts file to a .js, the error goes away.

However, since eslint is supposed to work with typescript, it should resolve modules with the .ts and not the .js.

I've also added the typescript information in my eslint config file:

```<code>"parser": "@typescript-eslint/parser",
"parserOptions": {
    "project": "./tsconfig.json"
}
</code>```

How can I config eslint in such a way that it tries to resolve modules with the .ts and not the .js?

EDIT #1

Content of app.ts:

```<code>import bodyParser from 'body-parser';
import express from 'express';
import graphqlHTTP from 'express-graphql';
import { buildSchema } from 'graphql';

const app = express();

const schema = buildSchema(`
    type Query {
        hello: String
    }
`);
const root = { hello: () => 'Hello world!' };

app.use(bodyParser());
app.use('/graphql', graphqlHTTP({
    schema,
    rootValue: root,
    graphiql: true,
}));

export default app;
</code>```

答:
My situation with ts monorepo was that I was not getting lint errors in IDE, all aliases were resolved alright, but as soon as I run eslint on one of the projects, I was getting

```<code>error  Unable to resolve path to module
</code>```

It is important to show eslint path to each of your package's tsconfig file.

To sum up and for those with TS, aliases and monorepo:

install eslint-import-resolver-typescript

add to eslintrc.js settings (this will help ide and eslint to figure aliases and stuff):

    'import/resolver': {
      node: {
        paths: 'packages/*/src',
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
      },
      typescript: {
        alwaysTryTypes: true,
        project:[
         path.resolve(__dirname, '.tsconfig.json'), // root tsconfig
         path.resolve(__dirname, './packages/projA/tsconfig.json'),
         path.resolve(__dirname, './packages/projB/tsconfig.json'),
         /* ...rest of projects path to its tsconfig */
        ],
      },
```
<ul>
<li>add to <code>eslintrc.js</code> extends:</li>
</ul>
<pre class="lang-js prettyprint-override"><code>{
 ...,
   'plugin:import/recommended',
   'plugin:import/typescript',
}

</code>```

add to eslintrc.js plugins:

  plugins: ['@typescript-eslint', ..., 'import'],
```
<ul>
<li>add to <code>eslintrc.js</code> parserOptions (same as to settings) this will help eslint:</li>
</ul>
<pre class="lang-js prettyprint-override"><code>        project: [
          path.resolve(__dirname, '.tsconfig.json'), // root tsconfig
          path.resolve(__dirname, './packages/projA/tsconfig.json'),
          path.resolve(__dirname, './packages/projB/tsconfig.json'),
          /* ...rest of projects path to its tsconfig */
        ],
</code>```

Body:
I have this import in my file app.spec.ts:

import app from './app';

Which causes this Typescript error

2:17  error  Unable to resolve path to module './app'  import/no-unresolved

./app.ts does exist, but I have not compiled the .ts file into a .js file. As soon as I compile the .ts file to a .js, the error goes away.

However, since eslint is supposed to work with typescript, it should resolve modules with the .ts and not the .js.

I've also added the typescript information in my eslint config file:

"parser": "@typescript-eslint/parser",
"parserOptions": {
    "project": "./tsconfig.json"
}

How can I config eslint in such a way that it tries to resolve modules with the .ts and not the .js?

EDIT #1

Content of app.ts:

import bodyParser from 'body-parser';
import express from 'express';
import graphqlHTTP from 'express-graphql';
import { buildSchema } from 'graphql';

const app = express();

const schema = buildSchema(`
    type Query {
        hello: String
    }
`);
const root = { hello: () => 'Hello world!' };

app.use(bodyParser());
app.use('/graphql', graphqlHTTP({
    schema,
    rootValue: root,
    graphiql: true,
}));

export default app;

Body:
My situation with ts monorepo was that I was not getting lint errors in IDE, all aliases were resolved alright, but as soon as I run eslint on one of the projects, I was getting

error  Unable to resolve path to module

It is important to show eslint path to each of your package's tsconfig file.

To sum up and for those with TS, aliases and monorepo:

install eslint-import-resolver-typescript

add to eslintrc.js settings (this will help ide and eslint to figure aliases and stuff):

    'import/resolver': {
      node: {
        paths: 'packages/*/src',
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
      },
      typescript: {
        alwaysTryTypes: true,
        project:[
         path.resolve(__dirname, '.tsconfig.json'), // root tsconfig
         path.resolve(__dirname, './packages/projA/tsconfig.json'),
         path.resolve(__dirname, './packages/projB/tsconfig.json'),
         /* ...rest of projects path to its tsconfig */
        ],
      },

add to eslintrc.js extends:

{
 ...,
   'plugin:import/recommended',
   'plugin:import/typescript',
}

add to eslintrc.js plugins:

  plugins: ['@typescript-eslint', ..., 'import'],

add to eslintrc.js parserOptions (same as to settings) this will help eslint:

        project: [
          path.resolve(__dirname, '.tsconfig.json'), // root tsconfig
          path.resolve(__dirname, './packages/projA/tsconfig.json'),
          path.resolve(__dirname, './packages/projB/tsconfig.json'),
          /* ...rest of projects path to its tsconfig */
        ],


问:
Deleting many tables when one specific table is deleted in FLASK SQLAlchemy
I have an SQLAlchemy VolunteerClient Model which is a join table:

```<code>class VolunteerClient(Base):
    __tablename__ = 'volunteer_client'

    id = Column(Integer, primary_key=True, autoincrement=True, index=True)
    volunteer_id = Column(Integer, ForeignKey('provider_user.user_id', onupdate='CASCADE', ondelete='RESTRICT'), unique=True)
    client_id = Column(Integer, ForeignKey('user.id', onupdate='CASCADE', ondelete='RESTRICT'), unique=True)
</code>```

and a VolunteerReport model:

```<code>class VolunteerReport(Base):
    __tablename__ = 'volunteer_report'

    id = Column(Integer, primary_key=True, autoincrement=True, index=True)
    volunteer_id = Column(Integer, ForeignKey('volunteer_client.volunteer_id', cascade="all, delete"))
    client_id = Column(Integer, ForeignKey('volunteer_client.client_id', cascade="all, delete"))
    report = Column(String(255), nullable=False)
    report_category = Column(String(255), nullable=False)
</code>```

If I was to delete a VolunteerClient table, which essentially unassignes a volunteer from a client but does not actually delete the users which they represent. with a specific volunteer_id and client_id set,

Example: I delete VolunteerClient table where: volunteer_id = 1, & client_id = 1,

I want any and all VolunteerReports where: volunteer_id = 1, & client_id = 1 to be deleted as well. Have I set this up correctly with the FK references to volunteer_client and the cascade='all, delete'?

Any advice would be awesome.

答:
To automatically delete child rows when a parent is deleted, you need to set ondelete='CASCADE' on the foreign key defined in the child table.  In this case, the foreign key is a composite key as it consists of volunteer_id and client_id.  This means you need a unique constraint over the columns in the parent as well.  This simplified version of your models show how it would work (I've removed the FK definitions from VolunteerClient the tables are defined in the question).

class VolunteerClient(Base):
    __tablename__ = 'volunteer_client'

    id = sa.Column(sa.Integer, primary_key=True)
    volunteer_id = sa.Column(sa.Integer)
    client_id = sa.Column(sa.Integer)

    __table_args__ = (sa.UniqueConstraint(volunteer_id, client_id),)

class VolunteerReport(Base):
    __tablename__ = 'volunteer_report'

    id = sa.Column(sa.Integer, primary_key=True)
    volunteer_id = sa.Column(sa.Integer)
    client_id = sa.Column(sa.Integer)

    __table_args__ = (
        sa.ForeignKeyConstraint(
            [volunteer_id, client_id],
            [VolunteerClient.volunteer_id, VolunteerClient.client_id],
            ondelete='CASCADE',
        ),
    )
```

You can also configure delete cascades on SQLAlchemy relationships, which give you more control over what happens when a parent row is deleted.  As you don't seem to be using relationships, and the database cascade does what you want I won't cover that in this answer.

Body:
I have an SQLAlchemy VolunteerClient Model which is a join table:

class VolunteerClient(Base):
    __tablename__ = 'volunteer_client'

    id = Column(Integer, primary_key=True, autoincrement=True, index=True)
    volunteer_id = Column(Integer, ForeignKey('provider_user.user_id', onupdate='CASCADE', ondelete='RESTRICT'), unique=True)
    client_id = Column(Integer, ForeignKey('user.id', onupdate='CASCADE', ondelete='RESTRICT'), unique=True)

and a VolunteerReport model:

class VolunteerReport(Base):
    __tablename__ = 'volunteer_report'

    id = Column(Integer, primary_key=True, autoincrement=True, index=True)
    volunteer_id = Column(Integer, ForeignKey('volunteer_client.volunteer_id', cascade="all, delete"))
    client_id = Column(Integer, ForeignKey('volunteer_client.client_id', cascade="all, delete"))
    report = Column(String(255), nullable=False)
    report_category = Column(String(255), nullable=False)

If I was to delete a VolunteerClient table, which essentially unassignes a volunteer from a client but does not actually delete the users which they represent. with a specific volunteer_id and client_id set,

Example: I delete VolunteerClient table where: volunteer_id = 1, & client_id = 1,

I want any and all VolunteerReports where: volunteer_id = 1, & client_id = 1 to be deleted as well. Have I set this up correctly with the FK references to volunteer_client and the cascade='all, delete'?

Any advice would be awesome.

Body:
To automatically delete child rows when a parent is deleted, you need to set ondelete='CASCADE' on the foreign key defined in the child table.  In this case, the foreign key is a composite key as it consists of volunteer_id and client_id.  This means you need a unique constraint over the columns in the parent as well.  This simplified version of your models show how it would work (I've removed the FK definitions from VolunteerClient the tables are defined in the question).

class VolunteerClient(Base):
    __tablename__ = 'volunteer_client'

    id = sa.Column(sa.Integer, primary_key=True)
    volunteer_id = sa.Column(sa.Integer)
    client_id = sa.Column(sa.Integer)

    __table_args__ = (sa.UniqueConstraint(volunteer_id, client_id),)

class VolunteerReport(Base):
    __tablename__ = 'volunteer_report'

    id = sa.Column(sa.Integer, primary_key=True)
    volunteer_id = sa.Column(sa.Integer)
    client_id = sa.Column(sa.Integer)

    __table_args__ = (
        sa.ForeignKeyConstraint(
            [volunteer_id, client_id],
            [VolunteerClient.volunteer_id, VolunteerClient.client_id],
            ondelete='CASCADE',
        ),
    )

You can also configure delete cascades on SQLAlchemy relationships, which give you more control over what happens when a parent row is deleted.  As you don't seem to be using relationships, and the database cascade does what you want I won't cover that in this answer.


问:
ORA-00933 sql command not properly ended ( in insert query )
I want the following query to be executed but I get an error:

```<code>insert into personal_info (case_type)
values ('unknown')
where case_description like '%normal%';
</code>```

But when I am running the following query I get no errors:

```<code>select *
from personal_info
where case_description like '%normal%';
</code>```

答:
It is not INSERT you're looking for, but UPDATE:

```<code>update personal_info set
  case_type = 'unknown'
  where case_description like '%normal%';
</code>```

If it were insert, then you'd just

```<code>insert into personal_info (case_type) values ('unknown');
</code>```

as insert - using values - can't contain a where clause.

Body:
I want the following query to be executed but I get an error:

insert into personal_info (case_type)
values ('unknown')
where case_description like '%normal%';

But when I am running the following query I get no errors:

select *
from personal_info
where case_description like '%normal%';

Body:
It is not INSERT you're looking for, but UPDATE:

update personal_info set
  case_type = 'unknown'
  where case_description like '%normal%';

If it were insert, then you'd just

insert into personal_info (case_type) values ('unknown');

as insert - using values - can't contain a where clause.


问:
margins package returning error Error in eval(model[["call"]][["data"]], env) : object '.' not found
I'm trying to use the margins package to get marginal effects of a simple linear model, but it returns the error:

```<code>Error in eval(model[["call"]][["data"]], env) : object '.' not found
</code>```

This data can be used to reproduce the problem:

```<code>forty_rows <- structure(list(wk_dist_eff_nov16 = structure(c(18, -24, -35,
-30, 18, 18, 4, -56, -41, 31, 18, -20, 36, 18, -15, 18, 35, 18,
18, -58, -52, -21, -47, 19, 18, 23, -38, 4, -50, -63, 31, -2,
-27, 2, 18, 18, -8, -12, 14, 19), class = "difftime", units = "days"),
    election_2016_11 = c(NA, NA, "0", NA, "0", "0", "1", NA,
    NA, "0", "0", NA, "1", "0", "0", "0", "1", "0", "0", NA,
    NA, "0", "0", "0", "1", "1", "1", "1", NA, NA, "0", NA, "0",
    NA, "1", "0", NA, NA, "0", "1")), class = "data.frame", row.names = c(NA,
-40L))

library(tidyverse)

model <- forty_rows %>%
             filter(!is.na(election_2016_11),
                    wk_dist_eff_nov16 %in% -36:0) %>%
    lm(as.numeric(election_2016_11) ~ as.factor(wk_dist_eff_nov16), data = .)
</code>```

Which returns kind of non-sensical values but that's just an artefact of how i've created a small reproducible example (sampling only 40 rows from a df of > 500k). I can then call tidy() on model object no problem, but margins() returns the error:

```<code>tidy(model)
# A tibble: 4 x 5
  term                            estimate std.error statistic p.value
  <chr>                              <dbl>     <dbl>     <dbl>   <dbl>
1 (Intercept)                            0       NaN       NaN     NaN
2 as.factor(wk_dist_eff_nov16)-27        0       NaN       NaN     NaN
3 as.factor(wk_dist_eff_nov16)-21        0       NaN       NaN     NaN
4 as.factor(wk_dist_eff_nov16)-15        0       NaN       NaN     NaN

library(margins)
margins(model)
Error in eval(model[["call"]][["data"]], env) : object '.' not found
</code>```

Does anyone know what's going wrong here? And how I can fix it?

答:
margins internally uses some find_data(model, parent.frame()) stuff to find the data and finds just . due to piping.

You may try to explicitly define the data which can be found in model$model.

```<code>library(dplyr)

model <- mtcars %>%
  mutate(foo='bar') %>%
  lm(mpg ~ hp, data=.)

margins(model)
# Error in eval(model[["call"]][["data"]], env) : object '.' not found

margins(model, data=model$model)
#       hp
# -0.06823
</code>```

Works with mtcars but not with your example data though.

Body:
I'm trying to use the margins package to get marginal effects of a simple linear model, but it returns the error:

Error in eval(model[["call"]][["data"]], env) : object '.' not found

This data can be used to reproduce the problem:

forty_rows <- structure(list(wk_dist_eff_nov16 = structure(c(18, -24, -35,
-30, 18, 18, 4, -56, -41, 31, 18, -20, 36, 18, -15, 18, 35, 18,
18, -58, -52, -21, -47, 19, 18, 23, -38, 4, -50, -63, 31, -2,
-27, 2, 18, 18, -8, -12, 14, 19), class = "difftime", units = "days"),
    election_2016_11 = c(NA, NA, "0", NA, "0", "0", "1", NA,
    NA, "0", "0", NA, "1", "0", "0", "0", "1", "0", "0", NA,
    NA, "0", "0", "0", "1", "1", "1", "1", NA, NA, "0", NA, "0",
    NA, "1", "0", NA, NA, "0", "1")), class = "data.frame", row.names = c(NA,
-40L))

library(tidyverse)

model <- forty_rows %>%
             filter(!is.na(election_2016_11),
                    wk_dist_eff_nov16 %in% -36:0) %>%
    lm(as.numeric(election_2016_11) ~ as.factor(wk_dist_eff_nov16), data = .)

Which returns kind of non-sensical values but that's just an artefact of how i've created a small reproducible example (sampling only 40 rows from a df of > 500k). I can then call tidy() on model object no problem, but margins() returns the error:

tidy(model)
# A tibble: 4 x 5
  term                            estimate std.error statistic p.value
  <chr>                              <dbl>     <dbl>     <dbl>   <dbl>
1 (Intercept)                            0       NaN       NaN     NaN
2 as.factor(wk_dist_eff_nov16)-27        0       NaN       NaN     NaN
3 as.factor(wk_dist_eff_nov16)-21        0       NaN       NaN     NaN
4 as.factor(wk_dist_eff_nov16)-15        0       NaN       NaN     NaN

library(margins)
margins(model)
Error in eval(model[["call"]][["data"]], env) : object '.' not found

Does anyone know what's going wrong here? And how I can fix it?

Body:
margins internally uses some find_data(model, parent.frame()) stuff to find the data and finds just . due to piping.

You may try to explicitly define the data which can be found in model$model.

library(dplyr)

model <- mtcars %>%
  mutate(foo='bar') %>%
  lm(mpg ~ hp, data=.)

margins(model)
# Error in eval(model[["call"]][["data"]], env) : object '.' not found

margins(model, data=model$model)
#       hp
# -0.06823

Works with mtcars but not with your example data though.


问:
can ping 8.8.8.8 but not google.com
I just got a new router and internet connection.
My phone and my second computer have no problem to connect to internet (wifi or cable). My first computer, where I am running Limux Mint 18.1 Serena, can connect with cable or wifi but I am unable to browser.
I can ping 8.8.8.8 but not google.com.

I do not understand much of DNS but I tried to follow some online tutorials.
I tried to modify the /etc/resolconf directory by adding a resolv.conf file with a new servername but didn't work (even after restarting network-manager). I tried as well to modify the /etc/resolv.conf.d/tail file (as read in other tutorials) by adding a new servername but still not working.

Any suggestion?

答:
The problem occurs due to trouble with DNS setting

If you are using linux follow:

Clear this file content (root permission required)
nano /etc/resolv.conf
Add the folling text:
nameserver 1.1.1.1
nameserver 8.8.8.8
Save and Reboot

If using Windows Follow:

Control Panel\Network and Internet\Network and Sharing Center
Select current active connection (wifi/broadband)
Properties > Networking > ipv4 > custom dns > 1.1.1.1 & 8.8.8.8
check Validate setting upon exit > save

Title: can ping 8.8.8.8 but not google.com