问:
FTP: I don't get to connect Ftp File with SwithYard ERROR Failed to start service SwitchYardService: host must be specified and not empty
```<code>17:16:56,767 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-7) MSC00001: Failed to start service jboss.deployment.unit."intercard-esb.jar".SwitchYardService: org.jboss.msc.service.StartException in service jboss.deployment.unit."intercard-esb.jar".SwitchYardService: org.switchyard.exception.SwitchYardException: java.lang.IllegalArgumentException: host must be specified and not empty
    at org.switchyard.as7.extension.services.SwitchYardService.start(SwitchYardService.java:85)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [rt.jar:1.7.0_45]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [rt.jar:1.7.0_45]
    at java.lang.Thread.run(Unknown Source) [rt.jar:1.7.0_45]
Caused by: org.switchyard.exception.SwitchYardException: java.lang.IllegalArgumentException: host must be specified and not empty
    at org.switchyard.component.camel.common.handler.InboundHandler.<init>(InboundHandler.java:77)
    at org.switchyard.component.camel.common.deploy.BaseBindingActivator.createInboundHandler(BaseBindingActivator.java:71)
    at org.switchyard.component.camel.common.deploy.BaseBindingActivator.activateBinding(BaseBindingActivator.java:63)
    at org.switchyard.deploy.internal.Deployment.deployServiceBindings(Deployment.java:515)
    at org.switchyard.deploy.internal.Deployment.start(Deployment.java:141)
    at org.switchyard.as7.extension.deployment.SwitchYardDeployment.start(SwitchYardDeployment.java:106)
    at org.switchyard.as7.extension.services.SwitchYardService.start(SwitchYardService.java:78)
    ... 5 more
Caused by: java.lang.IllegalArgumentException: host must be specified and not empty
    at org.apache.camel.util.ObjectHelper.notEmpty(ObjectHelper.java:319)
    at org.apache.camel.component.file.remote.RemoteFileEndpoint.afterPropertiesSet(RemoteFileEndpoint.java:119)
    at org.apache.camel.component.file.remote.RemoteFileEndpoint.createConsumer(RemoteFileEndpoint.java:86)
    at org.apache.camel.component.file.remote.RemoteFileEndpoint.createConsumer(RemoteFileEndpoint.java:34)
    at org.apache.camel.impl.EventDrivenConsumerRoute.addServices(EventDrivenConsumerRoute.java:65)
    at org.apache.camel.impl.DefaultRoute.onStartingServices(DefaultRoute.java:80)
    at org.apache.camel.impl.RouteService.warmUp(RouteService.java:133)
    at org.apache.camel.impl.DefaultCamelContext.doWarmUpRoutes(DefaultCamelContext.java:1971)
    at org.apache.camel.impl.DefaultCamelContext.safelyStartRouteServices(DefaultCamelContext.java:1899)
    at org.apache.camel.impl.DefaultCamelContext.safelyStartRouteServices(DefaultCamelContext.java:1921)
    at org.apache.camel.impl.DefaultCamelContext.startRouteService(DefaultCamelContext.java:1803)
    at org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:724)
    at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:1779)
    at org.apache.camel.impl.DefaultCamelContext.addRouteDefinitions(DefaultCamelContext.java:666)
    at org.apache.camel.impl.DefaultCamelContext.addRouteDefinition(DefaultCamelContext.java:671)
    at org.switchyard.component.camel.common.handler.InboundHandler.<init>(InboundHandler.java:75)
    ... 11 more

17:16:56,790 INFO  [org.jboss.as] (MSC service thread 1-7) JBAS015951: Admin console
17:16:56,791 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS015870: Deploy of deployment "intercard-esb.jar" was rolled back with failure message {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"intercard-esb.jar\".SwitchYardService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"intercard-esb.jar\".SwitchYardService: org.switchyard.exception.SwitchYardException: java.lang.IllegalArgumentException: host must be specified and not empty"}}
17:16:56,792 ERROR [org.jboss.as] (MSC service thread 1-7) JBAS015875: JBoss AS 7.1.1.Final "Brontes" started (with errors) in 4281ms - Started 184 of 261 services (1 services failed or missing dependencies, 76 services are passive or on-demand)
17:16:56,795 INFO  [org.jboss.weld.deployer] (MSC service thread 1-8) JBAS016009: Stopping weld service for deployment intercard-esb.jar
17:16:56,806 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015877: Stopped deployment intercard-esb.jar in 13ms
17:16:56,808 INFO  [org.jboss.as.controller] (DeploymentScanner-threads - 2) JBAS014774: Service status report
JBAS014777:   Services which failed to start:      service jboss.deployment.unit."intercard-esb.jar".SwitchYardService: org.jboss.msc.service.StartException in service jboss.deployment.unit."intercard-esb.jar".SwitchYardService: org.switchyard.exception.SwitchYardException: java.lang.IllegalArgumentException: host must be specified and not empty

17:16:56,812 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-2" => {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"intercard-esb.jar\".SwitchYardService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"intercard-esb.jar\".SwitchYardService: org.switchyard.exception.SwitchYardException: java.lang.IllegalArgumentException: host must be specified and not empty"}}}}
</code>```

答:
This specific problem might be due to multiple reasons.
Please check end point very carefully that there is no trailing space

sftp://my.host.com:22 /sftpdirectory  (There is space between port 22 and /sftpdirectory, please remove the sapce)
or
sftp://my.host.com :22/sftpdirectory (There is space between my.host.com and port 22 , please remove the sapce)

The possibility of having the above space due to trailing space in the value of configured property


来源: stackexchange

问:
How to update values into appsetting.json?
I am using the IOptions pattern as described in the official documentation.

This works fine when I am reading values from appsetting.json, but how do I update values and save changes back to appsetting.json?

In my case, I have a few fields that can be edited from the user interface (by admin user in application). Hence I am looking for the ideal approach to update these values via the option accessor.

答:
While there is still not a way via the Options accessor, I'd like to preset a .NET 6 class that makes it quite easy to write back to the file. You can use the JsonNode class in the System.Text.Json.Nodes class. I'm using it to write back an encrypted connection string after reading a plain text one from appsettings.json.

There are examples of using Newtonsoft.Json.JsonConvert.DeserializeObject and deserializing into a dynamic type like @Alper suggested - but System.Text.Json could not do that. Well, now you sort of can :) (though not with a dynamic type).

In my example below, I tried to be minimalistic and simple. I used JsonNode to retrieve the value instead of a Dependency Injected IConfiguration. In a real web application, I'd be using the DI method. It really doesn't matter how you retrieve the setting, writing it back still means reconstructing the Json and updating the file on disk.

MS Link for JsonNode: https://learn.microsoft.com/en-us/dotnet/api/system.text.json.nodes.jsonnode?view=net-6.0

My appsettings.json sample:

