问:
How to persist an EnumMap in Hibernate/JPA?
I'm currently trying to persist data which I'd stored as a Map in Java.
I've gotten this to work using List already, however when I try to make this a Map instead using @MapKeyEnumerated and @MapKey it acts a bit unexpected.

ExampleData.java

@MapKey(name = "feature")
@MapKeyEnumerated(EnumType.STRING)
@OneToMany(targetEntity = ExampleFeature.class, mappedBy = "exampleData")
private Map<Feature, ExampleFeature> features;
```
<p><strong>ExampleFeature.java</strong></p>
<pre class="lang-java prettyprint-override"><code>@ManyToOne
@JoinColumn(name = "example_id", nullable = false)
private ExampleData exampleData;

@Enumerated(EnumType.STRING)
@Column(name = "feature", nullable = false)
private Feature feature;
</code>```

I'm able to add rows to the database manually outside of runtime, and when running the application it's able to load those entities correctly. All other entities are also working as intended.

When persisting entities in from the application, the ExampleFeature does appear in the Map, but all properties in the instance are the default Java values, and after stepping-out

Dependencies

org.hibernate:hibernate-core:5.4.17.Final

org.hibernate:hibernate-c3p0:5.4.17.Final

Could anyone point me in the right direction as to what I might have wrong here?

答:
The issue is that in the project, #save() was only called on ExampleData, but not on any of the relational properties under it. This means that Hibernate would try to persist the ExampleData instance, however not any nested properties such as the EnumMap.

The solution is to set cascade = CascadeType.ALL which will tell Hibernate to persist changes in relational entities such as ExampleFeature when persisting ExampleData.

ExampleData.java

@MapKey(name = "feature")
@MapKeyEnumerated(EnumType.STRING)
@OneToMany(targetEntity = ExampleFeature.class, mappedBy = "exampleData", cascade = CascadeType.ALL)
private Map<Feature, ExampleFeature> features;
```

Body:
I'm currently trying to persist data which I'd stored as a Map in Java.
I've gotten this to work using List already, however when I try to make this a Map instead using @MapKeyEnumerated and @MapKey it acts a bit unexpected.

ExampleData.java

@MapKey(name = "feature")
@MapKeyEnumerated(EnumType.STRING)
@OneToMany(targetEntity = ExampleFeature.class, mappedBy = "exampleData")
private Map<Feature, ExampleFeature> features;

ExampleFeature.java

@ManyToOne
@JoinColumn(name = "example_id", nullable = false)
private ExampleData exampleData;

@Enumerated(EnumType.STRING)
@Column(name = "feature", nullable = false)
private Feature feature;

I'm able to add rows to the database manually outside of runtime, and when running the application it's able to load those entities correctly. All other entities are also working as intended.

When persisting entities in from the application, the ExampleFeature does appear in the Map, but all properties in the instance are the default Java values, and after stepping-out

Dependencies

org.hibernate:hibernate-core:5.4.17.Final

org.hibernate:hibernate-c3p0:5.4.17.Final

Could anyone point me in the right direction as to what I might have wrong here?


来源: stackexchange

问:
I want to store input data in object but can't be able to do so?
html

```<code><form name="AdminForm" onsubmit="return Updateit()">
      <input type="text" id="name" required>
      <input type="email" id="email" required>
      <input type="number" id="phoneNumb" required>
      <input type="text" id="address" required>
      <input type="submit" value="Submit" class="btn">
      <input type="reset" value="Reset">
</form>
</code>```

Javascript

```<code>var database = {}
function Updateit(){
    const Name = document.forms["AdminForm"]["name"].value;
    const Email = document.forms["AdminForm"]["email"].value;
    const PhoneNumb = document.forms["AdminForm"]["phoneNumb"].value;
    const Address = document.forms["AdminForm"]["address"].value;

    database[Name] = [Email,PhoneNumb.toString(),Address];
    console.log(database[Name]);
}
</code>```

the data in object is vanished after a Millisecond
After input data in form i used to save that data in database object but is not shown in it when i try to display in console or alert.

答:
You have not specified your Html structure and when this function was triggered, but if so, what is the problem with its operation ?

var database = {}

let button = document.getElementById("get-form");
button.addEventListener("click", Updateit)

function Updateit() {
  const Name = document.forms["AdminForm"]["name"].value;
  const Email = document.forms["AdminForm"]["email"].value;
  const PhoneNumb = document.forms["AdminForm"]["phoneNumb"].value;
  const Address = document.forms["AdminForm"]["address"].value;

  database[Name] = [Email, PhoneNumb.toString(), Address];
  console.log(database[Name]);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="AdminForm">
  <input type="text" name="name">
  <input type="email" name="email">
  <input type="text" name="phoneNumb">
  <input type="text" name="address">
  <button type="button" id="get-form">Get Form Items</button>
</form></code>```

ContentLicense: CC BY-SA 4.0

Body:
html

<form name="AdminForm" onsubmit="return Updateit()">
      <input type="text" id="name" required>
      <input type="email" id="email" required>
      <input type="number" id="phoneNumb" required>
      <input type="text" id="address" required>
      <input type="submit" value="Submit" class="btn">
      <input type="reset" value="Reset">
</form>

Javascript

var database = {}
function Updateit(){
    const Name = document.forms["AdminForm"]["name"].value;
    const Email = document.forms["AdminForm"]["email"].value;
    const PhoneNumb = document.forms["AdminForm"]["phoneNumb"].value;
    const Address = document.forms["AdminForm"]["address"].value;

    database[Name] = [Email,PhoneNumb.toString(),Address];
    console.log(database[Name]);
}

the data in object is vanished after a Millisecond
After input data in form i used to save that data in database object but is not shown in it when i try to display in console or alert.

Body:
You have not specified your Html structure and when this function was triggered, but if so, what is the problem with its operation ?

var database = {}

let button = document.getElementById("get-form");
button.addEventListener("click", Updateit)

function Updateit() {
  const Name = document.forms["AdminForm"]["name"].value;
  const Email = document.forms["AdminForm"]["email"].value;
  const PhoneNumb = document.forms["AdminForm"]["phoneNumb"].value;
  const Address = document.forms["AdminForm"]["address"].value;

  database[Name] = [Email, PhoneNumb.toString(), Address];
  console.log(database[Name]);
}

<form name="AdminForm">
  <input type="text" name="name">
  <input type="email" name="email">
  <input type="text" name="phoneNumb">
  <input type="text" name="address">
  <button type="button" id="get-form">Get Form Items</button>
</form>


问:
How can I filter results by custom field in Solr query?
I need some custom field filter for my Solr data like

```<code>   {
    "id":"1",
    "name":"Test title",
    "language":"en"
    },
  {
    "id":"2",
    "name":"Test title",
    "language":"fr"
    "parent": "1"
    }
</code>```

I need to get just first item by query

```<code>/select?q=name:test
</code>```

So I need to filter results by parent field in such way, that one of the items will be present in the result.
Thanks for any ideas.

答:
When I need to do querys in Solr I used the SearchQuery() and inside them I set filterQueries. There was possible set filters for my search.

```<code>final String FIELD_NAME = "name_text_mv"; // name of my field in Solr
SearchQuery searchQuery = init(facetSearchConfig); // init configs
searchQuery.setFreeTextQueryBuilder(text); // set the text of my search
setFiltersFreeTextSearch(searchQuery.getFilterQueries(), text, FIELD_NAME);
</code>```

The function to make the magic (add in my search my filters):

```<code>private void setFiltersFreeTextSearch(List<QueryField> filters, String text, String... fields) {
    text = StringUtils.stripAccents(text).toLowerCase();
    String textCapitalized = capitalizeEachWolrd(text.toLowerCase());
    for (String field : fields) {
        QueryField queryField = new QueryField(field, SearchQuery.Operator.OR, SearchQuery.QueryOperator.CONTAINS,
                text, text.toUpperCase(), textCapitalized);
        filters.add(queryField);
    }
}
</code>```

How you can see, in this QueryField you can add the 'wheres' of you search in Solr. I was using CONTAINS and that is my 'LIKE' and 'OR' for find any item.

So basicly you can use QueryField() to add filters for you specifically field.

Well, this was my solution for my case, anyway, this is just an idea. :)

(For the projet is used Java)

Body:
I need some custom field filter for my Solr data like

   {
    "id":"1",
    "name":"Test title",
    "language":"en"
    },
  {
    "id":"2",
    "name":"Test title",
    "language":"fr"
    "parent": "1"
    }

I need to get just first item by query

/select?q=name:test

So I need to filter results by parent field in such way, that one of the items will be present in the result.
Thanks for any ideas.

Body:
When I need to do querys in Solr I used the SearchQuery() and inside them I set filterQueries. There was possible set filters for my search.

final String FIELD_NAME = "name_text_mv"; // name of my field in Solr
SearchQuery searchQuery = init(facetSearchConfig); // init configs
searchQuery.setFreeTextQueryBuilder(text); // set the text of my search
setFiltersFreeTextSearch(searchQuery.getFilterQueries(), text, FIELD_NAME);

The function to make the magic (add in my search my filters):

private void setFiltersFreeTextSearch(List<QueryField> filters, String text, String... fields) {
    text = StringUtils.stripAccents(text).toLowerCase();
    String textCapitalized = capitalizeEachWolrd(text.toLowerCase());
    for (String field : fields) {
        QueryField queryField = new QueryField(field, SearchQuery.Operator.OR, SearchQuery.QueryOperator.CONTAINS,
                text, text.toUpperCase(), textCapitalized);
        filters.add(queryField);
    }
}

How you can see, in this QueryField you can add the 'wheres' of you search in Solr. I was using CONTAINS and that is my 'LIKE' and 'OR' for find any item.

So basicly you can use QueryField() to add filters for you specifically field.

Well, this was my solution for my case, anyway, this is just an idea. :)

(For the projet is used Java)


问:
How to print fullcalendar with given date range including all events?
How can someone print fullcalendar or export fullcalendar in PDF or Excel format?

For example:

Input:

Start Date: 01 Jan 2020

End Date: 31 Dec 2020

On click of button it will get all of the events between given date ranges and populate it to the fullcalendar

There will be something like...

26th January 2020 which will have an event - Australia Day

14th February 2020 which will have an event - Valentines day

...

...

25th December 2020 which will have an event - X-Mas Day

As you can see there will be multiple events in different months and what I am looking for is printing or exporting this fullcalendar in a single page with all 12 number of months.

Your response will help many.

答:
You can use the below sample code by editing , hope it helps

<?php

header("Content-Type: text/html; charset=iso-8859-9");
header("Content-Type: text/html; charset=windows-1254");
header("Content-Type: text/html; charset=x-mac-turkish");

$today = date("d-m-Y");

// Defines the name of the export file "codelution-export.xls"
header("Content-Disposition: attachment; filename=$today-BOOK.xls");

$date = '2020-05-01';

//get end date of month
$end = '2020-05-' . date('t', strtotime($date));