{
  "sampleSection": {
    "someStringSetting": "Value One",
    "deeperValues": {
      "someIntSetting": 23,
      "someBooleanSetting": true
    }
  }
}
```
<p>C# .NET 6 console application:</p>
<pre class="lang-cs prettyprint-override"><code>using System.Text.Json;
using System.Text.Json.Nodes;

const string AppSettingsPath = @"<PathToYourAppSettings.JsonFile>>\appsettings.json";
string appSettingsJson = File.ReadAllText(AppSettingsPath);
var jsonNodeOptions = new JsonNodeOptions { PropertyNameCaseInsensitive = true };
var node = JsonNode.Parse(appSettingsJson, jsonNodeOptions);

var options = new JsonSerializerOptions { WriteIndented = true };
Console.WriteLine("===========  Before ============");
Console.WriteLine(node.ToJsonString(options));

// Now you have access to all the structure using node["blah"] syntax
var stringSetting = (string) node["sampleSection"]["someStringSetting"];
var intSetting = (int) node["sampleSection"]["deeperValues"]["someIntSetting"];
var booleanSetting = (bool) node["sampleSection"]["deeperValues"]["someBooleanSetting"];

Console.WriteLine($"stringSetting: {stringSetting}, intSetting: {intSetting}, booleanSetting: {booleanSetting}");

// Now write new values back
node["sampleSection"]["someStringSetting"] = $"New setting at {DateTimeOffset.Now}";
node["sampleSection"]["deeperValues"]["someIntSetting"] = -6;
node["sampleSection"]["deeperValues"]["someBooleanSetting"] = false;

Console.WriteLine("===========  After ============");
Console.WriteLine(node.ToJsonString(options));

// Or, to actually write it to disk:
// File.WriteAllText(AppSettingsPath, node.ToJsonString(options));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
While there is still not a way via the Options accessor, I'd like to preset a .NET 6 class that makes it quite easy to write back to the file. You can use the JsonNode class in the System.Text.Json.Nodes class. I'm using it to write back an encrypted connection string after reading a plain text one from appsettings.json.

There are examples of using Newtonsoft.Json.JsonConvert.DeserializeObject and deserializing into a dynamic type like @Alper suggested - but System.Text.Json could not do that. Well, now you sort of can :) (though not with a dynamic type).

In my example below, I tried to be minimalistic and simple. I used JsonNode to retrieve the value instead of a Dependency Injected IConfiguration. In a real web application, I'd be using the DI method. It really doesn't matter how you retrieve the setting, writing it back still means reconstructing the Json and updating the file on disk.

MS Link for JsonNode: https://learn.microsoft.com/en-us/dotnet/api/system.text.json.nodes.jsonnode?view=net-6.0

My appsettings.json sample:

{
  "sampleSection": {
    "someStringSetting": "Value One",
    "deeperValues": {
      "someIntSetting": 23,
      "someBooleanSetting": true
    }
  }
}

C# .NET 6 console application:

using System.Text.Json;
using System.Text.Json.Nodes;

const string AppSettingsPath = @"<PathToYourAppSettings.JsonFile>>\appsettings.json";
string appSettingsJson = File.ReadAllText(AppSettingsPath);
var jsonNodeOptions = new JsonNodeOptions { PropertyNameCaseInsensitive = true };
var node = JsonNode.Parse(appSettingsJson, jsonNodeOptions);

var options = new JsonSerializerOptions { WriteIndented = true };
Console.WriteLine("===========  Before ============");
Console.WriteLine(node.ToJsonString(options));

// Now you have access to all the structure using node["blah"] syntax
var stringSetting = (string) node["sampleSection"]["someStringSetting"];
var intSetting = (int) node["sampleSection"]["deeperValues"]["someIntSetting"];
var booleanSetting = (bool) node["sampleSection"]["deeperValues"]["someBooleanSetting"];

Console.WriteLine($"stringSetting: {stringSetting}, intSetting: {intSetting}, booleanSetting: {booleanSetting}");

// Now write new values back
node["sampleSection"]["someStringSetting"] = $"New setting at {DateTimeOffset.Now}";
node["sampleSection"]["deeperValues"]["someIntSetting"] = -6;
node["sampleSection"]["deeperValues"]["someBooleanSetting"] = false;

Console.WriteLine("===========  After ============");
Console.WriteLine(node.ToJsonString(options));

// Or, to actually write it to disk:
// File.WriteAllText(AppSettingsPath, node.ToJsonString(options));

ContentLicense: CC BY-SA 4.0


问:
Call JavaScript function while the asp:LinkButton been clicked
Just wondering, could it be possible call a JavaScript under asp:LinkButton while it been clicked.

Example:
I have the following code that I would like it to be calling a JavaScript function (test()), when it been clicked. How could I do it?

```<code>    <asp:ListView ID="lvTest" runat="server" DataSourceID="dsTest" DataKeyNames="TestID"
    OnItemCommand="lvTest_ItemCommand">
    <LayoutTemplate>
      <ul style="color:#fe8113;">
        <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
      </ul>
    </LayoutTemplate>
    <ItemTemplate>
      <li>
        <asp:LinkButton runat="server" CausesValidation="true" CommandName="" CssClass="orange"
          Text='<%# Eval("TestName")%>'/>
      </li>
    </ItemTemplate>
  </asp:ListView>
</code>```

答: Adding the onclientclick="JsFunctionNameHere()" to the <asp:LinkButton> worked like a charm for me.

Body:
Just wondering, could it be possible call a JavaScript under asp:LinkButton while it been clicked.

Example:
I have the following code that I would like it to be calling a JavaScript function (test()), when it been clicked. How could I do it?

    <asp:ListView ID="lvTest" runat="server" DataSourceID="dsTest" DataKeyNames="TestID"
    OnItemCommand="lvTest_ItemCommand">
    <LayoutTemplate>

        <asp:PlaceHolder ID="itemPlaceholder" runat="server" />

    </LayoutTemplate>
    <ItemTemplate>

        <asp:LinkButton runat="server" CausesValidation="true" CommandName="" CssClass="orange"
          Text='<%# Eval("TestName")%>'/>

    </ItemTemplate>
  </asp:ListView>


问:
How do I restrict a remote desktop user to a single application on Windows Server 2016?
I have an AWS Lightsail server based on the Windows Server 2016 blueprint. I would like to have users log in via remote desktop, and be limited to using just one designated application, and have no access to the desktop or other features (including the File Explorer).

I tried setting up a group policy, both for the server (Computer Configuration) and users (User Configuration) under Administrative Templates -> Windows Components -> Remote Desktop Services -> Remote Desktop Session Host -> Remote Session Environment, and I enabled and configured Start a program on connection. That did not work.

I also tried the suggestions found at the following link:
Can RDP clients launch remote applications and not desktops

including setting the following dword value in the server's registry:

```<code>[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services]
"fAllowUnlistedRemotePrograms"=dword:00000001
</code>```

I also included the alternate shell and remoteapplication entries in an .RDP file, and pointed to that file in the user's Remote Desktop Services Profile tab of the user's Properties dialog.

None of that worked. Each time I logged in as the user, the configured application did not run and I had access to the desktop.

Nothing that I found in my Google searches worked either.

Can someone please point me in the right direction. I am pretty sure that what I am trying to do is possible, but I am stuck.

I am connecting to the server using the remote desktop client in Windows 10 Pro, though I am not sure that that has anything to do with the failure. I'll also note that once I log into the server using remote desktop I can successfully run the application from the File Explorer or cmd prompt.

答:
Thank you for this Guide Cary.

I just ran into an Issue where I had to Start an Application that requires the existence of the Taskbar while Loading.

After a few trial and error-run's I got to the following solution, if the Taskbar is not required anymore after Start as it seems it is not in my Case. I don't even know why this Application needs it. There isn't any Icon placed in it or what so ever...

Here is my little CMD

```<code>@echo off
start explorer.exe
start AvERP.exe
timeout /T 2
taskkill /f /im explorer.exe
</code>```

And to Krunoslav Djakovic

I created an Sub-Folder for the OrganizationalUnit where i did put the Policy and only moved the User one level deeper in to that Folder. Maybe this helps in resolving your Problem.

Body:
I have an AWS Lightsail server based on the Windows Server 2016 blueprint. I would like to have users log in via remote desktop, and be limited to using just one designated application, and have no access to the desktop or other features (including the File Explorer).

I tried setting up a group policy, both for the server (Computer Configuration) and users (User Configuration) under Administrative Templates -> Windows Components -> Remote Desktop Services -> Remote Desktop Session Host -> Remote Session Environment, and I enabled and configured Start a program on connection. That did not work.

I also tried the suggestions found at the following link:
Can RDP clients launch remote applications and not desktops

including setting the following dword value in the server's registry:

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services]
"fAllowUnlistedRemotePrograms"=dword:00000001

I also included the alternate shell and remoteapplication entries in an .RDP file, and pointed to that file in the user's Remote Desktop Services Profile tab of the user's Properties dialog.

None of that worked. Each time I logged in as the user, the configured application did not run and I had access to the desktop.

Nothing that I found in my Google searches worked either.

Can someone please point me in the right direction. I am pretty sure that what I am trying to do is possible, but I am stuck.

I am connecting to the server using the remote desktop client in Windows 10 Pro, though I am not sure that that has anything to do with the failure. I'll also note that once I log into the server using remote desktop I can successfully run the application from the File Explorer or cmd prompt.

Body:
Thank you for this Guide Cary.

I just ran into an Issue where I had to Start an Application that requires the existence of the Taskbar while Loading.

After a few trial and error-run's I got to the following solution, if the Taskbar is not required anymore after Start as it seems it is not in my Case. I don't even know why this Application needs it. There isn't any Icon placed in it or what so ever...

Here is my little CMD

@echo off
start explorer.exe
start AvERP.exe
timeout /T 2
taskkill /f /im explorer.exe

And to Krunoslav Djakovic

I created an Sub-Folder for the OrganizationalUnit where i did put the Policy and only moved the User one level deeper in to that Folder. Maybe this helps in resolving your Problem.


问:
pyqt5 gui freez while process in python
```<code>from PyQt5 import QtCore, QtGui, QtWidgets
import wget

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(353, 111)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(10, 16, 251, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(270, 10, 75, 31))
        self.pushButton.setObjectName("pushButton")
        self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget)
        self.textBrowser.setGeometry(QtCore.QRect(10, 50, 331, 31))
        self.textBrowser.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.textBrowser.setObjectName("textBrowser")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 353, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)

        self.pushButton.clicked.connect(self.download)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Download"))
        self.textBrowser.setPlaceholderText(_translate("MainWindow", " Download progress!"))

    def download(self):
        url= self.lineEdit.text()
        print(url)

        while True:
            try:
                wget.download(url)
                break
            except:
                ...

        print(">>> Download completed!")

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
</code>```

答:
Your download method keeps running as long as the downloads are in progress.

However, since it is a callback connected to the GUI, it is basically called from within the event loop.
So as long as it runs, it interrupts the flow of events. Hence the application freezing.

There are basically three solutions;

Chop the download up into small pieces that can don't interrupt the event loop too long.

Do the downloading in a separate thread.

Do the downloading in s separate process.

I gather that qt has specialized classes for all of these, but I'm not familiar with qt.

Title: pyqt5 gui freez while process in python


问:
Prisma many-to-many relations: create and connect
In my Prisma schema, I have a many-to-many relationship between posts and categories. I've added @map options to match the Postgres snake_case naming convention:

```<code>model Post {
  id         Int            @id @default(autoincrement())
  title      String
  body       String?
  categories PostCategory[]

  @@map("post")
}

model Category {
  id    Int            @id @default(autoincrement())
  name  String
  posts PostCategory[]

  @@map("category")
}

model PostCategory {
  categoryId Int      @map("category_id")
  postId     Int      @map("post_id")
  category   Category @relation(fields: [categoryId], references: [id])
  post       Post     @relation(fields: [postId], references: [id])

  @@id([categoryId, postId])
  @@map("post_category")
}
</code>```

I'm trying to create a post with multiple categories at the same time. If a category exists, I'd like to connect the category to the post. If the category doesn't exist, I'd like to create it. The creation part is working well, but the connection part is problematic:

```<code>  await prisma.post.create({
    data: {
      title: 'Hello',
      categories: {
        create: [{ category: { create: { name: 'News' } } }],
        connect: {
          categoryId_postId: { categoryId: 1, postId: ? }, // This doesn't work, even if I had the postId
        },
      },
    },
  });
</code>```

How can I connect an existing category to a new post with the schema that I have?

答:
Explicit many-to-many create/update existing tags read more here

let args =[1,2,3,4]
tags: {
      create: args.tags?.map(tagId=>({
          tag:{
              connect:{
                  id:tagId
              }
          }
      }))
    },
 }```

Body:
In my Prisma schema, I have a many-to-many relationship between posts and categories. I've added @map options to match the Postgres snake_case naming convention:

model Post {
  id         Int            @id @default(autoincrement())
  title      String
  body       String?
  categories PostCategory[]

  @@map("post")
}

model Category {
  id    Int            @id @default(autoincrement())
  name  String
  posts PostCategory[]

  @@map("category")
}

model PostCategory {
  categoryId Int      @map("category_id")
  postId     Int      @map("post_id")
  category   Category @relation(fields: [categoryId], references: [id])
  post       Post     @relation(fields: [postId], references: [id])

  @@id([categoryId, postId])
  @@map("post_category")
}

I'm trying to create a post with multiple categories at the same time. If a category exists, I'd like to connect the category to the post. If the category doesn't exist, I'd like to create it. The creation part is working well, but the connection part is problematic:

  await prisma.post.create({
    data: {
      title: 'Hello',
      categories: {
        create: [{ category: { create: { name: 'News' } } }],
        connect: {
          categoryId_postId: { categoryId: 1, postId: ? }, // This doesn't work, even if I had the postId
        },
      },
    },
  });

How can I connect an existing category to a new post with the schema that I have?


问:
JdbcSQLIntegrityConstraintViolationException when inserting new entry after schema generated from class and initial data loaded from file
I have a spring boot project with an h2 database.

I have an entity class from which the schema is to be generated:

```<code>@NoArgsConstructor
@Entity
@Table(name = "NAMES")
public class Name {

    @Id
    @GeneratedValue
    public Long id;

    @Column(nullable = false)
    public String name;

    public Name(String name) {
        this.name = name;
    }

}
</code>```

And I have a data.sql file:

```<code>insert into names (id, name) values (1, 'Alex');
insert into names (id, name) values (2, 'Bob');
</code>```

my application.properties is:

```<code>spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.defer-datasource-initialization=true
spring.jpa.show-sql=true
</code>```

The application starts up just fine, I can confirm with localhost:8080/h2-console that the data is loaded into the database.
But I cannot save new data into the table with

```<code>//public interface NameRepository extends CrudRepository<Name,Long> {}

@RestController
@Service
public class MyController {

  @Autowired
  private final NameRepository nameRepository;

  @PostMapping("/triggerError")
  public ResponseEntity<Void> trigger() {

    Name newName = new Name("Chris");
    nameRepository.save(newName);
    return ResponseEntity.ok().build();
  }
}
</code>```

The error message is:

```<code>could not execute statement; SQL [n/a]; constraint [\"PRIMARY KEY ON PUBLIC.NAMES(ID) ( /* key:1 */ CAST(1 AS BIGINT), 'Alex')\"; SQL statement:
insert into names (name, id) values (?, ?) [23505-210]];
</code>```

I assume that this means that spring wants to insert the new name at id=1, not realizing that ids 1 and 2 are already in use. I guess the right parameters to @GeneratedValue could fix it but I do not understand what they mean and which one to choose.

Trial and error:

@GeneratedValue(strategy = GenerationType.AUTO) is the default, see above.

@GeneratedValue(strategy = GenerationType.TABLE) same error

@GeneratedValue(strategy = GenerationType.SEQUENCE) same error

@GeneratedValue(strategy = GenerationType.IDENTITY) different error:

```<code>...
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column \"ID\"; SQL statement:\ninsert into names (id, name) values (null, ?) [23502-210]
...
could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
</code>```

So apparently it is not the annotation, but something else.

I'm giving up, heres my MRE: https://github.com/timo-a/duckpond-spring-backend/tree/debug/saving

答:
@Shankar Ghimire is partially correct. This is both a Hibernate bug and a data.sql issue. Update your Hibernate version to 5.6.5:

```<code>implementation('org.springframework.boot:spring-boot-starter-data-jpa'){
  exclude group: 'org.hibernate', module: 'hibernate-core'
}
implementation 'org.hibernate:hibernate-core:5.6.5.Final'
</code>```

and since you are using the h2 auto_increment, you should remove the id in your data.sql