include("../../DATABASE.php");
?>

    PERSONAL

    <?php
      while(strtotime($date) <= strtotime($end)){
        $day_num = date('d', strtotime($date));
        $day_name = date('l', strtotime($date));
        $date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
        echo "$day_num
 $day_name	";
      }
    ?>

  <?php
    //get end date of month
    $hsql=mysql_query("select * from XXXUSER");
    while($hyaz=mysql_fetch_array($hsql)){
      $firstname=$hyaz["firstname"];
      $kullanicidi=$hyaz["id"];
      echo "
";
      echo "$firstname	";
      $fromdate = '2020-06-01';
      $todate = '2020-06-' . date('t', strtotime($fromdate));

      while(strtotime($fromdate) <= strtotime($todate)) {
        $geneltarih = date('Y-m-d', strtotime($fromdate));
        $fromdate = date("Y-m-d", strtotime("+1 day",strtotime($fromdate)));
        $xxxsql = mysql_fetch_array(mysql_query("select * from XXXSCHEDULE where kaynakcodu='$kullanicidi' and start_event='$geneltarih'"));
        $title = $xxxsql["title"];
        echo " $title	";
      }

      echo "
";
    }
  ?>

```

Body:
You can use the below sample code by editing , hope it helps

<?php

header("Content-Type: text/html; charset=iso-8859-9");
header("Content-Type: text/html; charset=windows-1254");
header("Content-Type: text/html; charset=x-mac-turkish");

$today = date("d-m-Y");

// Defines the name of the export file "codelution-export.xls"
header("Content-Disposition: attachment; filename=$today-BOOK.xls");

$date = '2020-05-01';

//get end date of month
$end = '2020-05-' . date('t', strtotime($date));

include("../../DATABASE.php");
?>

<table>
  <tr>
    <td>PERSONAL</td>

    <?php
      while(strtotime($date) <= strtotime($end)){
        $day_num = date('d', strtotime($date));
        $day_name = date('l', strtotime($date));
        $date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
        echo "<td>$day_num <br/> $day_name</td>";
      }
    ?>
  </tr>

  <?php
    //get end date of month
    $hsql=mysql_query("select * from XXXUSER");
    while($hyaz=mysql_fetch_array($hsql)){
      $firstname=$hyaz["firstname"];
      $kullanicidi=$hyaz["id"];
      echo "<tr>";
      echo "<td>$firstname</td>";
      $fromdate = '2020-06-01';
      $todate = '2020-06-' . date('t', strtotime($fromdate));

      while(strtotime($fromdate) <= strtotime($todate)) {
        $geneltarih = date('Y-m-d', strtotime($fromdate));
        $fromdate = date("Y-m-d", strtotime("+1 day",strtotime($fromdate)));
        $xxxsql = mysql_fetch_array(mysql_query("select * from XXXSCHEDULE where kaynakcodu='$kullanicidi' and start_event='$geneltarih'"));
        $title = $xxxsql["title"];
        echo " <td>$title</td>";
      }

      echo "</tr>";
    }
  ?>
</table>


问:
Max value of for each column for distinct rows of data frame in r
Let’s say there is an ordered df with an ID column, and other columns containing numeral data, ordered by the last column.

```<code>ID <- c(123, 142, 21, 562, 36, 721, 847, 321)
A <- c(96, 83, 73, 47, 88, 65, 72, 67)
B <- c(72, 69, 88, 75, 63, 89, 48, 80)
C <- c(95, 94, 94, 94, 65, 81, 75, 75)
D <- c(63, 88, 89, 88, 89, 79, 88, 79)
Rating <- c(97, 95, 92, 87, 85, 83, 79, 77)
df <- data.frame(ID, A, B, C, D, Rating)
df
#   ID  A  B  C  D Rating
#1 123 96 72 95 63     97
#2 142 83 69 94 88     95
#3  21 73 88 94 89     92
#4 562 47 75 94 88     87
#5  36 88 63 65 89     85
#6 721 65 89 81 79     83
#7 847 72 48 75 88     79
#8 321 67 80 75 79     77
</code>```

The aim is to get the max value for each group/column, with its ID, and each pair needs to be from a distinct row (unique ID). For two IDs with the same value for a column, pick the one with the better Rating.

What I did is use the apply() function to get the max from each column, extract the IDs that have that value, and join them all into a data frame. Because I was still missing an ID for the 4th column, I used an anti join to take out the previous IDs and repeated the process to get this data frame:

```<code>my_max <- data.frame(apply(df, 2, max))
A2 <- df[which(df$A == my_max[2,1]),]%>% dplyr::select(ID, A)
B2 <- df[which(df$B == my_max[3,1]),]%>% dplyr::select(ID, B)
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
D2 <- df[which(df$D == my_max[5,1]),]%>% dplyr::select(ID, D)
all <- full_join(A2, B2, by='ID') %>% full_join(C2, by='ID') %>% full_join(D2, by='ID')
all <- all[-c(4),]
df <- anti_join(df, all, by='ID')
my_max <- data.frame(apply(df, 2, max))
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
all <- all %>% full_join(C2, by='ID')
all <- all[-c(5),-c(4)]
</code>```

To finally give me:

```<code>all
#   ID  A  B  D C.y
#1 123 96 NA NA  NA
#2 721 NA 89 NA  NA
#3  21 NA NA 89  NA
#4 142 NA NA NA  94
</code>```

Is there a more clean or concise/efficient way of doing this? Not necessarily the same way, perhaps just the ID and role like:

```<code>#   ID  Group
#1 123    A
#2 721    B
#3 142    C
#4 21     D
</code>```

答:
Based on this answer and using dplyr:

df %>%
  group_by(ID) %>%
  mutate(max.val = pmax(A, B, C, D)[which.max(Rating)]) %>%
  summarise_each(list(max)) %>%
  mutate(top.col=apply(.[,2:5], 1, function(x) names(x)[which.max(x)])) %>%
  select(-c(A, B, C, D, Rating))
```

<p>you get</p>

<pre class="lang-r prettyprint-override"><code># A tibble: 8 x 3
     ID max.val top.col
  <dbl>   <dbl> <chr>
1    21      94 C
2    36      89 D
3   123      96 A
4   142      94 C
5   321      80 B
6   562      94 C
7   721      89 B
8   847      88 D
</code>```

Body:
Let’s say there is an ordered df with an ID column, and other columns containing numeral data, ordered by the last column.

ID <- c(123, 142, 21, 562, 36, 721, 847, 321)
A <- c(96, 83, 73, 47, 88, 65, 72, 67)
B <- c(72, 69, 88, 75, 63, 89, 48, 80)
C <- c(95, 94, 94, 94, 65, 81, 75, 75)
D <- c(63, 88, 89, 88, 89, 79, 88, 79)
Rating <- c(97, 95, 92, 87, 85, 83, 79, 77)
df <- data.frame(ID, A, B, C, D, Rating)
df
#   ID  A  B  C  D Rating
#1 123 96 72 95 63     97
#2 142 83 69 94 88     95
#3  21 73 88 94 89     92
#4 562 47 75 94 88     87
#5  36 88 63 65 89     85
#6 721 65 89 81 79     83
#7 847 72 48 75 88     79
#8 321 67 80 75 79     77

The aim is to get the max value for each group/column, with its ID, and each pair needs to be from a distinct row (unique ID). For two IDs with the same value for a column, pick the one with the better Rating.

What I did is use the apply() function to get the max from each column, extract the IDs that have that value, and join them all into a data frame. Because I was still missing an ID for the 4th column, I used an anti join to take out the previous IDs and repeated the process to get this data frame:

my_max <- data.frame(apply(df, 2, max))
A2 <- df[which(df$A == my_max[2,1]),]%>% dplyr::select(ID, A)
B2 <- df[which(df$B == my_max[3,1]),]%>% dplyr::select(ID, B)
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
D2 <- df[which(df$D == my_max[5,1]),]%>% dplyr::select(ID, D)
all <- full_join(A2, B2, by='ID') %>% full_join(C2, by='ID') %>% full_join(D2, by='ID')
all <- all[-c(4),]
df <- anti_join(df, all, by='ID')
my_max <- data.frame(apply(df, 2, max))
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
all <- all %>% full_join(C2, by='ID')
all <- all[-c(5),-c(4)]

To finally give me:

all
#   ID  A  B  D C.y
#1 123 96 NA NA  NA
#2 721 NA 89 NA  NA
#3  21 NA NA 89  NA
#4 142 NA NA NA  94

Is there a more clean or concise/efficient way of doing this? Not necessarily the same way, perhaps just the ID and role like:

#   ID  Group
#1 123    A
#2 721    B
#3 142    C
#4 21     D

Body:
Based on this answer and using dplyr:

df %>%
  group_by(ID) %>%
  mutate(max.val = pmax(A, B, C, D)[which.max(Rating)]) %>%
  summarise_each(list(max)) %>%
  mutate(top.col=apply(.[,2:5], 1, function(x) names(x)[which.max(x)])) %>%
  select(-c(A, B, C, D, Rating))

you get

# A tibble: 8 x 3
     ID max.val top.col
  <dbl>   <dbl> <chr>
1    21      94 C
2    36      89 D
3   123      96 A
4   142      94 C
5   321      80 B
6   562      94 C
7   721      89 B
8   847      88 D


问:
Functions in other files
How can I use functions that I have created before, in different python files and projects? for example functions that I have created in project A I want to use in project B.</p>

答:
A.py contains

```<code>def myFunction():
    print("Hello World")
</code>```

you can call this function in your B.py
by simply importing it

B.py contains

```<code>import A