insert into names (name)
values ('Alex'),('Bob');
```
<p>The sequence won't increment otherwise leading to Unique index or primary key violation.</p>
<hr />
<p>By the way, your repository uses Integer as your PK whereas your entity uses Long. And since the question is tagged as JPA, use :</p>
```public interface NameRepository extends JpaRepository<Name,Long> {}
```

And you insert data in a table named "scores" but I assume it's a typo.

Body:
I have a spring boot project with an h2 database.

I have an entity class from which the schema is to be generated:

@NoArgsConstructor
@Entity
@Table(name = "NAMES")
public class Name {

    @Id
    @GeneratedValue
    public Long id;

    @Column(nullable = false)
    public String name;

    public Name(String name) {
        this.name = name;
    }

}

And I have a data.sql file:

insert into names (id, name) values (1, 'Alex');
insert into names (id, name) values (2, 'Bob');

my application.properties is:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.defer-datasource-initialization=true
spring.jpa.show-sql=true

The application starts up just fine, I can confirm with localhost:8080/h2-console that the data is loaded into the database.
But I cannot save new data into the table with

//public interface NameRepository extends CrudRepository<Name,Long> {}

@RestController
@Service
public class MyController {

  @Autowired
  private final NameRepository nameRepository;

  @PostMapping("/triggerError")
  public ResponseEntity<Void> trigger() {

    Name newName = new Name("Chris");
    nameRepository.save(newName);
    return ResponseEntity.ok().build();
  }
}

The error message is:

could not execute statement; SQL [n/a]; constraint [\"PRIMARY KEY ON PUBLIC.NAMES(ID) ( /* key:1 */ CAST(1 AS BIGINT), 'Alex')\"; SQL statement:
insert into names (name, id) values (?, ?) [23505-210]];

I assume that this means that spring wants to insert the new name at id=1, not realizing that ids 1 and 2 are already in use. I guess the right parameters to @GeneratedValue could fix it but I do not understand what they mean and which one to choose.

Trial and error:

@GeneratedValue(strategy = GenerationType.AUTO) is the default, see above.

@GeneratedValue(strategy = GenerationType.TABLE) same error

@GeneratedValue(strategy = GenerationType.SEQUENCE) same error

@GeneratedValue(strategy = GenerationType.IDENTITY) different error:

...
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column \"ID\"; SQL statement:\ninsert into names (id, name) values (null, ?) [23502-210]
...
could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

So apparently it is not the annotation, but something else.

I'm giving up, heres my MRE: https://github.com/timo-a/duckpond-spring-backend/tree/debug/saving

Body:
@Shankar Ghimire is partially correct. This is both a Hibernate bug and a data.sql issue. Update your Hibernate version to 5.6.5:

implementation('org.springframework.boot:spring-boot-starter-data-jpa'){
  exclude group: 'org.hibernate', module: 'hibernate-core'
}
implementation 'org.hibernate:hibernate-core:5.6.5.Final'

and since you are using the h2 auto_increment, you should remove the id in your data.sql

insert into names (name)
values ('Alex'),('Bob');

The sequence won't increment otherwise leading to Unique index or primary key violation.

By the way, your repository uses Integer as your PK whereas your entity uses Long. And since the question is tagged as JPA, use :

public interface NameRepository extends JpaRepository<Name,Long> {}

And you insert data in a table named "scores" but I assume it's a typo.


问:
Can we change the name of testng.xml to some other name? Instead of testng.xml can I make it like myproject.xml?
In my test automation project we are dynamically creating xml file for running tests. but im not able to find testng.xml file instead I got something like myproject.xml which looks like a testng.xml. Is it possible to create a testng.xml in different name? or am I referring to a wrong file?</p>

答: Yes, the testng.xml file can be renamed as anything, as long as the .xml extension is present and you keep consistency with the new name all through the project. For example, when I do cross-browser testing using TestNG, I rename the file as crossbrowser.xml. That way, anyone reading through the code will know right away the purpose of the file, as the name suggests. I find the name testng.xml is too generic for my liking.


问:
I keep getting a blank screen in React.JS
I was following a tutorial and my localhost is completely blank after importing {Link} from react-router-dom. Followed word for word but my local host is blank as soon as I added link in navbar.js.

```<code>import React from 'react';
import {Link} from 'react-router-dom';

function Navbar() {
    return(
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
                <div class="container-fluid">

                <Link to="/" class="navbar-brand">SkyCloud</Link>

                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-togglser-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
                    <li class="nav-item">
                        <Link to="/" class="nav-link active">Home</Link>
                    </li>

                    <li class="nav-item">
                    <Link to="/about" class="nav-link active">About</Link>
                    </li>

                    <li class="nav-item">
                    <Link to="/contact" class="nav-link active">Contact</Link>
                    </li>

                    </ul>

                </div>
                </div>
      </nav>

    );

}

export default Navbar;
</code>```

And this is my App.js file...

```<code>import React from 'react';
import Navbar from './components/inc/Navbar';
import Home from './components/pages/Home';
import About from './components/pages/About';
import Contact from './components/pages/Contact';
import {BrowserRouter as Router} from 'react-router-dom';

function App() {
  return (

    <Router>
    <div>
     <Navbar/>
    <Home/>
   <About/>
   <Contact/>

    </div>
    </Router>

  );
}

export default App;
</code>```

答:
You should import Routes and Route too from "react-router-dom";

then your code will become

```<code>import React from 'react';
import Navbar from './components/inc/Navbar';
import Home from './components/pages/Home';
import About from './components/pages/About';
import Contact from './components/pages/Contact';
import {Routes,Route ,BrowserRouter as Router} from 'react-router-dom';

function App() {
  return (

<Router>
 <div>
 <Navbar/>
    <Routes>
        <Route exact path="/" element={<Home/>}>
        <Route path="/about" element={ <About/>}>
        <Route path="/contact" element={ <Contact/>} />
    </Routes>
 </div>
</Router>

  );
</code>```

Body:
I was following a tutorial and my localhost is completely blank after importing {Link} from react-router-dom. Followed word for word but my local host is blank as soon as I added link in navbar.js.

import React from 'react';
import {Link} from 'react-router-dom';

function Navbar() {
    return(

                <Link to="/" class="navbar-brand">SkyCloud</Link>

                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                        <Link to="/" class="nav-link active">Home</Link>

                    <Link to="/about" class="nav-link active">About</Link>

                    <Link to="/contact" class="nav-link active">Contact</Link>

    );

}

export default Navbar;

And this is my App.js file...

import React from 'react';
import Navbar from './components/inc/Navbar';
import Home from './components/pages/Home';
import About from './components/pages/About';
import Contact from './components/pages/Contact';
import {BrowserRouter as Router} from 'react-router-dom';

function App() {
  return (

    <Router>

     <Navbar/>
    <Home/>
   <About/>
   <Contact/>

    </Router>

  );
}

export default App;

Body:
You should import Routes and Route too from "react-router-dom";

then your code will become

import React from 'react';
import Navbar from './components/inc/Navbar';
import Home from './components/pages/Home';
import About from './components/pages/About';
import Contact from './components/pages/Contact';
import {Routes,Route ,BrowserRouter as Router} from 'react-router-dom';

function App() {
  return (

<Router>
 <div>
 <Navbar/>
    <Routes>
        <Route exact path="/" element={<Home/>}>
        <Route path="/about" element={ <About/>}>
        <Route path="/contact" element={ <Contact/>} />
    </Routes>
 </div>
</Router>

  );


问:
Packer won't create image on GCloud
I've been using the tools from HashiCorp (Packer and Terraform) to create images and then build VMs by using Jenkins on AWS. Now I have a project that is on GCloud and I have successfully configured Terraform to create a VM but when I try to run packer I get the following error
root@packer packer]# packer build createImage.json

```<code>googlecompute output will be in this color.

==> googlecompute: Checking image does not exist...
==> googlecompute: Creating temporary SSH key for instance...
==> googlecompute: Error getting source image for instance creation: Could not find image, centos-7, in projects, [<PROJECT_ID> centos-cloud coreos-cloud debian-cloud google-containers opensuse-cloud rhel-cloud suse-cloud ubuntu-os-cloud windows-cloud gce-nvme]: 11 error(s) occurred:
==> googlecompute:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
Build 'googlecompute' errored: Error getting source image for instance creation: Could not find image, centos-7, in projects, [PROJECT_ID centos-cloud coreos-cloud debian-cloud google-containers opensuse-cloud rhel-cloud suse-cloud ubuntu-os-cloud windows-cloud gce-nvme]: 11 error(s) occurred:

* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:

==> Some builds didn't complete successfully and had errors:
--> googlecompute: Error getting source image for instance creation: Could not find image, centos-7, in projects, [PROJECT_ID centos-cloud coreos-cloud debian-cloud google-containers opensuse-cloud rhel-cloud suse-cloud ubuntu-os-cloud windows-cloud gce-nvme]: 11 error(s) occurred:

* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:

==> Builds finished but no artifacts were created.
</code>```

This is my createImage.json

```<code>{
 "variables": {
    "project_id": "PROJECT_ID"
  },
 "builders": [
    {
      "type": "googlecompute",
      "region": "europe-west1",
      "zone": "europe-west1-b",
      "project_id": "{{user `project_id`}}",
      "source_image_family": "centos-7",
      "image_name": "My-Test-Image",
      "disk_size": 10,
      "machine_type": "f1-micro",
      "ssh_username": "centos"
    }
  ]
}
</code>```

I should mention that the service account that I am using is even given a owner permission just to be sure that I have no issues with the permissions.
Does anybody has any idea why I have this issue while on AWS it works great.

答:
Can you list the available images on GCloud and use this information for your json configuration file:</p>
```<code>gcloud compute images list --filter centos
</code>```

Title: Packer won't create image on GCloud

Body:
I've been using the tools from HashiCorp (Packer and Terraform) to create images and then build VMs by using Jenkins on AWS. Now I have a project that is on GCloud and I have successfully configured Terraform to create a VM but when I try to run packer I get the following error
root@packer packer]# packer build createImage.json

googlecompute output will be in this color.

==> googlecompute: Checking image does not exist...
==> googlecompute: Creating temporary SSH key for instance...
==> googlecompute: Error getting source image for instance creation: Could not find image, centos-7, in projects, [<PROJECT_ID> centos-cloud coreos-cloud debian-cloud google-containers opensuse-cloud rhel-cloud suse-cloud ubuntu-os-cloud windows-cloud gce-nvme]: 11 error(s) occurred:
==> googlecompute:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
==> googlecompute: * googleapi: got HTTP response code 400 with body:
Build 'googlecompute' errored: Error getting source image for instance creation: Could not find image, centos-7, in projects, [PROJECT_ID centos-cloud coreos-cloud debian-cloud google-containers opensuse-cloud rhel-cloud suse-cloud ubuntu-os-cloud windows-cloud gce-nvme]: 11 error(s) occurred:

* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:

==> Some builds didn't complete successfully and had errors:
--> googlecompute: Error getting source image for instance creation: Could not find image, centos-7, in projects, [PROJECT_ID centos-cloud coreos-cloud debian-cloud google-containers opensuse-cloud rhel-cloud suse-cloud ubuntu-os-cloud windows-cloud gce-nvme]: 11 error(s) occurred:

* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:
* googleapi: got HTTP response code 400 with body:

==> Builds finished but no artifacts were created.

This is my createImage.json

{
 "variables": {
    "project_id": "PROJECT_ID"
  },
 "builders": [
    {
      "type": "googlecompute",
      "region": "europe-west1",
      "zone": "europe-west1-b",
      "project_id": "{{user `project_id`}}",
      "source_image_family": "centos-7",
      "image_name": "My-Test-Image",
      "disk_size": 10,
      "machine_type": "f1-micro",
      "ssh_username": "centos"
    }
  ]
}

I should mention that the service account that I am using is even given a owner permission just to be sure that I have no issues with the permissions.
Does anybody has any idea why I have this issue while on AWS it works great.

Body:
Can you list the available images on GCloud and use this information for your json configuration file:

gcloud compute images list --filter centos


问:
How do I sort array by numbers and also prevent it from increasing more then 15 length and take only the biggest numbers?
here is my code for now:

```<code>router.get('/questions/best', function(req,res,next){
  Question.find({}).exec(function(err,results){
    if (err){return next(err)}
    let top15 = [];
    for(let i = 0; i< results.length; i++){
      let dislikestouse = results[i].dislikes[0]
      let ratio  = 0
      if(dislikestouse > 0){
        ratio = results[i].likes[0]/dislikestouse
      }
      else{
        ratio = results[i].likes[0]/1
      }

    }
    res.render('content', { whichOne: 5, user: req.user, questions: top15 });
  })
});
</code>```

results is every question in the database, and top15 is supposed to be only the ones displayed since they have the highest ratio and rendered into the template.
I tried using if statements to prevent it dividing by 0 since it results in an error.

how do I sort every result by finding if it is bigger then any of the items in top15 and then placing it in the right place if it is? I use pure JavaScript.
to access the numbers of a result's dislikes and likes search for the first item since it where I store the length, like a typical likes array is: [2,'username1', 'username2'].
here is the scheme for a question:

```<code>const Question = mongoose.model(
  "Question",
  new Schema({
    title: { type: String, required: true },
    text: { type: String },
    authorUsername: { type: String, required: true },
    dateCreated: {},
    answers: { type: Array, required: true },
    likes: { type: Array, required: true },
    dislikes: { type: Array, required: true },
    tag: { type: String, required: true },
    views: {type: Array, required:true},
  })
);
</code>```

here is an example of a question:

```<code>_id:620935985f6865b4e85c333d
title:"How do i make a lemon?"
text:"yeet"
authorUsername:"SweetWhite"
dateCreated:2022-02-13T16:45:12.598+00:00
answers:
Array
likes:
Array
0:1
1:"SweetWhite"
dislikes:
Array
0:0
tag:
"Social"
views:
Array
0:1
1:"SweetWhite"
__v:0
</code>```

Thanks!

答:
The answer above is a superb pure Javascript solution.
However, it might be the case that we do not want to drag 1000s or possibly more of items out of the database just to sort and pick 15 on the client side.  Given a set of docs like this:

var r =   [
    {likes: ['A','A'], dislikes: ['A','A']},
    {likes: ['A','A']},
    {dislikes: ['A','A']},
    {likes: ['A','A','A','A','A'], dislikes: ['A','A']},
    {likes: ['A','A','A','A','A','A','A','A','A'], dislikes: ['A','A']},
    {likes: ['A','A','A','A','A','A','A','A'], dislikes: ['A','A']},
    {likes: ['A','A','A','A','A','A','A'], dislikes: ['A','A']},
    {likes: ['A'], dislikes: ['A','A']}
];
```
<p>Then here is an aggregation that will drive the sort and "slice" logic into the DB:</p>
<pre class="lang-js prettyprint-override"><code>db.foo.aggregate([
    // Protect against missing fields with $ifNull
    // Protect against division by zero dislikes using max[1,size]
    {$addFields: {ratio: {$divide:[{$size:{$ifNull:["$likes",[]]}},
                                 {$max:[1,{$size:{$ifNull:["$dislikes",[]]}}]}
                                ]}
               }},
    {$sort: {ratio:-1}},
    {$limit: 3}  // change to 15 for the real dataset
]);
</code>```

If we must accomodate the "run length encoding" nature of the arrays e.g. [2, 'user1', 'user2'] then the agg is very similar only using $arrayElemAt to grab array[0] instead of using $size:

var r =   [
    {likes: [2, 'A','A'], dislikes: [2, 'A','A']},
    {likes: [2, 'A','A']},
    {dislikes: [2, 'A','A']},
    {likes: [5, 'A','A','A','A','A'], dislikes: [2, 'A','A']},
    {likes: [9, 'A','A','A','A','A','A','A','A','A'], dislikes: [2, 'A','A']},
    {likes: [8, 'A','A','A','A','A','A','A','A'], dislikes: [2, 'A','A']},
    {likes: [7, 'A','A','A','A','A','A','A'], dislikes: [2, 'A','A']},
    {likes: [1, 'A'], dislikes: [2, 'A','A']}
];

db.foo.aggregate([
    // Protect against missing fields with $ifNull but this time it is not
    // an empty array [] but rather an array of one elem, the length, which
    // is 0:
    {$project: {ratio: {$divide:[
        {$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},
        {$max:[1, {$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]}]}
        ]}
    }},
    {$sort: {ratio:-1}},
    {$limit: 3}
]);

{ "_id" : 4, "ratio" : 4.5 }
{ "_id" : 5, "ratio" : 4 }
{ "_id" : 6, "ratio" : 3.5 }

```

Body:
here is my code for now:

router.get('/questions/best', function(req,res,next){
  Question.find({}).exec(function(err,results){
    if (err){return next(err)}
    let top15 = [];
    for(let i = 0; i< results.length; i++){
      let dislikestouse = results[i].dislikes[0]
      let ratio  = 0
      if(dislikestouse > 0){
        ratio = results[i].likes[0]/dislikestouse
      }
      else{
        ratio = results[i].likes[0]/1
      }

    }
    res.render('content', { whichOne: 5, user: req.user, questions: top15 });
  })
});

results is every question in the database, and top15 is supposed to be only the ones displayed since they have the highest ratio and rendered into the template.
I tried using if statements to prevent it dividing by 0 since it results in an error.

how do I sort every result by finding if it is bigger then any of the items in top15 and then placing it in the right place if it is? I use pure JavaScript.
to access the numbers of a result's dislikes and likes search for the first item since it where I store the length, like a typical likes array is: [2,'username1', 'username2'].
here is the scheme for a question:

const Question = mongoose.model(
  "Question",
  new Schema({
    title: { type: String, required: true },
    text: { type: String },
    authorUsername: { type: String, required: true },
    dateCreated: {},
    answers: { type: Array, required: true },
    likes: { type: Array, required: true },
    dislikes: { type: Array, required: true },
    tag: { type: String, required: true },
    views: {type: Array, required:true},
  })
);

here is an example of a question:

_id:620935985f6865b4e85c333d
title:"How do i make a lemon?"
text:"yeet"
authorUsername:"SweetWhite"
dateCreated:2022-02-13T16:45:12.598+00:00
answers:
Array
likes:
Array
0:1
1:"SweetWhite"
dislikes:
Array
0:0
tag:
"Social"
views:
Array
0:1
1:"SweetWhite"
__v:0

Thanks!

Body:
The answer above is a superb pure Javascript solution.
However, it might be the case that we do not want to drag 1000s or possibly more of items out of the database just to sort and pick 15 on the client side.  Given a set of docs like this:

var r =   [
    {likes: ['A','A'], dislikes: ['A','A']},
    {likes: ['A','A']},
    {dislikes: ['A','A']},
    {likes: ['A','A','A','A','A'], dislikes: ['A','A']},
    {likes: ['A','A','A','A','A','A','A','A','A'], dislikes: ['A','A']},
    {likes: ['A','A','A','A','A','A','A','A'], dislikes: ['A','A']},
    {likes: ['A','A','A','A','A','A','A'], dislikes: ['A','A']},
    {likes: ['A'], dislikes: ['A','A']}
];

Then here is an aggregation that will drive the sort and "slice" logic into the DB:

db.foo.aggregate([
    // Protect against missing fields with $ifNull
    // Protect against division by zero dislikes using max[1,size]
    {$addFields: {ratio: {$divide:[{$size:{$ifNull:["$likes",[]]}},
                                 {$max:[1,{$size:{$ifNull:["$dislikes",[]]}}]}
                                ]}
               }},
    {$sort: {ratio:-1}},
    {$limit: 3}  // change to 15 for the real dataset
]);

If we must accomodate the "run length encoding" nature of the arrays e.g. [2, 'user1', 'user2'] then the agg is very similar only using $arrayElemAt to grab array[0] instead of using $size:

var r =   [
    {likes: [2, 'A','A'], dislikes: [2, 'A','A']},
    {likes: [2, 'A','A']},
    {dislikes: [2, 'A','A']},
    {likes: [5, 'A','A','A','A','A'], dislikes: [2, 'A','A']},
    {likes: [9, 'A','A','A','A','A','A','A','A','A'], dislikes: [2, 'A','A']},
    {likes: [8, 'A','A','A','A','A','A','A','A'], dislikes: [2, 'A','A']},
    {likes: [7, 'A','A','A','A','A','A','A'], dislikes: [2, 'A','A']},
    {likes: [1, 'A'], dislikes: [2, 'A','A']}
];

db.foo.aggregate([
    // Protect against missing fields with $ifNull but this time it is not
    // an empty array [] but rather an array of one elem, the length, which
    // is 0:
    {$project: {ratio: {$divide:[
        {$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},
        {$max:[1, {$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]}]}
        ]}
    }},
    {$sort: {ratio:-1}},
    {$limit: 3}
]);