A.myFunction()
</code>```

Title: Functions in other files

Body:
A.py contains

def myFunction():
    print("Hello World")

you can call this function in your B.py
by simply importing it

B.py contains

import A

A.myFunction()


问:
Logstash settup to Mysql hosted on AWS RDS. Won't connect
I have a MySQL DB hosted on AWS RDS. I am running ElasticSearch locally and using Logstash to retrieve data from MYSQL server that is on AWS to then push the data to my ElasticSearch DB.

The problem is that my logstash file isn't settup correctly I guess:

```<code>input {
    jdbc {
        jdbc_connection_string => "jdbc:mysql://aws.ffffffffff.us-east-1.rds.amazonaws.com:3306/dbName?user=userName&password=pword"
        jdbc_user => "user"
        jdbc_password => "pword"
        schedule => "* * * * *"
        jdbc_validate_connection => true
        jdbc_driver_library => "C:\Program Files (x86)\MySQL\Connector J 8.0\mysql-connector-java-8.0.19.jar"
        jdbc_driver_class => "com.mysql.cj.jdbc.Driver"
        statement => "SELECT * from data-5"
        type => "data-5"
        tags => ["data-5"]
    }

    jdbc {
        jdbc_connection_string => "jdbc:mysql://aws.ffffffffff.us-east-1.rds.amazonaws.com:3306/dbName?user=userName&password=pword"
        jdbc_user => "user"
        jdbc_password => "pword"
        schedule => "* * * * *"
        jdbc_validate_connection => true
        jdbc_driver_library => "C:\Program Files (x86)\MySQL\Connector J 8.0\mysql-connector-java-8.0.19.jar"
        jdbc_driver_class => "com.mysql.cj.jdbc.Driver"
        statement => "SELECT * from data-4"
        type => "data-4"
        tags => ["data-4"]
    }

    jdbc {
        jdbc_connection_string => "jdbc:mysql://aws.ffffffffff.us-east-1.rds.amazonaws.com:3306/dbName?user=userName&password=pword"
        jdbc_user => "user"
    jdbc_password => "pword"
    schedule => "* * * * *"
        jdbc_validate_connection => true
        jdbc_driver_library => "C:\Program Files (x86)\MySQL\Connector J 8.0\mysql-connector-java-8.0.19.jar"
        jdbc_driver_class => "com.mysql.cj.jdbc.Driver"
        statement => "SELECT * from data-3"
        type => "data-3"
        tags => ["data-3"]
    }
}
output {
    stdout { codec => json_lines }

    if "data-5" in [tags] {
        elasticsearch {
            hosts => ["http://127.0.0.1:9200/"]
            index => "data-5"
            document_type => "data-%{+YYYY.MM.dd}"
        }
    }

    if "data-4" in [tags] {
        elasticsearch {
            hosts => ["http://127.0.0.1:9200/"]
            index => "data-4"
            document_type => "data-%{+YYYY.MM.dd}"
        }
    }

    if "data-3" in [tags] {
        elasticsearch {
            hosts => ["http://127.0.0.1:9200/"]
            index => "data-3"
            document_type => "data-%{+YYYY.MM.dd}"
        }
    }
}
</code>```

This is the fun part of programming right?

Anyway, locally I am on windows as you may be able to tell from the file path to the jdbc driver library. My jdbc connection to the AWS RDS is copied and pasted from AWS Console, so no typos were involved.

I am told that I only need to append jdbc:mysql:// to the url. But is there anything I'm missing to do in the AWS console? Do I need to modify my RDS instance?

The error by the way is:

```<code> Unable to connect to database. Tried 1 times
{:error_message=>"Java::ComMysqlCjJdbcExceptions::CommunicationsException:
Communications link failure\n\n
The last packet sent successfully to the server was 0 milliseconds ago.
The driver has not received any packets from the server."
</code>```

答:
I had a similar issue, and SSL was not enabled for communication. So, AWS RDS was not allowing to connect.

I specified an additional query param useSSL=false to JDBC connection string, and problem was solved.

So, in your case, the jdbc_connection_string would be as follows:

```<code>"jdbc:mysql://aws.ffffffffff.us-east-1.rds.amazonaws.com:3306/dbName?useSSL=false&user=userName&password=pword"
</code>```

Body:
I have a MySQL DB hosted on AWS RDS. I am running ElasticSearch locally and using Logstash to retrieve data from MYSQL server that is on AWS to then push the data to my ElasticSearch DB.

The problem is that my logstash file isn't settup correctly I guess:

input {
    jdbc {
        jdbc_connection_string => "jdbc:mysql://aws.ffffffffff.us-east-1.rds.amazonaws.com:3306/dbName?user=userName&password=pword"
        jdbc_user => "user"
        jdbc_password => "pword"
        schedule => "* * * * *"
        jdbc_validate_connection => true
        jdbc_driver_library => "C:\Program Files (x86)\MySQL\Connector J 8.0\mysql-connector-java-8.0.19.jar"
        jdbc_driver_class => "com.mysql.cj.jdbc.Driver"
        statement => "SELECT * from data-5"
        type => "data-5"
        tags => ["data-5"]
    }

    jdbc {
        jdbc_connection_string => "jdbc:mysql://aws.ffffffffff.us-east-1.rds.amazonaws.com:3306/dbName?user=userName&password=pword"
        jdbc_user => "user"
        jdbc_password => "pword"
        schedule => "* * * * *"
        jdbc_validate_connection => true
        jdbc_driver_library => "C:\Program Files (x86)\MySQL\Connector J 8.0\mysql-connector-java-8.0.19.jar"
        jdbc_driver_class => "com.mysql.cj.jdbc.Driver"
        statement => "SELECT * from data-4"
        type => "data-4"
        tags => ["data-4"]
    }

    jdbc {
        jdbc_connection_string => "jdbc:mysql://aws.ffffffffff.us-east-1.rds.amazonaws.com:3306/dbName?user=userName&password=pword"
        jdbc_user => "user"
    jdbc_password => "pword"
    schedule => "* * * * *"
        jdbc_validate_connection => true
        jdbc_driver_library => "C:\Program Files (x86)\MySQL\Connector J 8.0\mysql-connector-java-8.0.19.jar"
        jdbc_driver_class => "com.mysql.cj.jdbc.Driver"
        statement => "SELECT * from data-3"
        type => "data-3"
        tags => ["data-3"]
    }
}
output {
    stdout { codec => json_lines }

    if "data-5" in [tags] {
        elasticsearch {
            hosts => ["http://127.0.0.1:9200/"]
            index => "data-5"
            document_type => "data-%{+YYYY.MM.dd}"
        }
    }

    if "data-4" in [tags] {
        elasticsearch {
            hosts => ["http://127.0.0.1:9200/"]
            index => "data-4"
            document_type => "data-%{+YYYY.MM.dd}"
        }
    }

    if "data-3" in [tags] {
        elasticsearch {
            hosts => ["http://127.0.0.1:9200/"]
            index => "data-3"
            document_type => "data-%{+YYYY.MM.dd}"
        }
    }
}

This is the fun part of programming right?

Anyway, locally I am on windows as you may be able to tell from the file path to the jdbc driver library. My jdbc connection to the AWS RDS is copied and pasted from AWS Console, so no typos were involved.

I am told that I only need to append jdbc:mysql:// to the url. But is there anything I'm missing to do in the AWS console? Do I need to modify my RDS instance?

The error by the way is:

 Unable to connect to database. Tried 1 times
{:error_message=>"Java::ComMysqlCjJdbcExceptions::CommunicationsException:
Communications link failure\n\n
The last packet sent successfully to the server was 0 milliseconds ago.
The driver has not received any packets from the server."

Body:
I had a similar issue, and SSL was not enabled for communication. So, AWS RDS was not allowing to connect.

I specified an additional query param useSSL=false to JDBC connection string, and problem was solved.

So, in your case, the jdbc_connection_string would be as follows:

"jdbc:mysql://aws.ffffffffff.us-east-1.rds.amazonaws.com:3306/dbName?useSSL=false&user=userName&password=pword"


问:
Apache Camel Jetty Multipart: load text file with non-Latin charset or binary file
Camel 2.24.0

I am struggling to load a simple csv file that is not in a Latin charset, from a web form with file field:

```<code><form action="/register/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="inputfile"/>
<input type="submit"/>
</code>```

Here's my current endpoint URL:

```<code>jetty:http://0.0.0.0:{{web.port}}/register/upload?httpMethodRestrict=POST
</code>```

What happens is that the contents of the file is converted into String with multiple black question marks in place of non-Latin characters.

When I try to load a binary file like jpeg, it still puts the file contents as an ugly String into headers of the HttpMessage.

I can't see where I am asking to convert my file into String, but for a text (csv) file that would be okay if only it was able to use some charset other than the Latin-1.

I have read a lot of articles everywhere and have tried different magic to no avail. What I remember is a url query parameter to switch on/off the Multipart Filter, and in the web form  to add a hidden _charset_ field.

The Apache Jetty Component says that the Multi-part should work out of the box and even mentions some example, but unfortunately there is no hyperlink. Anyway, the HttpMessage attachments are empty, so it doesn't actually work as advertized.

So the question in simple terms is "how do I specify my endpoint URL so that I am able to get non-corrupt file contents that was uploaded through a web form, and how do I get the file contents". Or maybe, "do I have to add some attribute to the web form"

答:
You have a few things to consider.

Are all POST requests via that form going to be Windows-1251?

Does the HTML charset that the form was presented on matter to you?

Do you want the user to pick the charset?

You mentioned the "hidden charset field".  It's actually called _charset_ (with the start and end underscores present), and it's important to understand how it works with HTML forms.

That works by creating a hidden field in your form like this ...

<form method="POST"
      enctype="multipart/form-data"
      action="/formsubmit">
    <input type="hidden" name="_charset_"/>

Japanese

    <input type="text" name="japanese" value="健治"/>

Hello

    <input type="text" name="hello" value="ャユ戆タ"/>

    <input type="Submit" value="Capture">
</form>

```

<p>However, that's an incomplete example.</p>

<p>Why?  Well, that will submit via the <code>_charset_</code> form entry whatever the browser's HTML document charset is.  Which in the above example could be darn near anything and is unpredictable.</p>

<p>You could specify the Document charset as a meta entry, like this ...</p>

<pre class="lang-html prettyprint-override"><code><html>
<head>
<meta charset="utf-8">
</head>
<body>
<form ...>
</code>```

That will present the HTML in utf-8 and submit the form where the _charset_ entry is value utf-8.  (It also makes anything hand-typed into text fields on your form be UTF-8)

But wait, what if you wanted to have the form be a different charset?

You could do the following ...

<meta charset="utf-8">

<form accept-charset="windows-1251"
      method="POST"
      enctype="multipart/form-data"
      action="/formsubmit">
    <input type="hidden" name="_charset_"/>
    ...
```

<p>That will declare that all form submissions are <code>windows-1251</code>, and this is done by also submitting the <code>_charset_</code> entry with the value <code>windows-1251</code>.</p>

<p>But this means your form submissions will be <code>windows-1251</code>, which might not be feasible for some submissions.</p>

<p>You also mentioned that you are doing CSV form uploads.</p>

<p>You might want to consider doing a form file upload instead (as that will not interpret via the <code>_charset_</code> or encoding types).</p>

<pre class="lang-html prettyprint-override"><code><form method="POST"
      enctype="multipart/form-data"
      action="/formupload">
    <p>File</p>
    <input type="file" name="file"/>
    <input type="Submit" value="Capture">
</form>
</code>```

This all assumes that Apache Camel uses the HttpServletRequest.getParts()
 (and equivalent) APIs, and not something custom. (like the ancient Apache FileUpload lib).

The way the API works is that all parts of a multipart are binary and have no encoding or charset associated with them UNTIL you attempt to access it.

For <input> entries, no charset is applied via the Servlet Part API.

However, if Apache Camel uses HttpServletRequest.getParameter() style APIs, then the _charset_ is applied to the binary data held by the multipart section when returning the String.

Equivalent to ...

String charset = getPart("_charset_");
if(charset == null)
    charset = "utf-8"
try(InputStream in = getPart(keyname).getInputStream();
    InputStreamReader reader = new InputStreamReader(in, Charset.forName(charset));
    StringWriter writer = new StringWriter()) {
    IO.copy(reader, writer);
    return writer.toString();
}
```

Body:
Camel 2.24.0

I am struggling to load a simple csv file that is not in a Latin charset, from a web form with file field:

<form action="/register/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="inputfile"/>
<input type="submit"/>

Here's my current endpoint URL:

jetty:http://0.0.0.0:{{web.port}}/register/upload?httpMethodRestrict=POST

What happens is that the contents of the file is converted into String with multiple black question marks in place of non-Latin characters.

When I try to load a binary file like jpeg, it still puts the file contents as an ugly String into headers of the HttpMessage.

I can't see where I am asking to convert my file into String, but for a text (csv) file that would be okay if only it was able to use some charset other than the Latin-1.

I have read a lot of articles everywhere and have tried different magic to no avail. What I remember is a url query parameter to switch on/off the Multipart Filter, and in the web form  to add a hidden _charset_ field.

The Apache Jetty Component says that the Multi-part should work out of the box and even mentions some example, but unfortunately there is no hyperlink. Anyway, the HttpMessage attachments are empty, so it doesn't actually work as advertized.

So the question in simple terms is "how do I specify my endpoint URL so that I am able to get non-corrupt file contents that was uploaded through a web form, and how do I get the file contents". Or maybe, "do I have to add some attribute to the web form"

Body:
You have a few things to consider.

Are all POST requests via that form going to be Windows-1251?

Does the HTML charset that the form was presented on matter to you?

Do you want the user to pick the charset?

You mentioned the "hidden charset field".  It's actually called _charset_ (with the start and end underscores present), and it's important to understand how it works with HTML forms.

That works by creating a hidden field in your form like this ...

<html>
<body>
<form method="POST"
      enctype="multipart/form-data"
      action="/formsubmit">
    <input type="hidden" name="_charset_"/>
    <p>Japanese</p>
    <input type="text" name="japanese" value="健治"/>
    <p>Hello</p>
    <input type="text" name="hello" value="ャユ戆タ"/>
    <p></p>
    <input type="Submit" value="Capture">
</form>
</body>
</html>

However, that's an incomplete example.

Why?  Well, that will submit via the _charset_ form entry whatever the browser's HTML document charset is.  Which in the above example could be darn near anything and is unpredictable.

You could specify the Document charset as a meta entry, like this ...

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form ...>

That will present the HTML in utf-8 and submit the form where the _charset_ entry is value utf-8.  (It also makes anything hand-typed into text fields on your form be UTF-8)

But wait, what if you wanted to have the form be a different charset?

You could do the following ...

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form accept-charset="windows-1251"
      method="POST"
      enctype="multipart/form-data"
      action="/formsubmit">
    <input type="hidden" name="_charset_"/>
    ...

That will declare that all form submissions are windows-1251, and this is done by also submitting the _charset_ entry with the value windows-1251.

But this means your form submissions will be windows-1251, which might not be feasible for some submissions.

You also mentioned that you are doing CSV form uploads.

You might want to consider doing a form file upload instead (as that will not interpret via the _charset_ or encoding types).

<form method="POST"
      enctype="multipart/form-data"
      action="/formupload">
    <p>File</p>
    <input type="file" name="file"/>
    <input type="Submit" value="Capture">
</form>

This all assumes that Apache Camel uses the HttpServletRequest.getParts()
 (and equivalent) APIs, and not something custom. (like the ancient Apache FileUpload lib).

The way the API works is that all parts of a multipart are binary and have no encoding or charset associated with them UNTIL you attempt to access it.

For <input> entries, no charset is applied via the Servlet Part API.

However, if Apache Camel uses HttpServletRequest.getParameter() style APIs, then the _charset_ is applied to the binary data held by the multipart section when returning the String.

Equivalent to ...

String charset = getPart("_charset_");
if(charset == null)
    charset = "utf-8"
try(InputStream in = getPart(keyname).getInputStream();
    InputStreamReader reader = new InputStreamReader(in, Charset.forName(charset));
    StringWriter writer = new StringWriter()) {
    IO.copy(reader, writer);
    return writer.toString();
}


问:
Updating line in 3D plot Animation
I am trying to plot a line in a 3D animation. I cant erase the plots i created in update_line. The problem is im always adding new lines. The best solution i see is to create the lines outside of the function and updating the data of those lines, but i cant seems to find a way for plot in 3D

first time posting, just a few hours of python. Learned nothing about canvas yet. Keep it simple please

```<code>import matplotlib; matplotlib.use("TkAgg")
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
dotinline = 101
nframe = 7
fig = plt.figure(figsize=(16, 8))
ax = p3.Axes3D(fig)
ax.view_init(0, 90)

def init():
    ax.plot([-10, 10], [0, 0], [0, 0], "k")
    ax.plot([0, 0], [-10, 10], [0, 0], "k")
    ax.plot([0, 0], [0, 0], [-10, 10], "k")
    ax.plot([], [], [], "b")

def update_lines(index):
    seg = []
    x = np.linspace(-10, 10, dotinline)
    power = x**(-(nframe-1)/2+index)
    for i in range(len(x)-1):
        a = [x[i+1], x[i]]
        b = [0, 0]
        c = [power[i+1], power[i]]
        seg.append([a, b, c])
    for data in seg:
        ax.plot3D(data[0], data[1], data[2], "-b")

ax.set_xlim3d([-10, 10])
ax.set_xlabel('X')
ax.set_ylim3d([-10, 10])
ax.set_ylabel('Y')
ax.set_zlim3d([-10, 10])
ax.set_zlabel('Z')
ax.set_title('3D Test')

line_ani = animation.FuncAnimation(fig, update_lines, init_func=init, frames=nframe, interval=2000, blit=False)

plt.show()

</code>```

答:
Check this code:

```<code>import matplotlib; matplotlib.use("TkAgg")
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
dotinline = 101
nframe = 7
fig = plt.figure(figsize=(16, 8))
ax = p3.Axes3D(fig)
ax.view_init(0, 90)

def init():
    ax.plot([-10, 10], [0, 0], [0, 0], "k")
    ax.plot([0, 0], [-10, 10], [0, 0], "k")
    ax.plot([0, 0], [0, 0], [-10, 10], "k")
    ax.plot([], [], [], "b")

def update_lines(index):
    ax.cla()
    init()
    seg = []
    x = np.linspace(-10, 10, dotinline)
    power = x**(-(nframe-1)/2+index)
    for i in range(len(x)-1):
        a = [x[i+1], x[i]]
        b = [0, 0]
        c = [power[i+1], power[i]]
        seg.append([a, b, c])
    for data in seg:
        ax.plot3D(data[0], data[1], data[2], "-b")

    ax.set_xlim3d([-10, 10])
    ax.set_xlabel('X')
    ax.set_ylim3d([-10, 10])
    ax.set_ylabel('Y')
    ax.set_zlim3d([-10, 10])
    ax.set_zlabel('Z')
    ax.set_title('3D Test')

line_ani = animation.FuncAnimation(fig, update_lines, init_func=init, frames=nframe, interval=2000, blit=False)

plt.show()
</code>```

To erase the previous lines, just add ax.cla().

However, this erase also the black line axis; so, after ax.cla() I run again init(), in order to re-draw the axes lines.

Finally, it is better to move the block:

```<code>ax.set_xlim3d([-10, 10])
ax.set_xlabel('X')
ax.set_ylim3d([-10, 10])
ax.set_ylabel('Y')
ax.set_zlim3d([-10, 10])
ax.set_zlabel('Z')
ax.set_title('3D Test')
</code>```

inside the update_lines() function, in order to keep these options even when the lines are erased.

With this code, I get the following animation:

Title: Updating line in 3D plot Animation

Body:
I am trying to plot a line in a 3D animation. I cant erase the plots i created in update_line. The problem is im always adding new lines. The best solution i see is to create the lines outside of the function and updating the data of those lines, but i cant seems to find a way for plot in 3D

first time posting, just a few hours of python. Learned nothing about canvas yet. Keep it simple please

import matplotlib; matplotlib.use("TkAgg")
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
dotinline = 101
nframe = 7
fig = plt.figure(figsize=(16, 8))
ax = p3.Axes3D(fig)
ax.view_init(0, 90)

def init():
    ax.plot([-10, 10], [0, 0], [0, 0], "k")
    ax.plot([0, 0], [-10, 10], [0, 0], "k")
    ax.plot([0, 0], [0, 0], [-10, 10], "k")
    ax.plot([], [], [], "b")

def update_lines(index):
    seg = []
    x = np.linspace(-10, 10, dotinline)
    power = x**(-(nframe-1)/2+index)
    for i in range(len(x)-1):
        a = [x[i+1], x[i]]
        b = [0, 0]
        c = [power[i+1], power[i]]
        seg.append([a, b, c])
    for data in seg:
        ax.plot3D(data[0], data[1], data[2], "-b")

ax.set_xlim3d([-10, 10])
ax.set_xlabel('X')
ax.set_ylim3d([-10, 10])
ax.set_ylabel('Y')
ax.set_zlim3d([-10, 10])
ax.set_zlabel('Z')
ax.set_title('3D Test')

line_ani = animation.FuncAnimation(fig, update_lines, init_func=init, frames=nframe, interval=2000, blit=False)

plt.show()

Body:
Check this code:

import matplotlib; matplotlib.use("TkAgg")
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
dotinline = 101
nframe = 7
fig = plt.figure(figsize=(16, 8))
ax = p3.Axes3D(fig)
ax.view_init(0, 90)

def init():
    ax.plot([-10, 10], [0, 0], [0, 0], "k")
    ax.plot([0, 0], [-10, 10], [0, 0], "k")
    ax.plot([0, 0], [0, 0], [-10, 10], "k")
    ax.plot([], [], [], "b")

def update_lines(index):
    ax.cla()
    init()
    seg = []
    x = np.linspace(-10, 10, dotinline)
    power = x**(-(nframe-1)/2+index)
    for i in range(len(x)-1):
        a = [x[i+1], x[i]]
        b = [0, 0]
        c = [power[i+1], power[i]]
        seg.append([a, b, c])
    for data in seg:
        ax.plot3D(data[0], data[1], data[2], "-b")

    ax.set_xlim3d([-10, 10])
    ax.set_xlabel('X')
    ax.set_ylim3d([-10, 10])
    ax.set_ylabel('Y')
    ax.set_zlim3d([-10, 10])
    ax.set_zlabel('Z')
    ax.set_title('3D Test')

line_ani = animation.FuncAnimation(fig, update_lines, init_func=init, frames=nframe, interval=2000, blit=False)

plt.show()

To erase the previous lines, just add ax.cla().

However, this erase also the black line axis; so, after ax.cla() I run again init(), in order to re-draw the axes lines.

Finally, it is better to move the block:

ax.set_xlim3d([-10, 10])
ax.set_xlabel('X')
ax.set_ylim3d([-10, 10])
ax.set_ylabel('Y')
ax.set_zlim3d([-10, 10])
ax.set_zlabel('Z')
ax.set_title('3D Test')

inside the update_lines() function, in order to keep these options even when the lines are erased.

With this code, I get the following animation:


问:
How do I pass a variable used in a function to a variable in another function in C?
I'm making a small and simple game in C as a project for college.
In the game, there's a function in which the player will buy troops of different types for his army. Then, during the execution of the other function, the player will position the troops bought in the game scenario, but the function "needs to know" how many troops and of which type the player bought.

So basically, what I'm asking is how do I pass the value of a variable used in a function to be used in another one.

答:
example:</p>

```<code>typedef enum
{
    PLAYER_COMMAND_BUY,
    PLAYER_COMMAND_GET,
    PALYER_COMMAND_SET,
}PLAYER_COMMAND_t;

int manage_player(PLAYER_COMMAND_t command, unsigned *data)
{
    static unsigned nplayers;
    int result = 0; //OK

    switch(command)
    {
        case PLAYER_COMMAND_BUY:
            /* do something to buy players */
            /* set nplayers */
            break;
        case PLAYER_COMMAND_GET:
            *data = nplayers;
            /* do something to buy players */
            break;
        case PALYER_COMMAND_SET:
            /* do something to buy players */
            nplayers = data;
            break;
    }
    return result;
}
</code>```

Body:
example:

typedef enum
{
    PLAYER_COMMAND_BUY,
    PLAYER_COMMAND_GET,
    PALYER_COMMAND_SET,
}PLAYER_COMMAND_t;

int manage_player(PLAYER_COMMAND_t command, unsigned *data)
{
    static unsigned nplayers;
    int result = 0; //OK

    switch(command)
    {
        case PLAYER_COMMAND_BUY:
            /* do something to buy players */
            /* set nplayers */
            break;
        case PLAYER_COMMAND_GET:
            *data = nplayers;
            /* do something to buy players */
            break;
        case PALYER_COMMAND_SET:
            /* do something to buy players */
            nplayers = data;
            break;
    }
    return result;
}


问:
React typescript with react-redux component requires all passed props
So I've just started to combine react, redux (react-redux) and typescript. But I can't seem to figure out something here, namely, why the child components inside of the App component require all of the props that I pass into the App component.

App component:

```<code>const App = ({contacts, user, activeUserId}: ApplicationState) => (
    <div className="App">
        <Sidebar contacts={contacts} />
        <Main user={user} activeUserId={activeUserId}/>
    </div>
);

const getContacts = ({contacts, user, activeUserId}: ApplicationState) => ({contacts, user, activeUserId});
export default connect(getContacts)(App);
</code>```

Sidebar component:

```<code>const Sidebar = ({contacts}: ApplicationState) => {
    let contactsValues: Array<Contacts> = contacts && Object.values(contacts);

    return (
        <aside className="Sidebar">
            {contactsValues && contactsValues.map((contact: Contacts) => <User user={contact} key={contact.user_id}/>)}
        </aside>
    )
}
</code>```

I don't think there's any reason to list the Main component here as well since its only an empty component but gives the same errors, so I will just go ahead an list the Interfaces:

```<code>export default interface Contacts {
    email: string,
    name: string,
    profile_pic: string,
    status: string,
    user_id: string
}

export default interface ApplicationState {
    contacts: Contacts,
    user: object,
    activeUserId: string | null
}
</code>```

Actual error code: "TS2739: Type '{ contacts: Contacts; }' is missing the following properties from type 'ApplicationState': user, activeUserId"

So, both components ask to have all the props injected into them, even though they are not required inside the component itself. If I supply the components the everything works and I get no errors.

I'm pretty sure there's something wrong with my syntax or 'wiring' of the types.

Can we also get a explanation or a decent link to docs/materials that help us understand why this is happening?

If there is anything else that I should be including please let me know and I will provide!

Edit:

I've actually realized that its important to show the Main component too because this one also causes problems and some of the fixes you guys have suggested only fix the Sidebar component but not the Main.

Main component:

```<code>import React from "react";
import "./Main.scss";

import ApplicationState from "../../models/ApplicationState";

const Main = ({user, activeUserId}: ApplicationState) => {
    return (
        <main className="Main">
            Main Stuff
        </main>
    )
}

</code>```

Edit:

From what I've experimented with all of these answers I think the best solution would be to make everything in the interfaces optional, but if I do this then the contactsValues variable inside the Sidebar component throws: TS2322: Type 'any[] | undefined' is not assignable to type 'Contacts[]'.   Type 'undefined' is not assignable to type 'Contacts[]'..

答:
The problem is in this function

```<code>const Sidebar = ({contacts}: ApplicationState) => {
    let contactsValues: Array<Contacts> = contacts && Object.values(contacts);

    return (
        <aside className="Sidebar">
            {contactsValues && contactsValues.map((contact: Contacts) => <User user={contact} key={contact.user_id}/>)}
        </aside>
    )
}
</code>```

the type { contacts: Contacts } is not the same type ApplicationState

If you want to pass just contacts to your function you must create a new type or
make ApplicationState like this

```<code>
    export default interface ApplicationState {
        contacts: Contacts,
        user?: object,
        activeUserId?: string | null
    }

</code>```

Body:
So I've just started to combine react, redux (react-redux) and typescript. But I can't seem to figure out something here, namely, why the child components inside of the App component require all of the props that I pass into the App component.

App component:

const App = ({contacts, user, activeUserId}: ApplicationState) => (

        <Sidebar contacts={contacts} />

);

const getContacts = ({contacts, user, activeUserId}: ApplicationState) => ({contacts, user, activeUserId});
export default connect(getContacts)(App);

Sidebar component:

const Sidebar = ({contacts}: ApplicationState) => {
    let contactsValues: Array<Contacts> = contacts && Object.values(contacts);

    return (

            {contactsValues && contactsValues.map((contact: Contacts) => <User user={contact} key={contact.user_id}/>)}

    )
}

I don't think there's any reason to list the Main component here as well since its only an empty component but gives the same errors, so I will just go ahead an list the Interfaces:

export default interface Contacts {
    email: string,
    name: string,
    profile_pic: string,
    status: string,
    user_id: string
}

export default interface ApplicationState {
    contacts: Contacts,
    user: object,
    activeUserId: string | null
}

Actual error code: "TS2739: Type '{ contacts: Contacts; }' is missing the following properties from type 'ApplicationState': user, activeUserId"

So, both components ask to have all the props injected into them, even though they are not required inside the component itself. If I supply the components the everything works and I get no errors.

I'm pretty sure there's something wrong with my syntax or 'wiring' of the types.

Can we also get a explanation or a decent link to docs/materials that help us understand why this is happening?

If there is anything else that I should be including please let me know and I will provide!

Edit:

I've actually realized that its important to show the Main component too because this one also causes problems and some of the fixes you guys have suggested only fix the Sidebar component but not the Main.

Main component:

import React from "react";
import "./Main.scss";

import ApplicationState from "../../models/ApplicationState";

const Main = ({user, activeUserId}: ApplicationState) => {
    return (

            Main Stuff

    )
}

Edit:

From what I've experimented with all of these answers I think the best solution would be to make everything in the interfaces optional, but if I do this then the contactsValues variable inside the Sidebar component throws: TS2322: Type 'any[] | undefined' is not assignable to type 'Contacts[]'.   Type 'undefined' is not assignable to type 'Contacts[]'..

Body:
The problem is in this function

const Sidebar = ({contacts}: ApplicationState) => {
    let contactsValues: Array<Contacts> = contacts && Object.values(contacts);

    return (
        <aside className="Sidebar">
            {contactsValues && contactsValues.map((contact: Contacts) => <User user={contact} key={contact.user_id}/>)}
        </aside>
    )
}

the type { contacts: Contacts } is not the same type ApplicationState

If you want to pass just contacts to your function you must create a new type or
make ApplicationState like this

    export default interface ApplicationState {
        contacts: Contacts,
        user?: object,
        activeUserId?: string | null
    }


问:
overwriting react-native stylesheets styles
I have a custom react component that looks like this:

```<code>import { StyleSheet } from 'react-native';
import { Input, Item } from 'native-base';
import Icon from 'react-native-vector-icons/FontAwesome';
import { moderateScale, verticalScale } from 'react-native-size-matters';
import { styles as commonStyles } from '~/styles/RegistrationStyles';

type FieldInputProps = {
  handleChange: (e: string) => undefined;
  handleBlur: (e: string) => undefined;
  value: string;
  fieldType: string;
  placeholderText?: string;
  hidePasswordIcon?: string;
  hidePassword?: boolean;
  togglePassword?: () => void;
  icon: string;
};

export const FieldInput: React.FunctionComponent<FieldInputProps> = ({
  handleChange,
  handleBlur,
  fieldType,
  placeholderText,
  value,
  hidePassword,
  hidePasswordIcon,
  togglePassword,
  icon,
}) => {
  return (
    <Item rounded style={styles.personalListItem}>
      <Icon name={icon} size={moderateScale(20)} color="green" />
      <Input
        autoFocus={true}
        autoCapitalize="none"
        style={{ fontSize: moderateScale(15) }}
        placeholder={placeholderText}
        keyboardType="default"
        onChangeText={handleChange(fieldType)}
        onBlur={handleBlur(fieldType)}
        value={value}
        secureTextEntry={hidePassword}
      />
      {togglePassword ? (
        <Icon
          name={hidePasswordIcon}
          onPress={togglePassword}
          style={commonStyles.iconStyle}
          size={moderateScale(20)}
          color="green"
        />
      ) : null}
    </Item>
  );
};

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    backgroundColor: '#2E3331',
    flex: 1,
  },
  personalListItem: {
    width: moderateScale(320),
    backgroundColor: 'white',
    borderBottomColor: 'grey',
    borderRadius: moderateScale(10),
    height: verticalScale(50),
    paddingRight: moderateScale(20),
    paddingLeft: moderateScale(10),
    marginVertical: moderateScale(20),
  },
  text: {
    fontFamily: 'Roboto',
    fontSize: moderateScale(20),
    fontWeight: '600',
    marginVertical: moderateScale(10),
    color: '#17D041',
  },
  subtext: {
    color: '#17D041',
    fontSize: moderateScale(14),
  },
  subtextBold: {
    textDecorationLine: 'underline',
    color: '#17D041',
    fontWeight: '600',
    fontSize: moderateScale(14),
  },
  button: {
    height: moderateScale(50),
    width: moderateScale(350),
    borderRadius: moderateScale(10),
    justifyContent: 'center',
    marginBottom: moderateScale(5),
  },
  buttonText: {
    fontSize: moderateScale(15),
  },
});
</code>```

Usually when I use this component, I want to keep using this style. However, in one particular case, I want to overwrite the styles. For example, change the width or the background color of the input field etc. However, if I try to overwrite the styles, there are no changes.

```<code><FieldInput style={styles.fieldInput}
                      handleChange={handleChange}
                      handleBlur={handleBlur}
                      value={values.phoneNumber}
                      fieldType="phoneNumber"
                      icon="phone"
                      placeholderText="49152901820"
                    />

 fieldInput: {
    width: moderateScale(320),
    backgroundColor: 'red',
  },
</code>```

答:
Here you are passing the styles as a parameter, lets say you want to use it for the outer wrap, you can do it like below

```<code> <Item rounded style={[styles.personalListItem,this.props.style]}>
</code>```

If a style prop is received then it will overwrite the one in personalListItem, else it will use the styles in personalListItem.

You will have to add the style to the props, also you can add separate style props for inner components and use them the same way.

If you want to have only the style that is passed you can do this

```<code>  <Item rounded style={this.props.style||styles.personalListItem}>
</code>```

Which will use the personalListItem if a style prop is not passed

Body:
I have a custom react component that looks like this:

import { StyleSheet } from 'react-native';
import { Input, Item } from 'native-base';
import Icon from 'react-native-vector-icons/FontAwesome';
import { moderateScale, verticalScale } from 'react-native-size-matters';
import { styles as commonStyles } from '~/styles/RegistrationStyles';

type FieldInputProps = {
  handleChange: (e: string) => undefined;
  handleBlur: (e: string) => undefined;
  value: string;
  fieldType: string;
  placeholderText?: string;
  hidePasswordIcon?: string;
  hidePassword?: boolean;
  togglePassword?: () => void;
  icon: string;
};

export const FieldInput: React.FunctionComponent<FieldInputProps> = ({
  handleChange,
  handleBlur,
  fieldType,
  placeholderText,
  value,
  hidePassword,
  hidePasswordIcon,
  togglePassword,
  icon,
}) => {
  return (
    <Item rounded style={styles.personalListItem}>
      <Icon name={icon} size={moderateScale(20)} color="green" />
      <Input
        autoFocus={true}
        autoCapitalize="none"
        style={{ fontSize: moderateScale(15) }}
        placeholder={placeholderText}
        keyboardType="default"
        onChangeText={handleChange(fieldType)}
        onBlur={handleBlur(fieldType)}
        value={value}
        secureTextEntry={hidePassword}
      />
      {togglePassword ? (
        <Icon
          name={hidePasswordIcon}
          onPress={togglePassword}
          style={commonStyles.iconStyle}
          size={moderateScale(20)}
          color="green"
        />
      ) : null}
    </Item>
  );
};

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    backgroundColor: '#2E3331',
    flex: 1,
  },
  personalListItem: {
    width: moderateScale(320),
    backgroundColor: 'white',
    borderBottomColor: 'grey',
    borderRadius: moderateScale(10),
    height: verticalScale(50),
    paddingRight: moderateScale(20),
    paddingLeft: moderateScale(10),
    marginVertical: moderateScale(20),
  },
  text: {
    fontFamily: 'Roboto',
    fontSize: moderateScale(20),
    fontWeight: '600',
    marginVertical: moderateScale(10),
    color: '#17D041',
  },
  subtext: {
    color: '#17D041',
    fontSize: moderateScale(14),
  },
  subtextBold: {
    textDecorationLine: 'underline',
    color: '#17D041',
    fontWeight: '600',
    fontSize: moderateScale(14),
  },
  button: {
    height: moderateScale(50),
    width: moderateScale(350),
    borderRadius: moderateScale(10),
    justifyContent: 'center',
    marginBottom: moderateScale(5),
  },
  buttonText: {
    fontSize: moderateScale(15),
  },
});