{ "_id" : 4, "ratio" : 4.5 }
{ "_id" : 5, "ratio" : 4 }
{ "_id" : 6, "ratio" : 3.5 }


问:
Apply vector exponents to columns of matrix
In the cmprsk package one of the tests to call crr shows the following:

crr(ftime,fstatus,cov,cbind(cov[,1],cov[,1]),function(Uft) cbind(Uft,Uft^2))

It's the final inline function function(Uft) cbind(Uft,Uft^2) which I am interested in generalizing. This example call to crr above has cov1 as cov and cov2 as cbind(cov[,1],cov[,1]), essentially hardcoding the number of covariates. Hence the hardcoding of the function function(Uft) cbind(Uft,Uft^2) is sufficient.

I am working on some benchmarking code where I would like the number of covariates to be variable. So I generate a matrix cov2 which is has nobs rows and ncovs columns (rather than ncovs being pre-defined as 2 above).

My question is - how do I modify the inline function function(Uft) cbind(Uft,Uft^2) to take in a single column vector of length nobs and return a matrix of size nobs x ncovs where each column is simply the input vector raised to the column index?

Minimal reproducible example below. My call to z2 <- crr(...) is incorrect:

```<code>#!/usr/bin/env Rscript

library(cmprsk)

for(seed in c(1, 2)) {
    for(Nobs in c(10, 20)) {
        for(Ncovs in c(2, 3)) {
            set.seed(seed);
            ftime <- rexp(Nobs);
            fstatus <- sample(0:Ncovs,Nobs,replace=TRUE);
            cov1 <- matrix(runif(Nobs*Ncovs),nrow=Nobs);
            cov2 <- matrix(runif(Nobs*Ncovs),nrow=Nobs);
            df <- data.frame(ftime=ftime, fstatus=fstatus, cov1=cov1);

            z1 <- crr(ftime, fstatus, cov1, );
            z2 <- crr(ftime, fstatus, cov1, cov2, function(Uft) Uft^cbind(1:Ncovs));
        }
    }
}
</code>```

Body:
In the cmprsk package one of the tests to call crr shows the following:

crr(ftime,fstatus,cov,cbind(cov[,1],cov[,1]),function(Uft) cbind(Uft,Uft^2))

It's the final inline function function(Uft) cbind(Uft,Uft^2) which I am interested in generalizing. This example call to crr above has cov1 as cov and cov2 as cbind(cov[,1],cov[,1]), essentially hardcoding the number of covariates. Hence the hardcoding of the function function(Uft) cbind(Uft,Uft^2) is sufficient.

I am working on some benchmarking code where I would like the number of covariates to be variable. So I generate a matrix cov2 which is has nobs rows and ncovs columns (rather than ncovs being pre-defined as 2 above).

My question is - how do I modify the inline function function(Uft) cbind(Uft,Uft^2) to take in a single column vector of length nobs and return a matrix of size nobs x ncovs where each column is simply the input vector raised to the column index?

Minimal reproducible example below. My call to z2 <- crr(...) is incorrect:

#!/usr/bin/env Rscript

library(cmprsk)

for(seed in c(1, 2)) {
    for(Nobs in c(10, 20)) {
        for(Ncovs in c(2, 3)) {
            set.seed(seed);
            ftime <- rexp(Nobs);
            fstatus <- sample(0:Ncovs,Nobs,replace=TRUE);
            cov1 <- matrix(runif(Nobs*Ncovs),nrow=Nobs);
            cov2 <- matrix(runif(Nobs*Ncovs),nrow=Nobs);
            df <- data.frame(ftime=ftime, fstatus=fstatus, cov1=cov1);

            z1 <- crr(ftime, fstatus, cov1, );
            z2 <- crr(ftime, fstatus, cov1, cov2, function(Uft) Uft^cbind(1:Ncovs));
        }
    }
}

Body:
vec <- 1:4
ncovs <- 5
matrix(unlist(Reduce("*", rep(list(vec), ncovs), accumulate= TRUE)), ncol = ncovs)

gives:

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    2    4    8   16   32
[3,]    3    9   27   81  243
[4,]    4   16   64  256 1024


问:
Custom php.ini file not working in VPS hosting
I've tried going through Network Solutions tech support but didn't get it resolved ("You need to talk to Signature Support, which is $50").
I'm running some sites off of a Net Sol VPS account and need to change the upload_max_filesize setting (which is apparently set to a paltry 2MB by default) for the php server. I've added:

```<code>upload_max_filesize = 20M
post_max_size = 20M
max_execution_time = 6000
</code>```

to the /httpdocs/cgi-bin/php.ini file (per NS's instructions), and then restarted apache, but when I run a phpinfo on that domain, the settings are not applied. It still says "2M" for the upload max.

I also tried adding this to the server root at /cgi-bin/php.ini as well, to no effect.

There is no /cgi-bin/.php/php.coalesced.ini file that I can see.

Any ideas? I'm losing my mind with this.

答: First thought is to check your phpinfo() output for the value listed in the "Loaded Configuration File" setting and make sure that it matches the file you've been editing.</p>

Body:
I've tried going through Network Solutions tech support but didn't get it resolved ("You need to talk to Signature Support, which is $50").
I'm running some sites off of a Net Sol VPS account and need to change the upload_max_filesize setting (which is apparently set to a paltry 2MB by default) for the php server. I've added:

upload_max_filesize = 20M
post_max_size = 20M
max_execution_time = 6000

to the /httpdocs/cgi-bin/php.ini file (per NS's instructions), and then restarted apache, but when I run a phpinfo on that domain, the settings are not applied. It still says "2M" for the upload max.

I also tried adding this to the server root at /cgi-bin/php.ini as well, to no effect.

There is no /cgi-bin/.php/php.coalesced.ini file that I can see.

Any ideas? I'm losing my mind with this.


问:
Priority Queue to List. not adding properly
I am trying to copy items out of a priority queue and into an ArrayList. for some reason, when there are three or four items, it stops after adding two items to the list.
If there are 5 items, it stops after copying 3 items to the list. What am I doing wrong?

```<code>PriorityQueue<T> queue= new PriorityQueue<T> () ;
List<T> list = new ArrayList<T>();

 for (int i = 0 ; i< queue.size(); i++)
        {
           list.add(0, queue.poll());
        }
</code>```

答:
The reason is, the queue size is recalculated for each iteration but its size is reduced within the loop.

So, instead of calculating the queue size in the for loop... calculate it outside of the for loop. This way code does not need to recalculate it for each iteration and even though the queue size is reduced within the loop, it still iterates fully to the initial size of the list.

Some thing like:

```<code>PriorityQueue<T> queue= new PriorityQueue<T> () ;
List<T> list = new ArrayList<T>();

int qSize = queue.size();

 for (int i = 0 ; i< qSize; i++)
 {
    list.add(0, queue.poll());
 }
</code>```

Body:
I am trying to copy items out of a priority queue and into an ArrayList. for some reason, when there are three or four items, it stops after adding two items to the list.
If there are 5 items, it stops after copying 3 items to the list. What am I doing wrong?

PriorityQueue<T> queue= new PriorityQueue<T> () ;
List<T> list = new ArrayList<T>();

 for (int i = 0 ; i< queue.size(); i++)
        {
           list.add(0, queue.poll());
        }

Body:
The reason is, the queue size is recalculated for each iteration but its size is reduced within the loop.

So, instead of calculating the queue size in the for loop... calculate it outside of the for loop. This way code does not need to recalculate it for each iteration and even though the queue size is reduced within the loop, it still iterates fully to the initial size of the list.

Some thing like:

PriorityQueue<T> queue= new PriorityQueue<T> () ;
List<T> list = new ArrayList<T>();

int qSize = queue.size();

 for (int i = 0 ; i< qSize; i++)
 {
    list.add(0, queue.poll());
 }


问:
Error creating bean in maven spring, hibernate project
I am getting bean creating error for building online site. Here is the stack trace error message details:

Error creating bean with name 'adminController': Unsatisfied
dependency expressed through field 'adminService'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'adminService': Unsatisfied dependency
expressed through field 'adminDAO'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'adminDAO': Unsatisfied dependency
expressed through field 'sessionFactory'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'sessionFactory' defined in ServletContext
resource [/WEB-INF/main-servlet.xml]: Invocation of init method
failed; nested exception is
org.hibernate.service.spi.ServiceException: Unable to create requested
service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]   at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
at
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutow

Here is my Main-Servlet.xml code:

```<code><?xml  version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    <context:annotation-config />
    <context:component-scan base-package="com.simplilearn" />
    <beans:bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView"></beans:property>
        <beans:property name="prefix" value="/WEB-INF/view/"></beans:property>
        <beans:property name="suffix" value=".jsp"></beans:property>
    </beans:bean>
    <beans:bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <beans:property name="basename" value="classpath:messages"></beans:property>
        <beans:property name="defaultEncoding" value="UTF-8"></beans:property>
    </beans:bean>
    <beans:bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location" value="/WEB-INF/jdbc.properties"></beans:property>
    </beans:bean>
    <beans:bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
         <beans:property name="driverClassName" value="${jdbc.driverClassName}"></beans:property>
         <beans:property name="url" value="${jdbc.databaseurl}"></beans:property>
          <beans:property name="username" value="${jdbc.username}"></beans:property>
          <beans:property name="password" value="${jdbc.password}"></beans:property>
    </beans:bean>
    <beans:bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource"></beans:property>
          <beans:property name="packagesToScan" value="com.simplilearn.entity"></beans:property>
        <beans:property name="configLocation">
            <beans:value>classpath:hibernate.cfg.xml</beans:value>
        </beans:property>
        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.dialect">${jdbc.dialect}</beans:prop>
                <beans:prop key="hibernate.show_sql">true</beans:prop>
            </beans:props>
        </beans:property>
    </beans:bean>
    <tx:annotation-driven />
    <beans:bean id="transactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <beans:property name="sessionFactory" ref="sessionFactory"></beans:property>
    </beans:bean>
</beans:beans>
</code>```

Here is web.xml code

```<code><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<display-name>Archetype Created Web Application</display-name>

    <servlet>
        <servlet-name>main</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
          <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/main-servlet.xml</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>
     <servlet-mapping>
        <servlet-name>main</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/main-servlet.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>
 application properties
spring.jpa.hibernate.use-new-id-generator-mappings=false
 jdbc properties
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQL8Dialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/studentdb?useSSL=false
jdbc.username=root
jdbc.password=root

Here is my hibernate.cfg file
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.id.new_generator_mappings">false</property>
    </session-factory>
</hibernate-configuration>
Here is the pom file
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SportyShoes</groupId>
  <artifactId>SportyShoes</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Section7LEP Maven Webapp</name>
  <url>http://maven.apache.org</url>

    <!-- JBoss repository for Hibernate -->
    <repositories>
        <repository>
            <id>JBoss repository</id>
            <url>http://repository.jboss.org/nexus/content/groups/public/</url>
        </repository>
    </repositories>
   <properties>
    <org.springframework.version>5.1.6.RELEASE</org.springframework.version>
    <spring.security.version>3.2.3.RELEASE</spring.security.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

     <dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <!-- Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.security.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.version}</version>
        </dependency>

    <dependency>
       <groupId>log4j</groupId>
       <artifactId>log4j</artifactId>
       <version>1.2.16</version>
     </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.0.5.Final</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.guicedee.services/sl4j -->
<dependency>
    <groupId>com.guicedee.services</groupId>
    <artifactId>sl4j</artifactId>
    <version>1.0.13.5</version>
</dependency>

    <dependency>
        <groupId>javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.12.1.GA</version>
    </dependency>

    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>

   <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
    </dependency>

    <dependency>
      <groupId>javax.transaction</groupId>
      <artifactId>jta</artifactId>
      <version>1.1</version>
  </dependency>

  <dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2.11</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-core</artifactId>
        <version>2.2.11</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.2.11</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>
    <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
          <version>2.5</version>
          <scope>provided</scope>
    </dependency>
     <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>jstl</artifactId>
       <version>1.2</version>
 </dependency>

  </dependencies>
  <build>
    <finalName>Section7LEP2</finalName>
    <sourceDirectory>src/main</sourceDirectory>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
             <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                     <webXml>src\main\webapp\WEB-INF\web.xml</webXml>
                 </configuration>
                <version>2.4</version>
                <executions>
                    <execution>
                        <id>default-war</id>
                        <phase>package</phase>
                        <goals>
                            <goal>war</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>
  </build>

</project>
</code>```

答:
it work for me</p>
```<code>enter code here

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.24.RELEASE</version>
  </dependency>
       <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.24.RELEASE</version>
    </dependency>
        <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.17</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>5.2.3.RELEASE</version>
     </dependency>

    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
 </dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    </dependency>
        <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.2.6.RELEASE</version>
      </dependency>
         <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
        <version>4.2.6.RELEASE</version>
</dependency>
 <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.2.6.RELEASE</version>
</dependency>
 <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.2.6.RELEASE</version>
</dependency>
<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.36</version>
 </dependency>

    <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.0.Final</version>
</dependency>
    <dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.0.Final</version>
 </dependency>
</code>```

Body:
I am getting bean creating error for building online site. Here is the stack trace error message details:

Error creating bean with name 'adminController': Unsatisfied
dependency expressed through field 'adminService'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'adminService': Unsatisfied dependency
expressed through field 'adminDAO'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'adminDAO': Unsatisfied dependency
expressed through field 'sessionFactory'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'sessionFactory' defined in ServletContext
resource [/WEB-INF/main-servlet.xml]: Invocation of init method
failed; nested exception is
org.hibernate.service.spi.ServiceException: Unable to create requested
service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]   at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
at
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutow

Here is my Main-Servlet.xml code:

<?xml  version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    <context:annotation-config />
    <context:component-scan base-package="com.simplilearn" />
    <beans:bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView"></beans:property>
        <beans:property name="prefix" value="/WEB-INF/view/"></beans:property>
        <beans:property name="suffix" value=".jsp"></beans:property>
    </beans:bean>
    <beans:bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <beans:property name="basename" value="classpath:messages"></beans:property>
        <beans:property name="defaultEncoding" value="UTF-8"></beans:property>
    </beans:bean>
    <beans:bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location" value="/WEB-INF/jdbc.properties"></beans:property>
    </beans:bean>
    <beans:bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
         <beans:property name="driverClassName" value="${jdbc.driverClassName}"></beans:property>
         <beans:property name="url" value="${jdbc.databaseurl}"></beans:property>
          <beans:property name="username" value="${jdbc.username}"></beans:property>
          <beans:property name="password" value="${jdbc.password}"></beans:property>
    </beans:bean>
    <beans:bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource"></beans:property>
          <beans:property name="packagesToScan" value="com.simplilearn.entity"></beans:property>
        <beans:property name="configLocation">
            <beans:value>classpath:hibernate.cfg.xml</beans:value>
        </beans:property>
        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.dialect">${jdbc.dialect}</beans:prop>
                <beans:prop key="hibernate.show_sql">true</beans:prop>
            </beans:props>
        </beans:property>
    </beans:bean>
    <tx:annotation-driven />
    <beans:bean id="transactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <beans:property name="sessionFactory" ref="sessionFactory"></beans:property>
    </beans:bean>