Usually when I use this component, I want to keep using this style. However, in one particular case, I want to overwrite the styles. For example, change the width or the background color of the input field etc. However, if I try to overwrite the styles, there are no changes.

<FieldInput style={styles.fieldInput}
                      handleChange={handleChange}
                      handleBlur={handleBlur}
                      value={values.phoneNumber}
                      fieldType="phoneNumber"
                      icon="phone"
                      placeholderText="49152901820"
                    />

 fieldInput: {
    width: moderateScale(320),
    backgroundColor: 'red',
  },

Body:
Here you are passing the styles as a parameter, lets say you want to use it for the outer wrap, you can do it like below

 <Item rounded style={[styles.personalListItem,this.props.style]}>

If a style prop is received then it will overwrite the one in personalListItem, else it will use the styles in personalListItem.

You will have to add the style to the props, also you can add separate style props for inner components and use them the same way.

If you want to have only the style that is passed you can do this

  <Item rounded style={this.props.style||styles.personalListItem}>

Which will use the personalListItem if a style prop is not passed


问:
C# connecting to a database
I Am Trying to create a program using c# that needs to connect to a database running on a Solaris server, I am not too familiar with the server, we normally use dbVisualizer to connect to it. the driver it uses to connect is mysql-connector-java-5.1.10, which is a jdbc driver. was wondering what drivers to use to connect to the database using C# and what is the syntax used to establish the connection. as far as I know I will be unable to install any drivers on the server side, and i will only be able to make changes/Install what is required on the client. </p>

答:
I believe this is what you want to connect (on the server):
http://dev.mysql.com/downloads/connector/net/1.0.html

You can try your connection like this:

```<code>string MyConString = "SERVER=yourserver;" +
                "DATABASE=mydatabase;" +
                "UID=testuser;" +
                "PASSWORD=testpassword;";
            MySqlConnection connection = new MySqlConnection(MyConString);
</code>```

You would probably want to follow the normal guidelines for IDisposable classes (use using etc.).

ContentLicense: CC BY-SA 3.0

Title: C# connecting to a database

Body:
I believe this is what you want to connect (on the server):
http://dev.mysql.com/downloads/connector/net/1.0.html

You can try your connection like this:

string MyConString = "SERVER=yourserver;" +
                "DATABASE=mydatabase;" +
                "UID=testuser;" +
                "PASSWORD=testpassword;";
            MySqlConnection connection = new MySqlConnection(MyConString);

You would probably want to follow the normal guidelines for IDisposable classes (use using etc.).


问:
Select one column using Spring Data JPA
Does anyone have any idea how to get a single column using Spring Data JPA? I created a repository like below in my Spring Boot project, but always get the {"cause":null,"message":"PersistentEntity must not be null!"} error when accessing the Restful URL.

```<code>@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UsersRepository extends CrudRepository<Users, Integer> {

    @Query("SELECT u.userName  FROM Users u")
    public List<String> getUserName();
}
</code>```