</beans:beans>

Here is web.xml code

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<display-name>Archetype Created Web Application</display-name>

    <servlet>
        <servlet-name>main</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
          <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/main-servlet.xml</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>
     <servlet-mapping>
        <servlet-name>main</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/main-servlet.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>
 application properties
spring.jpa.hibernate.use-new-id-generator-mappings=false
 jdbc properties
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQL8Dialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/studentdb?useSSL=false
jdbc.username=root
jdbc.password=root

Here is my hibernate.cfg file
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.id.new_generator_mappings">false</property>
    </session-factory>
</hibernate-configuration>
Here is the pom file
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SportyShoes</groupId>
  <artifactId>SportyShoes</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Section7LEP Maven Webapp</name>
  <url>http://maven.apache.org</url>

    <repositories>
        <repository>
            <id>JBoss repository</id>
            <url>http://repository.jboss.org/nexus/content/groups/public/</url>
        </repository>
    </repositories>
   <properties>
    <org.springframework.version>5.1.6.RELEASE</org.springframework.version>
    <spring.security.version>3.2.3.RELEASE</spring.security.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

     <dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.security.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.version}</version>
        </dependency>

    <dependency>
       <groupId>log4j</groupId>
       <artifactId>log4j</artifactId>
       <version>1.2.16</version>
     </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.0.5.Final</version>
    </dependency>

<dependency>
    <groupId>com.guicedee.services</groupId>
    <artifactId>sl4j</artifactId>
    <version>1.0.13.5</version>
</dependency>

    <dependency>
        <groupId>javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.12.1.GA</version>
    </dependency>

    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>

   <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
    </dependency>

    <dependency>
      <groupId>javax.transaction</groupId>
      <artifactId>jta</artifactId>
      <version>1.1</version>
  </dependency>

  <dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2.11</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-core</artifactId>
        <version>2.2.11</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.2.11</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>
    <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
          <version>2.5</version>
          <scope>provided</scope>
    </dependency>
     <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>jstl</artifactId>
       <version>1.2</version>
 </dependency>

  </dependencies>
  <build>
    <finalName>Section7LEP2</finalName>
    <sourceDirectory>src/main</sourceDirectory>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
             <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                     <webXml>src\main\webapp\WEB-INF\web.xml</webXml>
                 </configuration>
                <version>2.4</version>
                <executions>
                    <execution>
                        <id>default-war</id>
                        <phase>package</phase>
                        <goals>
                            <goal>war</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>
  </build>

</project>

Body:
it work for me

enter code here

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.24.RELEASE</version>
  </dependency>
       <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.24.RELEASE</version>
    </dependency>
        <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.17</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>5.2.3.RELEASE</version>
     </dependency>

    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
 </dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    </dependency>
        <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.2.6.RELEASE</version>
      </dependency>
         <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
        <version>4.2.6.RELEASE</version>
</dependency>
 <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.2.6.RELEASE</version>
</dependency>
 <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.2.6.RELEASE</version>
</dependency>
<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.36</version>
 </dependency>

    <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.0.Final</version>
</dependency>
    <dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.0.Final</version>
 </dependency>


问:
Cant install pandas_datareader.data
'
I am trying to install 'pandas datareader data' as web

but getting this error

答:
Installing and importing are different things.

Before you can import pandas_datareader you must install it, e.g. by running

```<code>conda install pandas_datareader
</code>```

in your shell (it sounds like you use cmd.exe). Alternatively, you can do this right from Jupyter by prefixing the command with a !:

```<code>!conda install pandas_datareader
</code>```

Once installation has finished, you should be able to import and use the library.

Title: Cant install pandas_datareader.data

Body:
Installing and importing are different things.

Before you can import pandas_datareader you must install it, e.g. by running

conda install pandas_datareader

in your shell (it sounds like you use cmd.exe). Alternatively, you can do this right from Jupyter by prefixing the command with a !:

!conda install pandas_datareader

Once installation has finished, you should be able to import and use the library.


问:
for loop repeats until value is less than three
I dont know why my for loop is not working. I have been trying for so long. It just runs for the do / while and gives return. Everything in the do / while loop. I have declared a macro outside the main function and I am using it as loop condition. I can't add more details, all I have is code.

```<code>#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#define MIN_YEAR 2012
#define MAX_YEAR 2022

#define LOG_DAYS 3

int main(void)
{
    const int JAN = 1;
    const int DEC = 12;
    int year = 0;
    int month = 0;
    char day1 = 01;
    char day2 = 02;
    char day3 = 03;
    float ratingMorning = 0;
    float ratingEvening = 0;

    printf("General Well-being Log\n"
        "======================\n");

    do
    {
        printf("Set the year and month for the well-being log (YYYY MM): ");
        scanf(" %d %d", &year, &month);

        if ((MIN_YEAR > year || year > MAX_YEAR))
        {
            printf("   ERROR: The year must be between 2012 and 2022 inclusive\n");
        }

        if ((JAN > month || month > DEC))
        {
            printf("   ERROR: Jan.(1) - Dec.(12)\n");
        }

        if ((JAN <= month && month <= DEC) && (MIN_YEAR <= year && year <= MAX_YEAR))
        {
            printf("\n*** Log date set! ***\n\n");
            break;
        }

    } while ((MIN_YEAR <= year || year <= MAX_YEAR) && (JAN <= month || month <= DEC));

    for (int i = 0; i < LOG_DAYS; i++)
    {
        printf(" %d", year);
        printf("-");
        printf(" %d", month);
        printf("-");
        printf(" %d",day1);
        printf("   Morning rating (0.0-5.0): ");
        scanf(" %d", &ratingMorning);

        if (ratingMorning < 0 || ratingMorning > 5)
        {
            printf("      ERROR: Rating must be between 0.0 and 5.0 inclusive!");
        }

        printf("   Evening rating (0.0-5.0): ");
        scanf(" %d", &ratingEvening);

        if (ratingEvening < 0 || ratingEvening > 5)
        {
            printf("      ERROR: Rating must be between 0.0 and 5.0 inclusive!");
        }
    }
    return 0;
}
</code>```

答:
If the problem is that:

if (ratingMorning < 0 || ratingMorning > 5) is not working

i.e. the error line ERROR: Rating must be between 0.0 and 5.0 inclusive!" is never printed, then when you change the %d to %f in the scanf(" %d", &ratingMorning); lines, the errors are printed because now ratingMorning and ratingEvening contain valid values, whereas when they were input as integers, the values were invalid.

Body:
I dont know why my for loop is not working. I have been trying for so long. It just runs for the do / while and gives return. Everything in the do / while loop. I have declared a macro outside the main function and I am using it as loop condition. I can't add more details, all I have is code.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#define MIN_YEAR 2012
#define MAX_YEAR 2022

#define LOG_DAYS 3

int main(void)
{
    const int JAN = 1;
    const int DEC = 12;
    int year = 0;
    int month = 0;
    char day1 = 01;
    char day2 = 02;
    char day3 = 03;
    float ratingMorning = 0;
    float ratingEvening = 0;

    printf("General Well-being Log\n"
        "======================\n");

    do
    {
        printf("Set the year and month for the well-being log (YYYY MM): ");
        scanf(" %d %d", &year, &month);

        if ((MIN_YEAR > year || year > MAX_YEAR))
        {
            printf("   ERROR: The year must be between 2012 and 2022 inclusive\n");
        }

        if ((JAN > month || month > DEC))
        {
            printf("   ERROR: Jan.(1) - Dec.(12)\n");
        }

        if ((JAN <= month && month <= DEC) && (MIN_YEAR <= year && year <= MAX_YEAR))
        {
            printf("\n*** Log date set! ***\n\n");
            break;
        }

    } while ((MIN_YEAR <= year || year <= MAX_YEAR) && (JAN <= month || month <= DEC));

    for (int i = 0; i < LOG_DAYS; i++)
    {
        printf(" %d", year);
        printf("-");
        printf(" %d", month);
        printf("-");
        printf(" %d",day1);
        printf("   Morning rating (0.0-5.0): ");
        scanf(" %d", &ratingMorning);

        if (ratingMorning < 0 || ratingMorning > 5)
        {
            printf("      ERROR: Rating must be between 0.0 and 5.0 inclusive!");
        }

        printf("   Evening rating (0.0-5.0): ");
        scanf(" %d", &ratingEvening);

        if (ratingEvening < 0 || ratingEvening > 5)
        {
            printf("      ERROR: Rating must be between 0.0 and 5.0 inclusive!");
        }
    }
    return 0;
}