Then if I access the Restful URL like ../users/search/getUserName, I get the error:
{"cause":null,"message":"PersistentEntity must not be null!"}

答:
Create a Projection interface

```<code>public interface UserNameOnly {
    String getUserName();
}
</code>```

Then in your repository interface return that type instead of the user type

```<code>public interface UserRepository<User> extends JpaRepository<User,String> {
    List<UsernameOnly> findNamesByUserNameNotNull();
}
</code>```

The get method in the projection interface must match a get method of the defined type on the JPA repository, in this case User.
The "findBySomePropertyOnTheObjectThatIsNotNull" allows you to get a List of the entities (as opposed to an Iterable) based on some criteria, which for a findAll can simply be if the unique identifier (or any other NonNull field) is not null.

Title: Select one column using Spring Data JPA

Body:
Does anyone have any idea how to get a single column using Spring Data JPA? I created a repository like below in my Spring Boot project, but always get the {"cause":null,"message":"PersistentEntity must not be null!"} error when accessing the Restful URL.

@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UsersRepository extends CrudRepository<Users, Integer> {

    @Query("SELECT u.userName  FROM Users u")
    public List<String> getUserName();
}

Then if I access the Restful URL like ../users/search/getUserName, I get the error:
{"cause":null,"message":"PersistentEntity must not be null!"}

Body:
Create a Projection interface

public interface UserNameOnly {
    String getUserName();
}

Then in your repository interface return that type instead of the user type

public interface UserRepository<User> extends JpaRepository<User,String> {
    List<UsernameOnly> findNamesByUserNameNotNull();
}

The get method in the projection interface must match a get method of the defined type on the JPA repository, in this case User.
The "findBySomePropertyOnTheObjectThatIsNotNull" allows you to get a List of the entities (as opposed to an Iterable) based on some criteria, which for a findAll can simply be if the unique identifier (or any other NonNull field) is not null.


答:
If you need to support a NULL end date, then you just need to tweak your query:

```<code>SELECT cm.[Month],
       COUNT(cft.ID) AS TasksDue
FROM #CalendarMonths cm LEFT JOIN
     #CFTasks cft
     ON cft.STARTDATE <= cm.[Month] AND
        ( cft.ENDDATE > cm.[Month] OR cft.ENDDATE IS NULL )
GROUP BY cm.[Month]
ORDER BY cm.[Month];
</code>```

Title: Count only active records for each month

Body:
I have create a temporary table of 'tasks', called #CFTasks that looks like this:

ID           STARTDATE    ENDDATE
1712060019   06/12/2017   07/12/2017
1712060019   07/12/2017   07/12/2017
1712060019   08/12/2017   08/12/2017
1712060019   07/12/2017   08/12/2017
1712060019   07/12/2017   12/12/2017
1712060019   12/12/2017   13/12/2017
1712060019   14/12/2017   14/12/2017
1712060019   07/12/2017   14/12/2017
1712060019   14/12/2017   NULL
1712060019   07/12/2017   14/12/2017
1712060019   18/12/2017   21/12/2017
1712060019   18/12/2017   21/12/2017
1712060019   19/12/2017   21/12/2017
1712060019   02/11/2018   24/09/2018
1712060019   14/09/2018   24/09/2018
1712060019   13/10/2018   05/12/2018
1712060019   13/10/2018   05/12/2018
1712060019   12/11/2018   05/12/2018
1712060019   19/12/2018   07/12/2018
1712060019   13/12/2018   07/12/2018

For each month from the 1st December 2017 to the current month, I want to know how many of these records were active, by which I mean the [STARTDATE] is less than or equal to the first of the month and the [ENDDATE] is greater than the first of the month or the [ENDDATE] is NULL

i.e.

[DUEDATE] <= @StartOfMonth
 AND (    [ENDDATE] >= @StartOfMonth
           OR [ENDDATE] IS NULL
     )

For the sample task table provided, I'd expect the output to look like:

Month        ActiveTasks
01/12/2017   0
01/01/2018   1
01/02/2018   1
01/03/2018   1
01/04/2018   1
01/05/2018   1
01/06/2018   1
01/07/2018   1
01/08/2018   1
01/09/2018   1
01/10/2018   1
01/11/2018   3
01/12/2018   4

I've created a date table too, so that I can get a count even where there are no active tasks on a particular reporting date but I can't find a way to join the two tables in such a way that I get the desired result.

My date table is created like this:

DROP TABLE IF EXISTS #CalendarMonths
DECLARE @StartDate  date
SELECT @StartDate = '20171201';

DECLARE @CutoffDate date = getdate()

;WITH seq(n) AS
(
  SELECT 0 UNION ALL SELECT n + 1 FROM seq
  WHERE n < DATEDIFF(MONTH, @StartDate, @CutoffDate)
),
m(m) AS
(
  SELECT DATEADD(MONTH, n, @StartDate) FROM seq
)
SELECT m AS [Month]
INTO #CalendarMonths
FROM m
ORDER BY m
OPTION (MAXRECURSION 0);

I've tried joining the two tables in every way I can think of but I'm always stuck with the fact that I don't actually want to group the output by the [STARTDATE] or [ENDDATE] but rather by the reporting date and the fact that I want NULLs to be considered active from the start date onward.

The closest I've managed to get (meaning the query doesn't simply fail) is the below. The problem is I know I'm going down a blind alley and that this approach just won't work, no matter how much I tweak it but I just can't construct the problem in a way my brain can solve it in SQL. In Excel the same task would take me a couple of minutes but I'm working with over 600,000 rows and Excel just isn't the right tool for the job.

SELECT cm.[Month],
       COUNT(cft.ID) AS TasksDue
FROM #CalendarMonths cm
LEFT JOIN #CFTasks cft ON cft.STARTDATE <= cm.[Month]
                       AND cft.ENDDATE > cm.[Month]
GROUP BY cm.[Month]
ORDER BY cm.[Month]

Body:
If you need to support a NULL end date, then you just need to tweak your query:

SELECT cm.[Month],
       COUNT(cft.ID) AS TasksDue
FROM #CalendarMonths cm LEFT JOIN
     #CFTasks cft
     ON cft.STARTDATE <= cm.[Month] AND
        ( cft.ENDDATE > cm.[Month] OR cft.ENDDATE IS NULL )
GROUP BY cm.[Month]
ORDER BY cm.[Month];


问:
How to get the node a jstree context menu was triggered on?
Trying to get a jstree contextmenu up to trigger node-specific actions. Very helpful for starters: Doc to jstree.defaults.contextmenu.items

Sadly, one of the most interesting points is incomplete: What parameters are served to the action function assigned? Doing experiments, I already found it apparently has only one parameter (at least parameter 2 was undefined).

I progressed to connect action to

```<code>function action_on_context(data)
{
    let s = '';
    $.each(data, function(key, val) { s+=key + '=>' + Object.keys(val) + ', '});
    console.log("Context Action: " + s);
}
</code>```

Which yields me

```<code>Context Action:
  item => icon,label,title,action,
  reference => 0,length,prevObject,
  element => 0,length,
  position => x,y,
</code>```

item: As the name says, just the config I gave to the menu option.

reference: Appears to relate to the link connected to the node.

element: Apparently is the li tag of the context menu option itself.

position: Is this the x,y mouse coordinates?

So far reference is my best hunch:

```<code>console.log(data.reference.attr('id'));
</code>```

logs me the id of the anchor that seems to equal <tree_node_id_the_context_menu_was_opened_on>_anchor.

The question boils down to: "Is there a better way to obtain the node the context menu was opened on?"

答:
I think, I can answer my own question:

reference actually is the anchor embedded within the
 that defines the HTML making up the tree entry the context menu was opened upon.

Thus this parenting
 element holds the id attribute of the tree node. And since reference is presented as a JQuery object, all I need is the jquery command

```<code>data.reference.parent().attr('id');
</code>```

Body:
Trying to get a jstree contextmenu up to trigger node-specific actions. Very helpful for starters: Doc to jstree.defaults.contextmenu.items

Sadly, one of the most interesting points is incomplete: What parameters are served to the action function assigned? Doing experiments, I already found it apparently has only one parameter (at least parameter 2 was undefined).

I progressed to connect action to

function action_on_context(data)
{
    let s = '';
    $.each(data, function(key, val) { s+=key + '=>' + Object.keys(val) + ', '});
    console.log("Context Action: " + s);
}

Which yields me

Context Action:
  item => icon,label,title,action,
  reference => 0,length,prevObject,
  element => 0,length,
  position => x,y,

item: As the name says, just the config I gave to the menu option.

reference: Appears to relate to the link connected to the node.

element: Apparently is the li tag of the context menu option itself.

position: Is this the x,y mouse coordinates?

So far reference is my best hunch:

console.log(data.reference.attr('id'));

logs me the id of the anchor that seems to equal <tree_node_id_the_context_menu_was_opened_on>_anchor.

The question boils down to: "Is there a better way to obtain the node the context menu was opened on?"

Body:
I think, I can answer my own question:

reference actually is the anchor embedded within the <li> that defines the HTML making up the tree entry the context menu was opened upon.

Thus this parenting <li> element holds the id attribute of the tree node. And since reference is presented as a JQuery object, all I need is the jquery command

data.reference.parent().attr('id');


问:
More than one table found in namespace (, ) - SchemaExtractionException
I have been facing this weird exception while trying to persist some values into a  table using Hibernate in a Java application. However this exception occurs only for one particular table/entity for rest of the tables i am able to perform crud operations via Hibernate.

Please find below the Stacktrace and let me know if this is anyway related to java code is or its a database design error.

```<code> 2016-04-28 11:52:34 ERROR XXXXXDao:44 - Failed to create sessionFactory object.org.hibernate.tool.schema.extract.spi.SchemaExtractionException: More than one table found in namespace (, ) : YYYYYYY
Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.XX.dao.XXXXXXXDao.main(XXXXXXXXDao.java:45)
Caused by: org.hibernate.tool.schema.extract.spi.SchemaExtractionException: More than one table found in namespace (, ) : YYYYYYY
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults(InformationExtractorJdbcDatabaseMetaDataImpl.java:381)
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getTable(InformationExtractorJdbcDatabaseMetaDataImpl.java:279)
    at org.hibernate.tool.schema.internal.exec.ImprovedDatabaseInformationImpl.getTableInformation(ImprovedDatabaseInformationImpl.java:109)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.performMigration(SchemaMigratorImpl.java:252)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:137)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:110)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:176)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:64)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:458)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
    at com.xx.dao.zzzzzzzzzzzzDAOFactory.configureSessionFactory(zzzzzzzDAOFactory.java:43)
    at com.xx.dao.zzzzzzzzzzzzDAOFactory.buildSessionFactory(zzzzzzzzzDAOFactory.java:27)
    at com.xx.dao.XXXXXXXXDao.main(XXXXXXXXDao.java:41)
</code>```

Thanks in advance for your help

答: So after having the same issue, it turns out that I needed to update my OJDBC driver from ojdbc6 to ojdbc8. Hopefully this helps. </p>

Body:
I have been facing this weird exception while trying to persist some values into a  table using Hibernate in a Java application. However this exception occurs only for one particular table/entity for rest of the tables i am able to perform crud operations via Hibernate.

Please find below the Stacktrace and let me know if this is anyway related to java code is or its a database design error.

 2016-04-28 11:52:34 ERROR XXXXXDao:44 - Failed to create sessionFactory object.org.hibernate.tool.schema.extract.spi.SchemaExtractionException: More than one table found in namespace (, ) : YYYYYYY
Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.XX.dao.XXXXXXXDao.main(XXXXXXXXDao.java:45)
Caused by: org.hibernate.tool.schema.extract.spi.SchemaExtractionException: More than one table found in namespace (, ) : YYYYYYY
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults(InformationExtractorJdbcDatabaseMetaDataImpl.java:381)
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getTable(InformationExtractorJdbcDatabaseMetaDataImpl.java:279)
    at org.hibernate.tool.schema.internal.exec.ImprovedDatabaseInformationImpl.getTableInformation(ImprovedDatabaseInformationImpl.java:109)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.performMigration(SchemaMigratorImpl.java:252)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:137)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:110)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:176)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:64)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:458)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
    at com.xx.dao.zzzzzzzzzzzzDAOFactory.configureSessionFactory(zzzzzzzDAOFactory.java:43)
    at com.xx.dao.zzzzzzzzzzzzDAOFactory.buildSessionFactory(zzzzzzzzzDAOFactory.java:27)
    at com.xx.dao.XXXXXXXXDao.main(XXXXXXXXDao.java:41)

Thanks in advance for your help


问:
Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"
After years of working OK, I'm suddenly getting this message when trying to start the JVM:

```<code>Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'
</code>```

I tried uninstalling, and got a message saying a DLL was missing (unspecified)
Tried re-installing, all to no avail.

At the same time, when trying to start Scala I get:

```<code>\Java\jdk1.6.0_25\bin\java.exe was unexpected at this time.
</code>```

Checked %JAVA_HOME% and %path% - both OK

Can anyone help?

答:
Might be a slightly different cause, but that second issue occurs for me in scala 2.9.0.1 on Win7 (x64), though scala-2.9.1.final has already resolved this issue mentioned here:

```<code>\Java\jdk1.6.0_25\bin\java.exe was unexpected at this time.
</code>```

My %JAVA_HOME% set to a path like this: c:\program files(x86)\Java\jdk...

Note the space and the parentheses.

If you change line 24 in %SCALA_HOME%\bin\scala.bat from:

```<code>if exist "%JAVA_HOME%\bin\java.exe" set _JAVACMD=%JAVA_HOME%\bin\java.exe
</code>```

to

```<code>if exist "%JAVA_HOME%\bin\java.exe" set "_JAVACMD=%JAVA_HOME%\bin\java.exe"
</code>```

It works fine. Note the quotes around the set command parameters, this will properly enclose any spaces and 'special' characters (eg: spaces and parentheses) in the variable's value.

Hope this helps someone else searching for an answer.

Body:
After years of working OK, I'm suddenly getting this message when trying to start the JVM:

Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'

I tried uninstalling, and got a message saying a DLL was missing (unspecified)
Tried re-installing, all to no avail.

At the same time, when trying to start Scala I get:

\Java\jdk1.6.0_25\bin\java.exe was unexpected at this time.

Checked %JAVA_HOME% and %path% - both OK

Can anyone help?

Body:
Might be a slightly different cause, but that second issue occurs for me in scala 2.9.0.1 on Win7 (x64), though scala-2.9.1.final has already resolved this issue mentioned here:

\Java\jdk1.6.0_25\bin\java.exe was unexpected at this time.

My %JAVA_HOME% set to a path like this: c:\program files(x86)\Java\jdk...

Note the space and the parentheses.

If you change line 24 in %SCALA_HOME%\bin\scala.bat from:

if exist "%JAVA_HOME%\bin\java.exe" set _JAVACMD=%JAVA_HOME%\bin\java.exe

to

if exist "%JAVA_HOME%\bin\java.exe" set "_JAVACMD=%JAVA_HOME%\bin\java.exe"

It works fine. Note the quotes around the set command parameters, this will properly enclose any spaces and 'special' characters (eg: spaces and parentheses) in the variable's value.

Hope this helps someone else searching for an answer.


问:
Unable to pull Looker chart (view) into Databricks using Looker API
My goal is to access views or charts I have stored in my Looker folder and add those automatically to power point slides. The tutorial I am following is this one:
https://discourse.looker.com/t/generating-a-powerpoint-presentation-from-all-looks-in-a-space/8191.

My problem is at the point #Generate the PowerPoint (as per tutorial). When I run that command, the failure message states:

```<code>    103 chart_test
    Look failed 103: chart_test
    Failed to add image to slide

This corresponds to this piece of code where it fails:

try:
    image = looker_client.LookApi(client).run_look(**look_request)
    image_file = ''.join([str(look.id), '.png'])
    shutil.move(image, image_file)
except:
    print(f'Look failed {look.id}: {look.title}')
    image_file = None
</code>```

When I print 'image_file', is empty ('None') although I have one line chart saved in this folder 2703 called 'chart_test'.

Can someone help please?

答:
Check your parameters
Example

```<code>look_request = {
            "look_id": 21,
            "result_format": 'png',
            "image_width": 960,
            "image_height": 540
        }
</code>```

Try to use last sdk

```<code>import looker_sdk
import shutil
from looker_sdk import models
sdk = looker_sdk.init40("looker.ini")
look_request = {
            "look_id": 21,
            "result_format": 'html',
            "image_width": 960,
            "image_height": 540
        }

try:
    image1 = sdk.run_look(**look_request)
    image_file1 = '21.png'
    shutil.move(image1, image_file1)
except Exception as e:
    print(e)
</code>```

You should a file looker.ini in the same folder with your py file.

Body:
My goal is to access views or charts I have stored in my Looker folder and add those automatically to power point slides. The tutorial I am following is this one:
https://discourse.looker.com/t/generating-a-powerpoint-presentation-from-all-looks-in-a-space/8191.

My problem is at the point #Generate the PowerPoint (as per tutorial). When I run that command, the failure message states:

    103 chart_test
    Look failed 103: chart_test
    Failed to add image to slide

This corresponds to this piece of code where it fails:

try:
    image = looker_client.LookApi(client).run_look(**look_request)
    image_file = ''.join([str(look.id), '.png'])
    shutil.move(image, image_file)
except:
    print(f'Look failed {look.id}: {look.title}')
    image_file = None

When I print 'image_file', is empty ('None') although I have one line chart saved in this folder 2703 called 'chart_test'.

Can someone help please?

Body:
Check your parameters
Example

look_request = {
            "look_id": 21,
            "result_format": 'png',
            "image_width": 960,
            "image_height": 540
        }

Try to use last sdk

import looker_sdk
import shutil
from looker_sdk import models
sdk = looker_sdk.init40("looker.ini")
look_request = {
            "look_id": 21,
            "result_format": 'html',
            "image_width": 960,
            "image_height": 540
        }

try:
    image1 = sdk.run_look(**look_request)
    image_file1 = '21.png'
    shutil.move(image1, image_file1)
except Exception as e:
    print(e)

You should a file looker.ini in the same folder with your py file.


问:
NSUserDefaults Saving Score
I am looking for some advice when it comes to saving a score in my app - I currently have a coin count working in which through my HUD class when I collide through Coins the value increases accordingly. My next step is trying to initiate a high-score that initiates, after some research I think the topic I am looking into is based around NSUserDefaults..

The current code :

```<code>   import SpriteKit

   class HUD: SKNode {

   //An SKLabelNode to print the coin score:
   let coinCountText = SKLabelNode(text: "000000")

   func createHUDNodes(){

   // Configure the coin text label:
   coinCountText.fontName = "STHupo-Heavy-Italic"
   let coinTextPosition = CGPoint(x: -cameraOrigin.x + 770, y: coinPosition.y)
   coinCountText.position = coinTextPosition

   coinCountText.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.left
   coinCountText.verticalAlignmentMode = SKLabelVerticalAlignmentMode.center

   // Add the text label and coin icon to the HUD:
   self.addChild(coinCountText)

   }

   func setCoinCountDisplay(newCoinCount:Int) {

   let formatter = NumberFormatter()
   let number = NSNumber(value: newCoinCount)
   formatter.minimumIntegerDigits = 6
   if let coinStr =
        formatter.string(from: number) {

        // Update the label node with the new count:
        coinCountText.text = coinStr
    }
}
</code>```

Working in the HUD class I think naturally I would need to create another 'SKlabelNode'for the highscore node which I can duplicate from the code that works above.. my problem is how can I implement a highscore feature in the app, as when closed and re-opening the application it will remember the highscore..

I assume the following code would need to be added but I do not understand how it ties together in the class.

```<code>     var currentHighScore =
     NSUserDefaults.standardUserDefaults().integerForKey("coin_highscore")

     var highScoreLabel = SKLabelNode(fontNamed:"STHupo-Heavy-Italic")
     highScoreLabel.text = ""
     highScoreLabel.fontSize = 45
     highScoreLabel.position = CGPoint(x: viewSize.width * 0.5, y: viewSize.height * 0.30)
     self.addChild(highScoreLabel)

     if (score > currentHighScore) {

        NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "player_highscore")
        NSUserDefaults.standardUserDefaults().synchronize()

        highScoreLabel.text = "New High Score: \(score) !"

    } else {

        highScoreLabel.text = "Better Luck Next Time: \(score)"
    }
}
</code>```

Any advice on how I could integrate this code would be much appreciated.

,  AJ

Revised :

```<code>     else if nodeTouched.name == "returnToMenu"{
     // Transition to the main menu scene
     self.view?.presentScene(MenuScene(size: self.size),transition.crossFade(withDuration: 0.6))

     let currentHighScore = UserDefaults.standard.integer(forKey: "Player_highscore")

     let highScoreLabel = SKLabelNode(fontNamed:"STHupo-Heavy-Italic")
     highScoreLabel.text = "Value: \ (String(describing: coin.value))"
     highScoreLabel.text = ""
     highScoreLabel.fontSize = 45
     highScoreLabel.zPosition = 100
     highScoreLabel.position = CGPoint(x: 50, y: 50)

     self.addChild(highScoreLabel)

     if (coin.value > currentHighScore) {

     UserDefaults.standard.set(coin.value, forKey: "Player_highscore")

     UserDefaults.standard.synchronize()

     highScoreLabel.text = "New High Value: \(String(describing: coin.value)) !"

     } else {

     highScoreLabel.text = "Better Luck Next Time: \(String(describing: coin.value))"

                            }
                    }
            }

}
</code>```

I am assuming it's the referencing to my original HUD that is causing the problem? In my coin class I declared the coin.value = 5, each time the coin is collected by coinCountDisplay increases accordingly. However still does not show - :/

答:
Extending on Frankenstein's answer, IF you want to use Swift 5 you can use Property Wrappers to avoid writing get and set every time:

```<code>@propertyWrapper struct UserDefaultsBacked<Value> {
    let key: String
    let defaultValue: Value
    var storage: UserDefaults = .standard

    var wrappedValue: Value {
        get {
            let value = storage.value(forKey: key) as? Value
            return value ?? defaultValue
        }
        set {
            storage.setValue(newValue, forKey: key)
        }
    }
}
</code>```

And use it like this:

```<code>@UserDefaultsBacked(key: "coin_highscore", defaultValue: 0)
var coinHighscore: Int
</code>```

Title: NSUserDefaults Saving Score

Body:
I am looking for some advice when it comes to saving a score in my app - I currently have a coin count working in which through my HUD class when I collide through Coins the value increases accordingly. My next step is trying to initiate a high-score that initiates, after some research I think the topic I am looking into is based around NSUserDefaults..

The current code :

   import SpriteKit

   class HUD: SKNode {

   //An SKLabelNode to print the coin score:
   let coinCountText = SKLabelNode(text: "000000")

   func createHUDNodes(){

   // Configure the coin text label:
   coinCountText.fontName = "STHupo-Heavy-Italic"
   let coinTextPosition = CGPoint(x: -cameraOrigin.x + 770, y: coinPosition.y)
   coinCountText.position = coinTextPosition

   coinCountText.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.left
   coinCountText.verticalAlignmentMode = SKLabelVerticalAlignmentMode.center

   // Add the text label and coin icon to the HUD:
   self.addChild(coinCountText)

   }

   func setCoinCountDisplay(newCoinCount:Int) {

   let formatter = NumberFormatter()
   let number = NSNumber(value: newCoinCount)
   formatter.minimumIntegerDigits = 6
   if let coinStr =
        formatter.string(from: number) {

        // Update the label node with the new count:
        coinCountText.text = coinStr
    }
}

Working in the HUD class I think naturally I would need to create another 'SKlabelNode'for the highscore node which I can duplicate from the code that works above.. my problem is how can I implement a highscore feature in the app, as when closed and re-opening the application it will remember the highscore..

I assume the following code would need to be added but I do not understand how it ties together in the class.

     var currentHighScore =
     NSUserDefaults.standardUserDefaults().integerForKey("coin_highscore")

     var highScoreLabel = SKLabelNode(fontNamed:"STHupo-Heavy-Italic")
     highScoreLabel.text = ""
     highScoreLabel.fontSize = 45
     highScoreLabel.position = CGPoint(x: viewSize.width * 0.5, y: viewSize.height * 0.30)
     self.addChild(highScoreLabel)

     if (score > currentHighScore) {

        NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "player_highscore")
        NSUserDefaults.standardUserDefaults().synchronize()

        highScoreLabel.text = "New High Score: \(score) !"

    } else {

        highScoreLabel.text = "Better Luck Next Time: \(score)"
    }
}

Any advice on how I could integrate this code would be much appreciated.

,  AJ

Revised :

     else if nodeTouched.name == "returnToMenu"{
     // Transition to the main menu scene
     self.view?.presentScene(MenuScene(size: self.size),transition.crossFade(withDuration: 0.6))

     let currentHighScore = UserDefaults.standard.integer(forKey: "Player_highscore")

     let highScoreLabel = SKLabelNode(fontNamed:"STHupo-Heavy-Italic")
     highScoreLabel.text = "Value: \ (String(describing: coin.value))"
     highScoreLabel.text = ""
     highScoreLabel.fontSize = 45
     highScoreLabel.zPosition = 100
     highScoreLabel.position = CGPoint(x: 50, y: 50)

     self.addChild(highScoreLabel)

     if (coin.value > currentHighScore) {

     UserDefaults.standard.set(coin.value, forKey: "Player_highscore")

     UserDefaults.standard.synchronize()

     highScoreLabel.text = "New High Value: \(String(describing: coin.value)) !"

     } else {

     highScoreLabel.text = "Better Luck Next Time: \(String(describing: coin.value))"

                            }
                    }
            }

}

I am assuming it's the referencing to my original HUD that is causing the problem? In my coin class I declared the coin.value = 5, each time the coin is collected by coinCountDisplay increases accordingly. However still does not show - :/

Body:
Extending on Frankenstein's answer, IF you want to use Swift 5 you can use Property Wrappers to avoid writing get and set every time:

@propertyWrapper struct UserDefaultsBacked<Value> {
    let key: String
    let defaultValue: Value
    var storage: UserDefaults = .standard

    var wrappedValue: Value {
        get {
            let value = storage.value(forKey: key) as? Value
            return value ?? defaultValue
        }
        set {
            storage.setValue(newValue, forKey: key)
        }
    }
}

And use it like this:

@UserDefaultsBacked(key: "coin_highscore", defaultValue: 0)
var coinHighscore: Int