答:
Try this</p>

```<code>DECLARE @tblItemType as TAble(ID int,ItemType varchar(50))
Declare @Items AS TABLE(Id int, ItemType varchar(20), Size int)
INSERT INTO @tblItemType VALUES (1,'Tyre'),(2,'Nozle'),(3,'Brake'),(4,'Headlight'),(5,'KickPad'),(6,'Battery'),(7,'Seat')
INSERT INTO @Items VALUES (1, 'Tyre', 17), (2,'Battery', 3)

;WITH temps AS
(
   SELECT tit.ItemType, ISNULL(i.Size ,0) AS Size, row_number() over(PARTITION BY tit.ItemType ORDER BY i.Id)  AS RowIndex
   FROM @tblItemType tit
   LEFT JOIN @Items i ON tit.ItemType = i.ItemType
)
SELECT t.ItemType, t.Size FROM temps t WHERE t.RowIndex = 1
</code>```

Title: How to select Item Type with right join

Body:
Try this

DECLARE @tblItemType as TAble(ID int,ItemType varchar(50))
Declare @Items AS TABLE(Id int, ItemType varchar(20), Size int)
INSERT INTO @tblItemType VALUES (1,'Tyre'),(2,'Nozle'),(3,'Brake'),(4,'Headlight'),(5,'KickPad'),(6,'Battery'),(7,'Seat')
INSERT INTO @Items VALUES (1, 'Tyre', 17), (2,'Battery', 3)

;WITH temps AS
(
   SELECT tit.ItemType, ISNULL(i.Size ,0) AS Size, row_number() over(PARTITION BY tit.ItemType ORDER BY i.Id)  AS RowIndex
   FROM @tblItemType tit
   LEFT JOIN @Items i ON tit.ItemType = i.ItemType
)
SELECT t.ItemType, t.Size FROM temps t WHERE t.RowIndex = 1


来源: stackexchange

问:
Issue using While+if statements together in Python
Can someone please check below code, as i am using while and If statement together in python and calling one more python code, but it is executing all the code except calling the other python code.</p>

```<code>import os
import psycopg2
import os.path
import subprocess
import sys

if os.path.isfile("Z:\\xyz\\New.xlsx"):
    while True:
        conn = psycopg2.connect(database="gp_bdl", user="adwed1", password="***", host="bdlgp12", port="6200")
        cur = conn.cursor()
        print ("Opened database successfully")
        try:
            cur.execute('''select function1();''')
            conn.commit()
            conn.close()

        except psycopg2.OperationalError:
            continue
        break;
        if os.path.isfile("Z:\\xyz\\second.xlsx"):
         print("Next has started")
         subprocess.call([sys.executable,'Next Python.py'])
    else:
         print("Nothing")
else:
   print("No Process")*
</code>```

答:
Why does your code don't work? Answer:

Break breaks the whole loop, remove it!

Replace "continue" with "pass"

Remove that tiny * in "print("No Process")*"

No semicolons in Python!

Fixed code:

```<code>import os
import psycopg2
import os.path
import subprocess
import sys

if os.path.isfile("Z:\\xyz\\New.xlsx"):
    while True:
        conn = psycopg2.connect(database="gp_bdl", user="adwed1",password="***", host="bdlgp12", port="6200")
        cur = conn.cursor()
        print ("Opened database successfully")
        try:
            cur.execute('''select function1();''')
            conn.commit()
            conn.close()

        except psycopg2.OperationalError:
            continue
        break
        if os.path.isfile("Z:\\xyz\\second.xlsx"):
            print("Next has started")
            subprocess.call([sys.executable,'Next Python.py'])
    else:
         print("Nothing")
else:
   print("No Process")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Can someone please check below code, as i am using while and If statement together in python and calling one more python code, but it is executing all the code except calling the other python code.

import os
import psycopg2
import os.path
import subprocess
import sys

if os.path.isfile("Z:\\xyz\\New.xlsx"):
    while True:
        conn = psycopg2.connect(database="gp_bdl", user="adwed1", password="***", host="bdlgp12", port="6200")
        cur = conn.cursor()
        print ("Opened database successfully")
        try:
            cur.execute('''select function1();''')
            conn.commit()
            conn.close()

        except psycopg2.OperationalError:
            continue
        break;
        if os.path.isfile("Z:\\xyz\\second.xlsx"):
         print("Next has started")
         subprocess.call([sys.executable,'Next Python.py'])
    else:
         print("Nothing")
else:
   print("No Process")*

Body:
Why does your code don't work? Answer:

Break breaks the whole loop, remove it!

Replace "continue" with "pass"

Remove that tiny * in "print("No Process")*"

No semicolons in Python!

Fixed code:

import os
import psycopg2
import os.path
import subprocess
import sys

if os.path.isfile("Z:\\xyz\\New.xlsx"):
    while True:
        conn = psycopg2.connect(database="gp_bdl", user="adwed1",password="***", host="bdlgp12", port="6200")
        cur = conn.cursor()
        print ("Opened database successfully")
        try:
            cur.execute('''select function1();''')
            conn.commit()
            conn.close()

        except psycopg2.OperationalError:
            continue
        break
        if os.path.isfile("Z:\\xyz\\second.xlsx"):
            print("Next has started")
            subprocess.call([sys.executable,'Next Python.py'])
    else:
         print("Nothing")
else:
   print("No Process")


问:
Backspace doesn't work in Visual Studio
I keep getting a very annoying problem in Visual Studio.  When I try to delete some text by pressing backspace it doesn't work.  Why is this?  What is going on?  Sometimes I have to close and open Visual Studio to make this problem go away but I just tried that right now and it didn't work.  Backspace works in Notepad in case you are wondering.</p>

答:
Try resetting your Visual Studio Settings

Go to :

```<code>All Program > Visual Studio 20xx > Visual Studio Tools
</code>```

Run Developer Command Prompt for VS20xx as Administrator and this command:

devenv.exe /resetsettings

Title: Backspace doesn't work in Visual Studio

Body:
Try resetting your Visual Studio Settings

Go to :

All Program > Visual Studio 20xx > Visual Studio Tools

Run Developer Command Prompt for VS20xx as Administrator and this command:

devenv.exe /resetsettings


问:
convert two dimensional array to object array without duplicates
I have a two dimensional array of colors:

```<code>var colors = [["Blue", "Red"],["Green","Red"],["Black","Orange"],["Red", "Blue"]]
</code>```

I want to turn this into an object array and I've successfully done so using a .map

```<code>obj = colors.map(function(x) {return
{
    "color1": x[0],
    "color2": x[1]
}});
</code>```

However I want the new object array to exclude duplicates and just be a list of the colors mentioned (instead of color1 and color2, combine into one). New array should have the format:

```<code>[{"color": Blue},
 {"color": Red},
 {"color": Green},
 {"color": Black},
 {"color": Orange}]
</code>```

How can I achieve this?

答:
You can use js Set to remove duplicate instance from Array.

var colors = [["Blue", "Red"],["Green","Red"],["Black","Orange"],["Red", "Blue"]];
//Merge array
var merged = [].concat.apply([], colors);
//Remove duplicates
var removeDuplicates = Array.from( new Set(merged));
//create the array of object
var o = removeDuplicates.map(function(obj) {
  return {"color":obj};
});

console.log(o);```

fiddle

Body:
I have a two dimensional array of colors:

var colors = [["Blue", "Red"],["Green","Red"],["Black","Orange"],["Red", "Blue"]]

I want to turn this into an object array and I've successfully done so using a .map

obj = colors.map(function(x) {return
{
    "color1": x[0],
    "color2": x[1]
}});

However I want the new object array to exclude duplicates and just be a list of the colors mentioned (instead of color1 and color2, combine into one). New array should have the format:

[{"color": Blue},
 {"color": Red},
 {"color": Green},
 {"color": Black},
 {"color": Orange}]

How can I achieve this?

Body:
You can use js Set to remove duplicate instance from Array.

var colors = [["Blue", "Red"],["Green","Red"],["Black","Orange"],["Red", "Blue"]];
//Merge array
var merged = [].concat.apply([], colors);
//Remove duplicates
var removeDuplicates = Array.from( new Set(merged));
//create the array of object
var o = removeDuplicates.map(function(obj) {
  return {"color":obj};
});

console.log(o);

fiddle


问:
How to show selected values sent from Controller as List of Objects?
AddTruck.jsp Page form below:

```<code>    <form:form method="post" modelAttribute="truckDto" action="myController">

       <form:checkbox path="operatingDays[0].weekDays"
value="MONDAY" class="weekday" id="weekday-mon"/>

       <form:checkbox path="operatingDays[1].weekDays"
value="TUESDAY" class="weekday" id="weekday-tue"/>
</code>```

// likewise its for all days of week till sunday and the index of operatingDays keeps incrementing till end of week.

TruckDto has following property of ArrayList of Objects:

```<code>private List<TruckOperatingDays> operatingDays = new ArrayList<TruckOperatingDays>();
//getter setter below
</code>```

TruckOperatingDays POJO has following properties with their getter-setter methods:

```<code>@Enumerated(EnumType.STRING)
    @Column(name = "week_days")
    private WeekDaysEnum weekDays;

    @Column(name = "opening_hours")
    private String openingHours;

    @Column(name = "closing_hours")
    private String closingHours;
</code>```

When I submit the form, I get values in my controller as needed and I can save the values to my database with no issues. The problem is at the "Edit" time.
When I open this page to edit the values that has been saved previously in database, I fail to get the checkboxes already selected because of the index positions of operatingDays are static in the form and the ArrayList passed from controller doesn't set values to my input fields/checkboxes in the form.

Please note that I cannot use JSTL foreach loop to generate the form fields from the ArrayList because I need to show labels too as Monday, Tuesday etc.

Is there any way through which my form fields can automatically bind through my DTO proeprties just like we can bind simple input fields with no issues?

答:
You can still use JSTL , just add an additional list to store the week days into (NOTE: this example assumes that your ArrayList returns all 7 days but some days may be null( not selected)).

```<code><%
    String[] days = new String[]{ "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY" };
pageContext.setAttribute("wDays", days);
    %>
//and then use JSTL
<c:forEach items=${operatingDays} var="day", varStatus="counter">
   <form:checkbox path=${day.weekDays}
   value=${wDays[counter]} class="weekday" id="weekday-mon"/>
</c:forEach>
</code>```

If you would like to avoid scriptlets, you can use <c:set> in your JSP page to populate the week days list or just populate the days list in your Java code (not in JSP)

Body:
AddTruck.jsp Page form below:

    <form:form method="post" modelAttribute="truckDto" action="myController">

       <form:checkbox path="operatingDays[0].weekDays"
value="MONDAY" class="weekday" id="weekday-mon"/>

       <form:checkbox path="operatingDays[1].weekDays"
value="TUESDAY" class="weekday" id="weekday-tue"/>

// likewise its for all days of week till sunday and the index of operatingDays keeps incrementing till end of week.

TruckDto has following property of ArrayList of Objects:

private List<TruckOperatingDays> operatingDays = new ArrayList<TruckOperatingDays>();
//getter setter below

TruckOperatingDays POJO has following properties with their getter-setter methods:

@Enumerated(EnumType.STRING)
    @Column(name = "week_days")
    private WeekDaysEnum weekDays;

    @Column(name = "opening_hours")
    private String openingHours;

    @Column(name = "closing_hours")
    private String closingHours;

When I submit the form, I get values in my controller as needed and I can save the values to my database with no issues. The problem is at the "Edit" time.
When I open this page to edit the values that has been saved previously in database, I fail to get the checkboxes already selected because of the index positions of operatingDays are static in the form and the ArrayList passed from controller doesn't set values to my input fields/checkboxes in the form.

Please note that I cannot use JSTL foreach loop to generate the form fields from the ArrayList because I need to show labels too as Monday, Tuesday etc.

Is there any way through which my form fields can automatically bind through my DTO proeprties just like we can bind simple input fields with no issues?

Body:
You can still use JSTL , just add an additional list to store the week days into (NOTE: this example assumes that your ArrayList returns all 7 days but some days may be null( not selected)).

<%
    String[] days = new String[]{ "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY" };
pageContext.setAttribute("wDays", days);
    %>
//and then use JSTL
<c:forEach items=${operatingDays} var="day", varStatus="counter">
   <form:checkbox path=${day.weekDays}
   value=${wDays[counter]} class="weekday" id="weekday-mon"/>
</c:forEach>

If you would like to avoid scriptlets, you can use <c:set> in your JSP page to populate the week days list or just populate the days list in your Java code (not in JSP)


问:
Is reading from remote networked memory mapped file or device block faster than reading from Local 7200rpm HDDs?
Or rather how does remote RAM compare against local Disk access?
If the answer is "it depends", what are the conditions?
Data access patterns, ratio of read-to-writes, distance etc.

Finally, what if the local disks are NetApp filers?

Thanks.

答: It is as always a question of latency versus bandwidth.  The access time to remote memory will be on the order of microseconds for gigabit networking, 100s of nanoseconds for InfiniBand and 10 GigE compared with milliseconds for local disks (example Seagate ST3250318AS - 4.1ms).  As soon as the disk has hit a contiguous block it's transfer rate will exceed gigabit networking which is why local disk is predominantly considered faster.</p>

ContentLicense: CC BY-SA 2.5


问:
how to change .do in struts 1 to .html for 1 action
Ex：when I click button submit, I will　go to

../showMemberList.do

Now I want to go action ShowMemberListAction but url change to

../showMemberList.html

Plz help me!

答:
In web.xml as below  All action will be has  .do

```<code>    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>
</code>```

I want to change for only action ShowMemberListAction when click button submit to action ShowMemberListAction, this action will process something and return .jsp file. this time, url will

../showMemberList.html

Body:
In web.xml as below  All action will be has  .do

    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

I want to change for only action ShowMemberListAction when click button submit to action ShowMemberListAction, this action will process something and return .jsp file. this time, url will

../showMemberList.html


问:
postgresql trigger NEW row as a json
I am writing a trigger where I need to convert NEW row into a json and insert into an other table. I am not getting it right.</p>

```<code>     CREATE OR REPLACE FUNCTION public.eventlogs_add_user()
      RETURNS trigger AS

    $BODY$
    DECLARE newRecord JSON;
    BEGIN

    newRecord :=  row_to_json(row)
        from (NEW) row;

// Insert newRecord into another table

    RETURN NEW;
    END$BODY$
      LANGUAGE plpgsql VOLATILE
      COST 100;
    ALTER FUNCTION public.eventlogs_add_user()
      OWNER TO postgres;

    -----------------------------------------------------------
</code>```

答:
changing

```<code>newRecord :=  row_to_json(row)
        from (NEW) row;
</code>```

to

```<code>newRecord :=  row_to_json(NEW.*);
</code>```

should help

Title: postgresql trigger NEW row as a json

Body:
I am writing a trigger where I need to convert NEW row into a json and insert into an other table. I am not getting it right.

     CREATE OR REPLACE FUNCTION public.eventlogs_add_user()
      RETURNS trigger AS

    $BODY$
    DECLARE newRecord JSON;
    BEGIN

    newRecord :=  row_to_json(row)
        from (NEW) row;

// Insert newRecord into another table

    RETURN NEW;
    END$BODY$
      LANGUAGE plpgsql VOLATILE
      COST 100;
    ALTER FUNCTION public.eventlogs_add_user()
      OWNER TO postgres;

    -----------------------------------------------------------

Body:
changing

newRecord :=  row_to_json(row)
        from (NEW) row;

to

newRecord :=  row_to_json(NEW.*);

should help


问:
how might I create multiple search results pages, and direct different forms to their respective results page?
I have a complex setup on a site I am working on. It uses a mixture of taxonomies and meta data to contain a web of pages that represent different countries. each country has an author, and their content can be written by coauthors. I use a query to deal with the array of coauthors and make sure that that content appears on the page of each author within, though it does not lend itself well to search queries.

```<code>ob_start();
    extract(shortcode_atts(array(
        'author' => '',
        'province' => '',
    ), $atts ));

    $post = get_post();

    if(is_page('testimonials') && empty($post->post_parent)) {
        $args = array(
        'post_type' =>  'shagun_testimonials',
        'order'     =>  'DESC',
        'orderby'   =>  'date',
        'posts_per_page'    =>  -1,
        'post_status'   =>  'publish'
        );
    } else {
        if(!empty($author)) {
            $authors = get_posts(array(
                'post_type' =>  'shagun_testimonials',
                'fields' => 'ids',
                'order'     =>  'DESC',
                'orderby'   =>  'date',
                'posts_per_page'    =>  -1,
                'post_status'   =>  'publish',
                'author__in'    => explode(',',$author),
                'nopaging'  => true,
                'posts_per_archive_page' => -1
            ));
        };
        if(!empty($province)){
            $multi_author = get_posts(array(
                'post_type' => 'shagun_testimonials',
                'fields' => 'ids',
                'nopaging'  => true,
                'posts_per_archive_page' => -1,
                'meta_query' => array(
                    array(
                        'key' => 'co-author',
                        'value' => $province,
                        'compare' => 'LIKE'
                    )
                )
            ));
        };
        if(isset($authors) && isset($multi_author)) {
            $options = array_merge($authors, $multi_author);
        }
        elseif (!isset($authors)) {
            $options = $multi_author;
        }
        elseif (!isset($multi_author)) {
            $options = $authors;
        };
</code>```

The problem now, is that these pages need a search form to search through only the content that applies to them. My idea is that I would have a search form that takes users to a page which uses the query above, but then just adds the search term as an additional filter, though I am not sure how to make it so that a form will be directed to a specific search results page instead of the default template.

答:
i use this way to go to different forms

```<code>if($count==1 && $ccdate > $nn4date ){
    //this is for var text
    $stat="已&#23450";
    //this is for var button
    $but="删除";
    //this is for var form
    $form="can.php";
    }
</code>```

now in html

```<code><form action="<?php echo $form; ?>" method="post">
</code>```

you can do same for the button and custom message this way also
ignore the funny variables in the if statement i have to use that to remember it lol

Body:
I have a complex setup on a site I am working on. It uses a mixture of taxonomies and meta data to contain a web of pages that represent different countries. each country has an author, and their content can be written by coauthors. I use a query to deal with the array of coauthors and make sure that that content appears on the page of each author within, though it does not lend itself well to search queries.

ob_start();
    extract(shortcode_atts(array(
        'author' => '',
        'province' => '',
    ), $atts ));

    $post = get_post();

    if(is_page('testimonials') && empty($post->post_parent)) {
        $args = array(
        'post_type' =>  'shagun_testimonials',
        'order'     =>  'DESC',
        'orderby'   =>  'date',
        'posts_per_page'    =>  -1,
        'post_status'   =>  'publish'
        );
    } else {
        if(!empty($author)) {
            $authors = get_posts(array(
                'post_type' =>  'shagun_testimonials',
                'fields' => 'ids',
                'order'     =>  'DESC',
                'orderby'   =>  'date',
                'posts_per_page'    =>  -1,
                'post_status'   =>  'publish',
                'author__in'    => explode(',',$author),
                'nopaging'  => true,
                'posts_per_archive_page' => -1
            ));
        };
        if(!empty($province)){
            $multi_author = get_posts(array(
                'post_type' => 'shagun_testimonials',
                'fields' => 'ids',
                'nopaging'  => true,
                'posts_per_archive_page' => -1,
                'meta_query' => array(
                    array(
                        'key' => 'co-author',
                        'value' => $province,
                        'compare' => 'LIKE'
                    )
                )
            ));
        };
        if(isset($authors) && isset($multi_author)) {
            $options = array_merge($authors, $multi_author);
        }
        elseif (!isset($authors)) {
            $options = $multi_author;
        }
        elseif (!isset($multi_author)) {
            $options = $authors;
        };

The problem now, is that these pages need a search form to search through only the content that applies to them. My idea is that I would have a search form that takes users to a page which uses the query above, but then just adds the search term as an additional filter, though I am not sure how to make it so that a form will be directed to a specific search results page instead of the default template.

Body:
i use this way to go to different forms

if($count==1 && $ccdate > $nn4date ){
    //this is for var text
    $stat="&#24050;&#23450";
    //this is for var button
    $but="&#21024;&#38500;";
    //this is for var form
    $form="can.php";
    }

now in html

<form action="<?php echo $form; ?>" method="post">

you can do same for the button and custom message this way also
ignore the funny variables in the if statement i have to use that to remember it lol


问:
Regex to match base name of files with multiple extensions
I'm trying to match files of the following structure in PHP.

Input:

```<code>filename.ext1
filename.ext1.ext2
filename.ext3.ext2.ext1
filename.ext4.ext2.ext1.ext4
file name with spaces and no way of knowing how long.ext1
file name with spaces and no way of knowing how long.ext1.ext2
file name with spaces and no way of knowing how long.ext2.ext1.ext3
file name with spaces and no way of knowing how long.ext3.ext1.ext4.ext3
</code>```

Output:

```<code>filename
filename
filename
filename
file name with spaces and no way of knowing how long
file name with spaces and no way of knowing how long
file name with spaces and no way of knowing how long
file name with spaces and no way of knowing how long
</code>```

What I've already attempted (doesn't work of course and I already understand why):

```<code>^(?P<basename>.*)(\.ext4)|(\.ext3)|(\.ext2)|(\.ext1).*$
</code>```

I'd like to extract the base name of the file and basically strip all extensions, because there's no way of knowing in which order they may appear. I've tried several solutions presented here but they did not work for me. The extensions could be anything alphanumeric of any length.

I'm fairly new to regular expressions and am confused that apparently you cannot simply search forward to the first dot and remove it including everything that comes after.

To learn, I'd also love to see how to do the reverse and just match all the extensions including the first dot.

Update:

I didn't think about file names that contain dots. So obviously my thinking regarding "searching forward" is flawed. Does anyone have a solution for the case

```<code>file name with spaces and no. way of knowing how long.ext3.ext1.ext4.ext3
</code>```

or even

```<code>file name with spaces and no way of knowing.how.long.ext3.ext1.ext4.ext3
</code>```

The latter one would quite possibly only work when certain extensions are given. So please assume ext1-4 are given but are in an unpredictable sequence.

答:
This is easy with just plain old php functions. No need for fancy regex.

```<code>$name = substr($filename, 0, strpos($filename, '.'));
</code>```

This won't work for filenames which have a . like your updated example, however in order to achieve this you would likely need to know in advance the extensions which you are likely to encounter.

Body:
I'm trying to match files of the following structure in PHP.

Input:

filename.ext1
filename.ext1.ext2
filename.ext3.ext2.ext1
filename.ext4.ext2.ext1.ext4
file name with spaces and no way of knowing how long.ext1
file name with spaces and no way of knowing how long.ext1.ext2
file name with spaces and no way of knowing how long.ext2.ext1.ext3
file name with spaces and no way of knowing how long.ext3.ext1.ext4.ext3

Output:

filename
filename
filename
filename
file name with spaces and no way of knowing how long
file name with spaces and no way of knowing how long
file name with spaces and no way of knowing how long
file name with spaces and no way of knowing how long

What I've already attempted (doesn't work of course and I already understand why):

^(?P<basename>.*)(\.ext4)|(\.ext3)|(\.ext2)|(\.ext1).*$

I'd like to extract the base name of the file and basically strip all extensions, because there's no way of knowing in which order they may appear. I've tried several solutions presented here but they did not work for me. The extensions could be anything alphanumeric of any length.

I'm fairly new to regular expressions and am confused that apparently you cannot simply search forward to the first dot and remove it including everything that comes after.

To learn, I'd also love to see how to do the reverse and just match all the extensions including the first dot.

Update:

I didn't think about file names that contain dots. So obviously my thinking regarding "searching forward" is flawed. Does anyone have a solution for the case

file name with spaces and no. way of knowing how long.ext3.ext1.ext4.ext3

or even

file name with spaces and no way of knowing.how.long.ext3.ext1.ext4.ext3

The latter one would quite possibly only work when certain extensions are given. So please assume ext1-4 are given but are in an unpredictable sequence.

Body:
This is easy with just plain old php functions. No need for fancy regex.

$name = substr($filename, 0, strpos($filename, '.'));

This won't work for filenames which have a . like your updated example, however in order to achieve this you would likely need to know in advance the extensions which you are likely to encounter.


问:
java.net.ConnectException when trying to connect in MySQL
I try to connect with my DB (MySQL) from a servlet but I get Connection refused error. I read similar questions like this. However:

You have not started your server.

In my local server (Ubuntu server 16.04), with IP 192.168.0.4 is installed MySQL server. MySQL Server is running as the command service mysql status give this output:

```<code>Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2017-03-21 11:50:56 EET; 1 weeks 1 days ago
Main PID: 1209 (mysqld)
</code>```

You are trying to connect to the wrong IP/port.

MySQL is listening to port 3306, as the command netstat -an | grep 3306.
gives the following output

```<code>tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN
</code>```

A firewall is blocking your connection before it reaches your server.

The server's firewall is disabled, as ufw status

```<code>Status: inactive
</code>```

I disabled my PC's firewall too but it didn't solve the connection error.

Your server has too many pending connections waiting to be accepted.

My server is fresh installed and there is no way to have any pending connections.

Your server is not listening for connections.

I run the commnand nmap -sT -O localhost and I got:

```<code>Not shown: 993 closed ports
PORT     STATE SERVICE
21/tcp   open  ftp
22/tcp   open  ssh
25/tcp   open  smtp
80/tcp   open  http
110/tcp  open  pop3
143/tcp  open  imap
3306/tcp open  mysql
</code>```

NETBEANS

Me and Server we are in the same network. My Java class which handles the communication with the DB contains:

```<code>private final String WEBAPP_DB = "jdbc:mysql://192.168.0.4:3306/myDataBase";
private final String JDBC_DRIVER="com.mysql.jdbc.Driver";
private final String USERNAME = "myUserName";
private final String PASSWORD = "myPassWord";

Connection c = null;
PreparedStatement stm = null;

sq = "SELECT * FROM Machines";
try {
    Class.forName(JDBC_DRIVER);
    c = DriverManager.getConnection(WEBAPP_DB, USERNAME, PASSWORD);
    stm = c.prepareStatement(sq);
    ResultSet rs = stm.executeQuery();

    while(rs.next()){
        System.out.println("Machine = " + rs.getInt("id"));
    }

} catch (SQLException e) {
    e.printStackTrace();
} finally {
    if (stm != null) {
        stm.close();
    }
    if (c != null) {
        c.close();
    }
}
</code>```

and some of the errors I get is

```<code>com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
...
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
...
Caused by: java.net.ConnectException: Connection refused: connect
</code>```

Any hint what may be the problem?

答:
If you're trying to connect yo your MySql server remotely, the problem is in the MySql server network configuration, it's listening on localhost (127.0.0.1):

```<code>Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN
</code>```

It should be:

```<code>Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN
</code>```

Or at least, instead of 0.0.0.0, your server ip address (192.168.0.4).

I suggest to read this How to Bind to Static IP address in MySQL

On the other hand, if you're connecting locally (your code is executed on MySql server, which is the same machine where NetBeans runs) you should change your connection string into jdbc:mysql://localhost:3306/myDataBase

P.S. So at resuming your questionnaire :)

You are trying to connect to the wrong IP.

Body:
I try to connect with my DB (MySQL) from a servlet but I get Connection refused error. I read similar questions like this. However:

You have not started your server.

In my local server (Ubuntu server 16.04), with IP 192.168.0.4 is installed MySQL server. MySQL Server is running as the command service mysql status give this output:

Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2017-03-21 11:50:56 EET; 1 weeks 1 days ago
Main PID: 1209 (mysqld)

You are trying to connect to the wrong IP/port.

MySQL is listening to port 3306, as the command netstat -an | grep 3306.
gives the following output

tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN

A firewall is blocking your connection before it reaches your server.

The server's firewall is disabled, as ufw status

Status: inactive

I disabled my PC's firewall too but it didn't solve the connection error.

Your server has too many pending connections waiting to be accepted.

My server is fresh installed and there is no way to have any pending connections.

Your server is not listening for connections.

I run the commnand nmap -sT -O localhost and I got:

Not shown: 993 closed ports
PORT     STATE SERVICE
21/tcp   open  ftp
22/tcp   open  ssh
25/tcp   open  smtp
80/tcp   open  http
110/tcp  open  pop3
143/tcp  open  imap
3306/tcp open  mysql

NETBEANS

Me and Server we are in the same network. My Java class which handles the communication with the DB contains:

private final String WEBAPP_DB = "jdbc:mysql://192.168.0.4:3306/myDataBase";
private final String JDBC_DRIVER="com.mysql.jdbc.Driver";
private final String USERNAME = "myUserName";
private final String PASSWORD = "myPassWord";

Connection c = null;
PreparedStatement stm = null;

sq = "SELECT * FROM Machines";
try {
    Class.forName(JDBC_DRIVER);
    c = DriverManager.getConnection(WEBAPP_DB, USERNAME, PASSWORD);
    stm = c.prepareStatement(sq);
    ResultSet rs = stm.executeQuery();

    while(rs.next()){
        System.out.println("Machine = " + rs.getInt("id"));
    }

} catch (SQLException e) {
    e.printStackTrace();
} finally {
    if (stm != null) {
        stm.close();
    }
    if (c != null) {
        c.close();
    }
}

and some of the errors I get is

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
...
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
...
Caused by: java.net.ConnectException: Connection refused: connect

Any hint what may be the problem?

Body:
If you're trying to connect yo your MySql server remotely, the problem is in the MySql server network configuration, it's listening on localhost (127.0.0.1):

Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN

It should be:

Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN

Or at least, instead of 0.0.0.0, your server ip address (192.168.0.4).

I suggest to read this How to Bind to Static IP address in MySQL

On the other hand, if you're connecting locally (your code is executed on MySql server, which is the same machine where NetBeans runs) you should change your connection string into jdbc:mysql://localhost:3306/myDataBase

P.S. So at resuming your questionnaire :)

You are trying to connect to the wrong IP.


问:
Starting SonarQube in my remote linux ubuntu machine
I'm trying to start SonarQube in my linux machine, but i'm getting this error:

```<code>--> Wrapper Started as Daemon
Launching a JVM...
Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
  Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.

2017.03.28 20:00:24 INFO  app[][o.s.a.AppFileSystem] Cleaning or creating temp directory /opt/sonar/temp
2017.03.28 20:00:24 INFO  app[][o.s.p.m.JavaProcessLauncher] Launch process[es]: /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java -Djava.awt.headless=true -Xmx1G -Xms256m -Xss256k -Djna.nosys=true -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError -Djava.io.tmpdir=/opt/sonar/temp -javaagent:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/management-agent.jar -cp ./lib/common/*:./lib/search/* org.sonar.search.SearchServer /opt/sonar/temp/sq-process4414918112205828016properties
2017.03.28 20:00:25 INFO   es[][o.s.p.ProcessEntryPoint]  Starting es
2017.03.28 20:00:25 INFO   es[][o.s.s.EsSettings]  Elasticsearch listening on /127.0.0.1:9001
2017.03.28 20:00:26 INFO   es[][o.elasticsearch.node]  [sonarqube] version[2.3.3], pid[4801], build[218bdf1/2016-05-17T15:40:04Z]
2017.03.28 20:00:26 INFO   es[][o.elasticsearch.node]  [sonarqube] initializing ...
2017.03.28 20:00:26 INFO   es[][o.e.plugins]  [sonarqube] modules [], plugins [], sites []
2017.03.28 20:00:26 INFO   es[][o.elasticsearch.env]  [sonarqube] using [1] data paths, mounts [[/ (/dev/root)]], net usable_space [12.5gb], net total_space [19.4gb], spins? [possibly], types [ext4]
2017.03.28 20:00:26 INFO   es[][o.elasticsearch.env]  [sonarqube] heap size [1015.6mb], compressed ordinary object pointers [true]
2017.03.28 20:00:30 INFO   es[][o.elasticsearch.node]  [sonarqube] initialized
2017.03.28 20:00:30 INFO   es[][o.elasticsearch.node]  [sonarqube] starting ...
2017.03.28 20:00:30 INFO   es[][o.e.transport]  [sonarqube] publish_address {127.0.0.1:9001}, bound_addresses {127.0.0.1:9001}
2017.03.28 20:00:30 INFO   es[][o.e.discovery]  [sonarqube] sonarqube/upk_GmJgQPmBqNGykii2jw
2017.03.28 20:00:33 INFO   es[][o.e.cluster.service]  [sonarqube] new_master {sonarqube}{upk_GmJgQPmBqNGykii2jw}{127.0.0.1}{127.0.0.1:9001}{rack_id=sonarqube, master=true}, reason: zen-disco-join(elected_as_master, [0] joins received)
2017.03.28 20:00:33 INFO   es[][o.elasticsearch.node]  [sonarqube] started
2017.03.28 20:00:33 INFO   es[][o.e.gateway]  [sonarqube] recovered [0] indices into cluster_state
2017.03.28 20:00:33 INFO  app[][o.s.p.m.Monitor] Process[es] is up
2017.03.28 20:00:33 INFO  app[][o.s.p.m.JavaProcessLauncher] Launch process[web]: /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djruby.management.enabled=false -Djruby.compile.invokedynamic=false -Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError -Djava.io.tmpdir=/opt/sonar/temp -javaagent:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/management-agent.jar -cp ./lib/common/*:./lib/server/*:/opt/sonar/lib/jdbc/mysql/mysql-connector-java-5.1.39.jar org.sonar.server.app.WebServer /opt/sonar/temp/sq-process3450868362392661343properties
2017.03.28 20:00:34 INFO  web[][o.s.p.ProcessEntryPoint] Starting web
2017.03.28 20:00:35 INFO  web[][o.s.s.a.TomcatContexts] Webapp directory: /opt/sonar/web
2017.03.28 20:00:35 INFO  web[][o.a.c.h.Http11NioProtocol] Initializing ProtocolHandler ["http-nio-127.0.0.1-9000"]
2017.03.28 20:00:35 INFO  web[][o.a.t.u.n.NioSelectorPool] Using a shared selector for servlet write/read
2017.03.28 20:00:36 INFO  web[][o.e.plugins] [Eternal Brain] modules [], plugins [], sites []
2017.03.28 20:00:38 INFO  web[][o.s.s.e.EsClientProvider] Connected to local Elasticsearch: [127.0.0.1:9001]
2017.03.28 20:00:38 INFO  web[][o.s.s.p.LogServerVersion] SonarQube Server / 6.1 / dc148a71a1c184ccad588b66251980c994879dff
2017.03.28 20:00:38 INFO  web[][o.sonar.db.Database] Create JDBC data source for jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance
Tue Mar 28 20:00:38 UTC 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Tue Mar 28 20:00:38 UTC 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2017.03.28 20:00:40 ERROR web[][o.a.c.c.C.[.[.[/sonar]] Exception sending context initialized event to listener instance of class org.sonar.server.platform.web.PlatformServletContextListener
org.sonar.api.utils.MessageException: Database was upgraded to a more recent of SonarQube. Backup must probably be restored or db settings are incorrect.
2017.03.28 20:00:40 ERROR web[][o.a.c.c.StandardContext] One or more listeners failed to start. Full details will be found in the appropriate container log file
2017.03.28 20:00:40 ERROR web[][o.a.c.c.StandardContext] Context [/sonar] startup failed due to previous errors
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [elasticsearch[Eternal Brain][[timer]]] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Thread.sleep(Native Method)
 org.elasticsearch.threadpool.ThreadPool$EstimatedTimeThread.run(ThreadPool.java:719)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [elasticsearch[Eternal Brain][scheduler][T#1]] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 sun.misc.Unsafe.park(Native Method)
 java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
 java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
 java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093)
 java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809)
 java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 java.lang.Thread.run(Thread.java:745)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [elasticsearch[Eternal Brain][transport_client_worker][T#1]{New I/O worker #1}] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 sun.nio.ch.EPollArrayWrapper.epollWait(Native Method)
 sun.nio.ch.EPollArrayWrapper.poll(EPollArrayWrapper.java:269)
 sun.nio.ch.EPollSelectorImpl.doSelect(EPollSelectorImpl.java:93)
 sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:86)
 sun.nio.ch.SelectorImpl.select(SelectorImpl.java:97)
 org.jboss.netty.channel.socket.nio.SelectorUtil.select(SelectorUtil.java:68)
 org.jboss.netty.channel.socket.nio.AbstractNioSelector.select(AbstractNioSelector.java:434)
 org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:212)
 org.jboss.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:89)
 org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178)
 org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
 org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 java.lang.Thread.run(Thread.java:745)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [elasticsearch[Eternal Brain][transport_client_worker][T#2]{New I/O worker #2}] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 sun.nio.ch.EPollArrayWrapper.epollWait(Native Method)
 sun.nio.ch.EPollArrayWrapper.poll(EPollArrayWrapper.java:269)
 sun.nio.ch.EPollSelectorImpl.doSelect(EPollSelectorImpl.java:93)
 sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:86)
 sun.nio.ch.SelectorImpl.select(SelectorImpl.java:97)
 org.jboss.netty.channel.socket.nio.SelectorUtil.select(SelectorUtil.java:68)
 org.jboss.netty.channel.socket.nio.AbstractNioSelector.select(AbstractNioSelector.java:434)
 org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:212)
 org.jboss.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:89)
 org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178)
 org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
 org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 java.lang.Thread.run(Thread.java:745)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [elasticsearch[Eternal Brain][transport_client_boss][T#1]{New I/O boss #3}] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 sun.nio.ch.EPollArrayWrapper.epollWait(Native Method)
 sun.nio.ch.EPollArrayWrapper.poll(EPollArrayWrapper.java:269)
 sun.nio.ch.EPollSelectorImpl.doSelect(EPollSelectorImpl.java:93)
 sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:86)
 sun.nio.ch.SelectorImpl.select(SelectorImpl.java:97)
 org.jboss.netty.channel.socket.nio.SelectorUtil.select(SelectorUtil.java:68)
 org.jboss.netty.channel.socket.nio.AbstractNioSelector.select(AbstractNioSelector.java:434)
 org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:212)
 org.jboss.netty.channel.socket.nio.NioClientBoss.run(NioClientBoss.java:42)
 org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
 org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 java.lang.Thread.run(Thread.java:745)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [elasticsearch[Eternal Brain][transport_client_timer][T#1]{Hashed wheel timer #1}] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Thread.sleep(Native Method)
 org.jboss.netty.util.HashedWheelTimer$Worker.waitForNextTick(HashedWheelTimer.java:445)
 org.jboss.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:364)
 org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
 java.lang.Thread.run(Thread.java:745)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [elasticsearch[Eternal Brain][generic][T#1]] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 sun.misc.Unsafe.park(Native Method)
 java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
 java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
 java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
 java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
 java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1066)
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 java.lang.Thread.run(Thread.java:745)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Object.wait(Native Method)
 java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
 com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:43)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [Timer-0] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Object.wait(Native Method)
 java.util.TimerThread.mainLoop(Timer.java:552)
 java.util.TimerThread.run(Timer.java:505)
2017.03.28 20:00:40 INFO  web[][o.a.c.h.Http11NioProtocol] Starting ProtocolHandler ["http-nio-127.0.0.1-9000"]
2017.03.28 20:00:40 INFO  web[][o.s.s.a.TomcatAccessLog] Web server is started
2017.03.28 20:00:40 INFO  web[][o.s.s.a.EmbeddedTomcat] HTTP connector enabled on port 9000
2017.03.28 20:00:40 WARN  web[][o.s.p.ProcessEntryPoint] Fail to start web
java.lang.IllegalStateException: Webapp did not start
    at org.sonar.server.app.EmbeddedTomcat.isUp(EmbeddedTomcat.java:84) ~[sonar-server-6.1.jar:na]
    at org.sonar.server.app.WebServer.isUp(WebServer.java:46) [sonar-server-6.1.jar:na]
    at org.sonar.process.ProcessEntryPoint.launch(ProcessEntryPoint.java:105) ~[sonar-process-6.1.jar:na]
    at org.sonar.server.app.WebServer.main(WebServer.java:67) [sonar-server-6.1.jar:na]
2017.03.28 20:00:40 INFO  web[][o.a.c.h.Http11NioProtocol] Pausing ProtocolHandler ["http-nio-127.0.0.1-9000"]
2017.03.28 20:00:41 INFO  web[][o.a.c.h.Http11NioProtocol] Stopping ProtocolHandler ["http-nio-127.0.0.1-9000"]
2017.03.28 20:00:42 INFO  web[][o.a.c.h.Http11NioProtocol] Destroying ProtocolHandler ["http-nio-127.0.0.1-9000"]
2017.03.28 20:00:42 INFO  web[][o.s.s.a.TomcatAccessLog] Web server is stopped
2017.03.28 20:00:42 INFO  app[][o.s.p.m.Monitor] Process[es] is stopping
2017.03.28 20:00:42 INFO   es[][o.s.p.StopWatcher]  Stopping process
2017.03.28 20:00:42 INFO   es[][o.elasticsearch.node]  [sonarqube] stopping ...
2017.03.28 20:00:42 INFO   es[][o.elasticsearch.node]  [sonarqube] stopped
2017.03.28 20:00:42 INFO   es[][o.elasticsearch.node]  [sonarqube] closing ...
2017.03.28 20:00:42 INFO   es[][o.elasticsearch.node]  [sonarqube] closed
2017.03.28 20:00:43 INFO  app[][o.s.p.m.Monitor] Process[es] is stopped
<-- Wrapper Stopped
</code>```

the log show me that it's a memory leak, but i don't think that is the error cause.

I was reading in some posts that it's cause because the java isn't reconized.

答:
The error "Database was upgraded to a more recent of SonarQube. Backup must probably be restored or db settings are incorrect." means that the DB schema has already been used by another version of SonarQube (> 6.1 in your case).

You should re-create the schema or install the correct version of SonarQube.

Body:
I'm trying to start SonarQube in my linux machine, but i'm getting this error:

--> Wrapper Started as Daemon
Launching a JVM...
Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
  Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.

2017.03.28 20:00:24 INFO  app[][o.s.a.AppFileSystem] Cleaning or creating temp directory /opt/sonar/temp
2017.03.28 20:00:24 INFO  app[][o.s.p.m.JavaProcessLauncher] Launch process[es]: /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java -Djava.awt.headless=true -Xmx1G -Xms256m -Xss256k -Djna.nosys=true -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError -Djava.io.tmpdir=/opt/sonar/temp -javaagent:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/management-agent.jar -cp ./lib/common/*:./lib/search/* org.sonar.search.SearchServer /opt/sonar/temp/sq-process4414918112205828016properties
2017.03.28 20:00:25 INFO   es[][o.s.p.ProcessEntryPoint]  Starting es
2017.03.28 20:00:25 INFO   es[][o.s.s.EsSettings]  Elasticsearch listening on /127.0.0.1:9001
2017.03.28 20:00:26 INFO   es[][o.elasticsearch.node]  [sonarqube] version[2.3.3], pid[4801], build[218bdf1/2016-05-17T15:40:04Z]
2017.03.28 20:00:26 INFO   es[][o.elasticsearch.node]  [sonarqube] initializing ...
2017.03.28 20:00:26 INFO   es[][o.e.plugins]  [sonarqube] modules [], plugins [], sites []
2017.03.28 20:00:26 INFO   es[][o.elasticsearch.env]  [sonarqube] using [1] data paths, mounts [[/ (/dev/root)]], net usable_space [12.5gb], net total_space [19.4gb], spins? [possibly], types [ext4]
2017.03.28 20:00:26 INFO   es[][o.elasticsearch.env]  [sonarqube] heap size [1015.6mb], compressed ordinary object pointers [true]
2017.03.28 20:00:30 INFO   es[][o.elasticsearch.node]  [sonarqube] initialized
2017.03.28 20:00:30 INFO   es[][o.elasticsearch.node]  [sonarqube] starting ...
2017.03.28 20:00:30 INFO   es[][o.e.transport]  [sonarqube] publish_address {127.0.0.1:9001}, bound_addresses {127.0.0.1:9001}
2017.03.28 20:00:30 INFO   es[][o.e.discovery]  [sonarqube] sonarqube/upk_GmJgQPmBqNGykii2jw
2017.03.28 20:00:33 INFO   es[][o.e.cluster.service]  [sonarqube] new_master {sonarqube}{upk_GmJgQPmBqNGykii2jw}{127.0.0.1}{127.0.0.1:9001}{rack_id=sonarqube, master=true}, reason: zen-disco-join(elected_as_master, [0] joins received)
2017.03.28 20:00:33 INFO   es[][o.elasticsearch.node]  [sonarqube] started
2017.03.28 20:00:33 INFO   es[][o.e.gateway]  [sonarqube] recovered [0] indices into cluster_state
2017.03.28 20:00:33 INFO  app[][o.s.p.m.Monitor] Process[es] is up
2017.03.28 20:00:33 INFO  app[][o.s.p.m.JavaProcessLauncher] Launch process[web]: /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djruby.management.enabled=false -Djruby.compile.invokedynamic=false -Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError -Djava.io.tmpdir=/opt/sonar/temp -javaagent:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/management-agent.jar -cp ./lib/common/*:./lib/server/*:/opt/sonar/lib/jdbc/mysql/mysql-connector-java-5.1.39.jar org.sonar.server.app.WebServer /opt/sonar/temp/sq-process3450868362392661343properties
2017.03.28 20:00:34 INFO  web[][o.s.p.ProcessEntryPoint] Starting web
2017.03.28 20:00:35 INFO  web[][o.s.s.a.TomcatContexts] Webapp directory: /opt/sonar/web
2017.03.28 20:00:35 INFO  web[][o.a.c.h.Http11NioProtocol] Initializing ProtocolHandler ["http-nio-127.0.0.1-9000"]
2017.03.28 20:00:35 INFO  web[][o.a.t.u.n.NioSelectorPool] Using a shared selector for servlet write/read
2017.03.28 20:00:36 INFO  web[][o.e.plugins] [Eternal Brain] modules [], plugins [], sites []
2017.03.28 20:00:38 INFO  web[][o.s.s.e.EsClientProvider] Connected to local Elasticsearch: [127.0.0.1:9001]
2017.03.28 20:00:38 INFO  web[][o.s.s.p.LogServerVersion] SonarQube Server / 6.1 / dc148a71a1c184ccad588b66251980c994879dff
2017.03.28 20:00:38 INFO  web[][o.sonar.db.Database] Create JDBC data source for jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance
Tue Mar 28 20:00:38 UTC 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Tue Mar 28 20:00:38 UTC 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2017.03.28 20:00:40 ERROR web[][o.a.c.c.C.[.[.[/sonar]] Exception sending context initialized event to listener instance of class org.sonar.server.platform.web.PlatformServletContextListener
org.sonar.api.utils.MessageException: Database was upgraded to a more recent of SonarQube. Backup must probably be restored or db settings are incorrect.
2017.03.28 20:00:40 ERROR web[][o.a.c.c.StandardContext] One or more listeners failed to start. Full details will be found in the appropriate container log file
2017.03.28 20:00:40 ERROR web[][o.a.c.c.StandardContext] Context [/sonar] startup failed due to previous errors
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [elasticsearch[Eternal Brain][[timer]]] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Thread.sleep(Native Method)
 org.elasticsearch.threadpool.ThreadPool$EstimatedTimeThread.run(ThreadPool.java:719)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [elasticsearch[Eternal Brain][scheduler][T#1]] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 sun.misc.Unsafe.park(Native Method)
 java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
 java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
 java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093)
 java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809)
 java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 java.lang.Thread.run(Thread.java:745)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [elasticsearch[Eternal Brain][transport_client_worker][T#1]{New I/O worker #1}] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 sun.nio.ch.EPollArrayWrapper.epollWait(Native Method)
 sun.nio.ch.EPollArrayWrapper.poll(EPollArrayWrapper.java:269)
 sun.nio.ch.EPollSelectorImpl.doSelect(EPollSelectorImpl.java:93)
 sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:86)
 sun.nio.ch.SelectorImpl.select(SelectorImpl.java:97)
 org.jboss.netty.channel.socket.nio.SelectorUtil.select(SelectorUtil.java:68)
 org.jboss.netty.channel.socket.nio.AbstractNioSelector.select(AbstractNioSelector.java:434)
 org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:212)
 org.jboss.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:89)
 org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178)
 org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
 org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 java.lang.Thread.run(Thread.java:745)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [elasticsearch[Eternal Brain][transport_client_worker][T#2]{New I/O worker #2}] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 sun.nio.ch.EPollArrayWrapper.epollWait(Native Method)
 sun.nio.ch.EPollArrayWrapper.poll(EPollArrayWrapper.java:269)
 sun.nio.ch.EPollSelectorImpl.doSelect(EPollSelectorImpl.java:93)
 sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:86)
 sun.nio.ch.SelectorImpl.select(SelectorImpl.java:97)
 org.jboss.netty.channel.socket.nio.SelectorUtil.select(SelectorUtil.java:68)
 org.jboss.netty.channel.socket.nio.AbstractNioSelector.select(AbstractNioSelector.java:434)
 org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:212)
 org.jboss.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:89)
 org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178)
 org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
 org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 java.lang.Thread.run(Thread.java:745)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [elasticsearch[Eternal Brain][transport_client_boss][T#1]{New I/O boss #3}] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 sun.nio.ch.EPollArrayWrapper.epollWait(Native Method)
 sun.nio.ch.EPollArrayWrapper.poll(EPollArrayWrapper.java:269)
 sun.nio.ch.EPollSelectorImpl.doSelect(EPollSelectorImpl.java:93)
 sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:86)
 sun.nio.ch.SelectorImpl.select(SelectorImpl.java:97)
 org.jboss.netty.channel.socket.nio.SelectorUtil.select(SelectorUtil.java:68)
 org.jboss.netty.channel.socket.nio.AbstractNioSelector.select(AbstractNioSelector.java:434)
 org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:212)
 org.jboss.netty.channel.socket.nio.NioClientBoss.run(NioClientBoss.java:42)
 org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
 org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 java.lang.Thread.run(Thread.java:745)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [elasticsearch[Eternal Brain][transport_client_timer][T#1]{Hashed wheel timer #1}] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Thread.sleep(Native Method)
 org.jboss.netty.util.HashedWheelTimer$Worker.waitForNextTick(HashedWheelTimer.java:445)
 org.jboss.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:364)
 org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
 java.lang.Thread.run(Thread.java:745)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [elasticsearch[Eternal Brain][generic][T#1]] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 sun.misc.Unsafe.park(Native Method)
 java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
 java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
 java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
 java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
 java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1066)
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 java.lang.Thread.run(Thread.java:745)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Object.wait(Native Method)
 java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
 com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:43)
2017.03.28 20:00:40 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [sonar] appears to have started a thread named [Timer-0] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Object.wait(Native Method)
 java.util.TimerThread.mainLoop(Timer.java:552)
 java.util.TimerThread.run(Timer.java:505)
2017.03.28 20:00:40 INFO  web[][o.a.c.h.Http11NioProtocol] Starting ProtocolHandler ["http-nio-127.0.0.1-9000"]
2017.03.28 20:00:40 INFO  web[][o.s.s.a.TomcatAccessLog] Web server is started
2017.03.28 20:00:40 INFO  web[][o.s.s.a.EmbeddedTomcat] HTTP connector enabled on port 9000
2017.03.28 20:00:40 WARN  web[][o.s.p.ProcessEntryPoint] Fail to start web
java.lang.IllegalStateException: Webapp did not start
    at org.sonar.server.app.EmbeddedTomcat.isUp(EmbeddedTomcat.java:84) ~[sonar-server-6.1.jar:na]
    at org.sonar.server.app.WebServer.isUp(WebServer.java:46) [sonar-server-6.1.jar:na]
    at org.sonar.process.ProcessEntryPoint.launch(ProcessEntryPoint.java:105) ~[sonar-process-6.1.jar:na]
    at org.sonar.server.app.WebServer.main(WebServer.java:67) [sonar-server-6.1.jar:na]
2017.03.28 20:00:40 INFO  web[][o.a.c.h.Http11NioProtocol] Pausing ProtocolHandler ["http-nio-127.0.0.1-9000"]
2017.03.28 20:00:41 INFO  web[][o.a.c.h.Http11NioProtocol] Stopping ProtocolHandler ["http-nio-127.0.0.1-9000"]
2017.03.28 20:00:42 INFO  web[][o.a.c.h.Http11NioProtocol] Destroying ProtocolHandler ["http-nio-127.0.0.1-9000"]
2017.03.28 20:00:42 INFO  web[][o.s.s.a.TomcatAccessLog] Web server is stopped
2017.03.28 20:00:42 INFO  app[][o.s.p.m.Monitor] Process[es] is stopping
2017.03.28 20:00:42 INFO   es[][o.s.p.StopWatcher]  Stopping process
2017.03.28 20:00:42 INFO   es[][o.elasticsearch.node]  [sonarqube] stopping ...
2017.03.28 20:00:42 INFO   es[][o.elasticsearch.node]  [sonarqube] stopped
2017.03.28 20:00:42 INFO   es[][o.elasticsearch.node]  [sonarqube] closing ...
2017.03.28 20:00:42 INFO   es[][o.elasticsearch.node]  [sonarqube] closed
2017.03.28 20:00:43 INFO  app[][o.s.p.m.Monitor] Process[es] is stopped
<-- Wrapper Stopped

the log show me that it's a memory leak, but i don't think that is the error cause.

I was reading in some posts that it's cause because the java isn't reconized.


问:
Embedded Unity3D in WPF Application -> SetWindowLong issues
I'm developping an application in WPF that host an Unity application.
This hosting is set by using a HwndHost class (because the unity way with the _hwndparent argument seems don(t work).

In the BuilWindowCore of my HwndHost class, I need to change the window child style using GetWindowLong and SetWindowLong.

All of these works perfectly on my developping computer. But I can't use the application on another computer.

When I just set WS_CCHILD value (without retrieving the style using GetWindowLong) ther isn't crash on all computers, but the child application not appeared correctly (Maximized etc..). That's why I think the problem is about the styling child window part.

There is my HwndHost class code:

```<code>public class UnityHwndHost : HwndHost
{
    private Process _process;
    private HandleRef _hwnd;
    private IntPtr _unityHWND; // = IntPtr.Zero;

    private const int GWL_STYLE = -16;

    // Window Styles
    const UInt32 WS_OVERLAPPED = 0;
    const UInt32 WS_POPUP = 0x80000000;
    const UInt32 WS_CHILD = 0x40000000;
    const UInt32 WS_MINIMIZE = 0x20000000;
    const UInt32 WS_VISIBLE = 0x10000000;
    const UInt32 WS_DISABLED = 0x8000000;
    const UInt32 WS_CLIPSIBLINGS = 0x4000000;
    const UInt32 WS_CLIPCHILDREN = 0x2000000;
    const UInt32 WS_MAXIMIZE = 0x1000000;
    const UInt32 WS_CAPTION = 0xC00000;      // WS_BORDER or WS_DLGFRAME
    const UInt32 WS_BORDER = 0x800000;
    const UInt32 WS_DLGFRAME = 0x400000;
    const UInt32 WS_VSCROLL = 0x200000;
    const UInt32 WS_HSCROLL = 0x100000;
    const UInt32 WS_SYSMENU = 0x80000;
    const UInt32 WS_THICKFRAME = 0x40000;
    const UInt32 WS_GROUP = 0x20000;
    const UInt32 WS_TABSTOP = 0x10000;
    const UInt32 WS_MINIMIZEBOX = 0x20000;
    const UInt32 WS_MAXIMIZEBOX = 0x10000;
    const UInt32 WS_TILED = WS_OVERLAPPED;
    const UInt32 WS_ICONIC = WS_MINIMIZE;
    const UInt32 WS_SIZEBOX = WS_THICKFRAME;

    // Extended Window Styles
    const UInt32 WS_EX_DLGMODALFRAME = 0x0001;
    const UInt32 WS_EX_NOPARENTNOTIFY = 0x0004;
    const UInt32 WS_EX_TOPMOST = 0x0008;
    const UInt32 WS_EX_ACCEPTFILES = 0x0010;
    const UInt32 WS_EX_TRANSPARENT = 0x0020;
    const UInt32 WS_EX_MDICHILD = 0x0040;
    const UInt32 WS_EX_TOOLWINDOW = 0x0080;
    const UInt32 WS_EX_WINDOWEDGE = 0x0100;
    const UInt32 WS_EX_CLIENTEDGE = 0x0200;
    const UInt32 WS_EX_CONTEXTHELP = 0x0400;
    const UInt32 WS_EX_RIGHT = 0x1000;
    const UInt32 WS_EX_LEFT = 0x0000;
    const UInt32 WS_EX_RTLREADING = 0x2000;
    const UInt32 WS_EX_LTRREADING = 0x0000;
    const UInt32 WS_EX_LEFTSCROLLBAR = 0x4000;
    const UInt32 WS_EX_RIGHTSCROLLBAR = 0x0000;
    const UInt32 WS_EX_CONTROLPARENT = 0x10000;
    const UInt32 WS_EX_STATICEDGE = 0x20000;
    const UInt32 WS_EX_APPWINDOW = 0x40000;
    const UInt32 WS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
    const UInt32 WS_EX_PALETTEWINDOW = (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST);
    const UInt32 WS_EX_LAYERED = 0x00080000;
    const UInt32 WS_EX_NOINHERITLAYOUT = 0x00100000; // Disable inheritence of mirroring by children
    const UInt32 WS_EX_LAYOUTRTL = 0x00400000; // Right to left mirroring
    const UInt32 WS_EX_COMPOSITED = 0x02000000;
    const UInt32 WS_EX_NOACTIVATE = 0x08000000;

    private const int WM_ACTIVATE = 0x0006;
    private readonly IntPtr WA_ACTIVE = new IntPtr(1);
    private readonly IntPtr WA_INACTIVE = new IntPtr(0);

    [DllImport("user32.dll")]
    private static extern int SetWindowLong(IntPtr hWnd, int nIndex, UInt32 dwNewLong);

    [DllImport("user32.dll", SetLastError = true)]
    private static extern UInt32 GetWindowLong(IntPtr hWnd, int nIndex);

    [DllImport("user32")]
    private static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent);

    internal delegate int WindowEnumProc(IntPtr hwnd, IntPtr lparam);
    [DllImport("user32.dll")]
    internal static extern bool EnumChildWindows(IntPtr hwnd, WindowEnumProc func, IntPtr lParam);

    [DllImport("user32.dll")]
    static extern int SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
    public static extern bool IsWindow(IntPtr hWnd);

    #region CONSTRUCTORS
    #endregion

    #region METHODS
    protected override HandleRef BuildWindowCore(HandleRef hwndParent)
    {
        var context = DataContext as UltrasoundVM;
        var psi = new ProcessStartInfo("UnityStandAlone.exe");

        psi.Arguments = "\"" + context.Workspace.Replace('\\', '/') + "\" " + context.SelectedFlexible;
        LoggerHelper.Write(GetType().FullName + "." + new StackTrace().GetFrame(0).GetMethod().Name + " : " + psi.Arguments, EventLogEntryType.Information);
        psi.WindowStyle = ProcessWindowStyle.Minimized;

        _process = Process.Start(psi);
        _process.WaitForInputIdle();
        while (_process.MainWindowHandle == IntPtr.Zero || !IsWindow(_process.MainWindowHandle))
        {
            Thread.Yield();
        }
        _unityHWND = _process.MainWindowHandle;
        SetParent(_unityHWND, hwndParent.Handle);

        var style = GetWindowLong(_unityHWND, GWL_STYLE);
        style = style & ~WS_CAPTION & ~WS_THICKFRAME; // Removes Caption bar and the sizing border
        style |= (WS_CHILD); // Must be a child window to be hosted
        SetWindowLong(_unityHWND, GWL_STYLE, style);

        SetWindowLong(_unityHWND, GWL_STYLE, WS_CHILD | WS_MAXIMIZE);

        SendMessage(_unityHWND, WM_ACTIVATE, WA_ACTIVE, IntPtr.Zero);

        _hwnd = new HandleRef(this, _unityHWND);
        return _hwnd;
    }

    protected override void DestroyWindowCore(HandleRef hwnd)
    {
        SendMessage(_hwnd.Handle, WM_ACTIVATE, WA_INACTIVE, IntPtr.Zero);

        _process.CloseMainWindow();

        _process.WaitForExit(5000);

        if (_process.HasExited == false)
        {
            _process.Kill();
        }

        _process.Close();
        _process.Dispose();
        _process = null;
    }
    #endregion
}
</code>```

Notes:

Developping Computer

- OS : Windows 10 Home edition
- Unity 3D 5.5.2.f.1 free edition

Testing Computers
- OS : Windows 10 (Home edition & Pro Edition)

Of course I've tried to build the unity application with different parameters, same thing with my parent application.

答:
OK

It seems that the problem came from my unity stand alone which was not the same between my sources and my debug folder.

Body:
I'm developping an application in WPF that host an Unity application.
This hosting is set by using a HwndHost class (because the unity way with the _hwndparent argument seems don(t work).

In the BuilWindowCore of my HwndHost class, I need to change the window child style using GetWindowLong and SetWindowLong.

All of these works perfectly on my developping computer. But I can't use the application on another computer.

When I just set WS_CCHILD value (without retrieving the style using GetWindowLong) ther isn't crash on all computers, but the child application not appeared correctly (Maximized etc..). That's why I think the problem is about the styling child window part.

There is my HwndHost class code:

public class UnityHwndHost : HwndHost
{
    private Process _process;
    private HandleRef _hwnd;
    private IntPtr _unityHWND; // = IntPtr.Zero;

    private const int GWL_STYLE = -16;

    // Window Styles
    const UInt32 WS_OVERLAPPED = 0;
    const UInt32 WS_POPUP = 0x80000000;
    const UInt32 WS_CHILD = 0x40000000;
    const UInt32 WS_MINIMIZE = 0x20000000;
    const UInt32 WS_VISIBLE = 0x10000000;
    const UInt32 WS_DISABLED = 0x8000000;
    const UInt32 WS_CLIPSIBLINGS = 0x4000000;
    const UInt32 WS_CLIPCHILDREN = 0x2000000;
    const UInt32 WS_MAXIMIZE = 0x1000000;
    const UInt32 WS_CAPTION = 0xC00000;      // WS_BORDER or WS_DLGFRAME
    const UInt32 WS_BORDER = 0x800000;
    const UInt32 WS_DLGFRAME = 0x400000;
    const UInt32 WS_VSCROLL = 0x200000;
    const UInt32 WS_HSCROLL = 0x100000;
    const UInt32 WS_SYSMENU = 0x80000;
    const UInt32 WS_THICKFRAME = 0x40000;
    const UInt32 WS_GROUP = 0x20000;
    const UInt32 WS_TABSTOP = 0x10000;
    const UInt32 WS_MINIMIZEBOX = 0x20000;
    const UInt32 WS_MAXIMIZEBOX = 0x10000;
    const UInt32 WS_TILED = WS_OVERLAPPED;
    const UInt32 WS_ICONIC = WS_MINIMIZE;
    const UInt32 WS_SIZEBOX = WS_THICKFRAME;

    // Extended Window Styles
    const UInt32 WS_EX_DLGMODALFRAME = 0x0001;
    const UInt32 WS_EX_NOPARENTNOTIFY = 0x0004;
    const UInt32 WS_EX_TOPMOST = 0x0008;
    const UInt32 WS_EX_ACCEPTFILES = 0x0010;
    const UInt32 WS_EX_TRANSPARENT = 0x0020;
    const UInt32 WS_EX_MDICHILD = 0x0040;
    const UInt32 WS_EX_TOOLWINDOW = 0x0080;
    const UInt32 WS_EX_WINDOWEDGE = 0x0100;
    const UInt32 WS_EX_CLIENTEDGE = 0x0200;
    const UInt32 WS_EX_CONTEXTHELP = 0x0400;
    const UInt32 WS_EX_RIGHT = 0x1000;
    const UInt32 WS_EX_LEFT = 0x0000;
    const UInt32 WS_EX_RTLREADING = 0x2000;
    const UInt32 WS_EX_LTRREADING = 0x0000;
    const UInt32 WS_EX_LEFTSCROLLBAR = 0x4000;
    const UInt32 WS_EX_RIGHTSCROLLBAR = 0x0000;
    const UInt32 WS_EX_CONTROLPARENT = 0x10000;
    const UInt32 WS_EX_STATICEDGE = 0x20000;
    const UInt32 WS_EX_APPWINDOW = 0x40000;
    const UInt32 WS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
    const UInt32 WS_EX_PALETTEWINDOW = (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST);
    const UInt32 WS_EX_LAYERED = 0x00080000;
    const UInt32 WS_EX_NOINHERITLAYOUT = 0x00100000; // Disable inheritence of mirroring by children
    const UInt32 WS_EX_LAYOUTRTL = 0x00400000; // Right to left mirroring
    const UInt32 WS_EX_COMPOSITED = 0x02000000;
    const UInt32 WS_EX_NOACTIVATE = 0x08000000;

    private const int WM_ACTIVATE = 0x0006;
    private readonly IntPtr WA_ACTIVE = new IntPtr(1);
    private readonly IntPtr WA_INACTIVE = new IntPtr(0);

    [DllImport("user32.dll")]
    private static extern int SetWindowLong(IntPtr hWnd, int nIndex, UInt32 dwNewLong);

    [DllImport("user32.dll", SetLastError = true)]
    private static extern UInt32 GetWindowLong(IntPtr hWnd, int nIndex);

    [DllImport("user32")]
    private static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent);

    internal delegate int WindowEnumProc(IntPtr hwnd, IntPtr lparam);
    [DllImport("user32.dll")]
    internal static extern bool EnumChildWindows(IntPtr hwnd, WindowEnumProc func, IntPtr lParam);

    [DllImport("user32.dll")]
    static extern int SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
    public static extern bool IsWindow(IntPtr hWnd);

    #region CONSTRUCTORS
    #endregion

    #region METHODS
    protected override HandleRef BuildWindowCore(HandleRef hwndParent)
    {
        var context = DataContext as UltrasoundVM;
        var psi = new ProcessStartInfo("UnityStandAlone.exe");

        psi.Arguments = "\"" + context.Workspace.Replace('\\', '/') + "\" " + context.SelectedFlexible;
        LoggerHelper.Write(GetType().FullName + "." + new StackTrace().GetFrame(0).GetMethod().Name + " : " + psi.Arguments, EventLogEntryType.Information);
        psi.WindowStyle = ProcessWindowStyle.Minimized;

        _process = Process.Start(psi);
        _process.WaitForInputIdle();
        while (_process.MainWindowHandle == IntPtr.Zero || !IsWindow(_process.MainWindowHandle))
        {
            Thread.Yield();
        }
        _unityHWND = _process.MainWindowHandle;
        SetParent(_unityHWND, hwndParent.Handle);

        var style = GetWindowLong(_unityHWND, GWL_STYLE);
        style = style & ~WS_CAPTION & ~WS_THICKFRAME; // Removes Caption bar and the sizing border
        style |= (WS_CHILD); // Must be a child window to be hosted
        SetWindowLong(_unityHWND, GWL_STYLE, style);

        SetWindowLong(_unityHWND, GWL_STYLE, WS_CHILD | WS_MAXIMIZE);

        SendMessage(_unityHWND, WM_ACTIVATE, WA_ACTIVE, IntPtr.Zero);

        _hwnd = new HandleRef(this, _unityHWND);
        return _hwnd;
    }

    protected override void DestroyWindowCore(HandleRef hwnd)
    {
        SendMessage(_hwnd.Handle, WM_ACTIVATE, WA_INACTIVE, IntPtr.Zero);

        _process.CloseMainWindow();

        _process.WaitForExit(5000);

        if (_process.HasExited == false)
        {
            _process.Kill();
        }

        _process.Close();
        _process.Dispose();
        _process = null;
    }
    #endregion
}

Notes:

Developping Computer

- OS : Windows 10 Home edition
- Unity 3D 5.5.2.f.1 free edition

Testing Computers
- OS : Windows 10 (Home edition & Pro Edition)

Of course I've tried to build the unity application with different parameters, same thing with my parent application.


问:
Get the result from the Query
I write this code :

```<code>Var Q : TFDQuery;
begin
Q := TFDQuery.Create(Self);
Q.Connection := FDConnection1;
Q.Params.CreateParam(ftString,'N',ptOutput);// Try also ptResult
Q.Params.CreateParam(ftInteger,'ID',ptInput);
Q.SQL.Text := 'SELECT NOM FROM EMPLOYEE WHERE ID_EMP = :ID';
Q.Params.ParamByName('ID').Value := 1;
Q.Active := True;
ShowMessage( VarToStr(Q.Params.ParamByName('N').Value) );
</code>```

The result should be the name of the employer.

I get an error :

'N' parameter not found

How can I get the result from the Query using the parameter?

If I can't , what is the the function of :

ptOutput

ptResult

答:
Try this code:

```<code>procedure TForm1.ExecuteQuery;
var
  SQL : String;
  Q : TFDQuery;
begin
  SQL := 'select ''Sami'' as NOM';  //  Tested with MS Sql Server backend
  try
    Q := TFDQuery.Create(Self);
    Q.Connection := FDConnection1;
    Q.Params.CreateParam(ftString, 'Nom', ptOutput);// Try also ptResult
    Q.SQL.Text := SQL;
    Q.Open;
    ShowMessage( IntToStr(Q.ParamCount));
    Caption := Q.FieldByName('Nom').AsString;
  finally
    Q.Free;  // otherwise you have a memory leak
  end;
end;
</code>```

You'll see that the created parameter no longer exists once the FDQuery is opened, because FireDAC "knows" that there is nothing it can do with it.

Then, replace Q.Open by Q.ExecSQL.  When that executes you get an exception
with the message

Cannot execute command returning result set.
  Hint: Use Open method for SELECT-like commands.

And that's your problem.  If you use a SELECT statement, you get a result set whether
you like it or not, and the way to access its contents is to do something like

```<code>Nom := Q.FieldByName('Nom').AsString
</code>```

You asked in a comment what is the point of ptOutput parameters.  Suppose your database has a stored procedure defined like this

Create Procedure spReturnValue(@Value varchar(80) out)
  as
  select @Value = 'something'

Then, in your code you could do

```<code>  SQL := 'exec spReturnValue :Value';  //  note the absence of the `out` qualifier in the invocation of the SP

  try
    Q := TFDQuery.Create(Self);
    Q.Connection := FDConnection1;
    Q.Params.CreateParam(ftString, 'Value', ptOutput);// Try also ptResult
    Q.SQL.Text := SQL;
    Q.ExecSQL;
    ShowMessage( IntToStr(Q.ParamCount));
    Caption := Q.ParamByName('Value').AsString;
  finally
    Q.Free;  // otherwise you have a memory leak
  end;
</code>```

which retrieves the output parameter of the Stored Proc into Q's Value parameter.

Title: Get the result from the Query

Body:
I write this code :

Var Q : TFDQuery;
begin
Q := TFDQuery.Create(Self);
Q.Connection := FDConnection1;
Q.Params.CreateParam(ftString,'N',ptOutput);// Try also ptResult
Q.Params.CreateParam(ftInteger,'ID',ptInput);
Q.SQL.Text := 'SELECT NOM FROM EMPLOYEE WHERE ID_EMP = :ID';
Q.Params.ParamByName('ID').Value := 1;
Q.Active := True;
ShowMessage( VarToStr(Q.Params.ParamByName('N').Value) );

The result should be the name of the employer.

I get an error :

'N' parameter not found

How can I get the result from the Query using the parameter?

If I can't , what is the the function of :

ptOutput

ptResult

Body:
Try this code:

procedure TForm1.ExecuteQuery;
var
  SQL : String;
  Q : TFDQuery;
begin
  SQL := 'select ''Sami'' as NOM';  //  Tested with MS Sql Server backend
  try
    Q := TFDQuery.Create(Self);
    Q.Connection := FDConnection1;
    Q.Params.CreateParam(ftString, 'Nom', ptOutput);// Try also ptResult
    Q.SQL.Text := SQL;
    Q.Open;
    ShowMessage( IntToStr(Q.ParamCount));
    Caption := Q.FieldByName('Nom').AsString;
  finally
    Q.Free;  // otherwise you have a memory leak
  end;
end;

You'll see that the created parameter no longer exists once the FDQuery is opened, because FireDAC "knows" that there is nothing it can do with it.

Then, replace Q.Open by Q.ExecSQL.  When that executes you get an exception
with the message

Cannot execute command returning result set.
  Hint: Use Open method for SELECT-like commands.

And that's your problem.  If you use a SELECT statement, you get a result set whether
you like it or not, and the way to access its contents is to do something like

Nom := Q.FieldByName('Nom').AsString

You asked in a comment what is the point of ptOutput parameters.  Suppose your database has a stored procedure defined like this

Create Procedure spReturnValue(@Value varchar(80) out)
  as
  select @Value = 'something'

Then, in your code you could do

  SQL := 'exec spReturnValue :Value';  //  note the absence of the `out` qualifier in the invocation of the SP

  try
    Q := TFDQuery.Create(Self);
    Q.Connection := FDConnection1;
    Q.Params.CreateParam(ftString, 'Value', ptOutput);// Try also ptResult
    Q.SQL.Text := SQL;
    Q.ExecSQL;
    ShowMessage( IntToStr(Q.ParamCount));
    Caption := Q.ParamByName('Value').AsString;
  finally
    Q.Free;  // otherwise you have a memory leak
  end;

which retrieves the output parameter of the Stored Proc into Q's Value parameter.


问:
How to Start SQL Server without TempDB
After the scheduled maintenance when the DBA tried to start the SQL Server;
it failed due to some corruption issue with storage subsystem.

Later on,  we identified that the drive on which we had our TempDB's data and log files was corrupt and it was preventing SQL Server from starting successfully.
(Drive was corrupt, so I am unable to read anything from that drive)

So basically we did not have Tempdb database on the server.

And we had to start SQL Server without TempDB

So how do we start the SQL Server without TempDB and how do we fix this?

答:
Before you try anything make sure you backup your data. If one drive failed, another one might fail and leave you without your data. Drives that are purchases at around the same time tend to fail around the same time too.

You need to do that even if some of the data is stored in a RAID array - RAID isn't the same as a backup. If something happens to the array, your best case scenario is that you'll wait for a few hours to recover the data. Worst case, you could lose it all.

The process is described in The SQL Server Instance That Will not Start in the TempDB location does not exist section, and other sites like Start SQL Server without tempdb.

You'll have to start SQL Server with Minimal Configuration. In that state, tempdb isn't used. You can do this with the -f command-line parameter. You can specify this parameter in the service's property page, or by calling sqlservr.exe -f from the command line, eg:

```<code>sqlservr -f
</code>```

Another option is to use the -t3608 trace flag which starts only the master database.

```<code>sqlservr -t3608
</code>```

After that, you need to connect to the server with the sqlcmd utility, eg :

```<code>sqlcmd -S myservername -E
</code>```

to connect using Windows authentication.

Once you do this, you can go to the master database and change the file location of the tempdb files:

```<code>USE master;
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = tempdev, FILENAME = 'E:\SQLData\tempdb.mdf');
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = templog, FILENAME = 'F:\SQLLog\templog.ldf');
GO
</code>```

After that, remove the parameters from the service (if you set them there) and restart the service.

Finally, you may have to reconsider the placement of TempDB. TempDB is used heavily for sorting, calculating window functions or in situations where the available RAM isn't enough. Some operations require creating intermediate results, which get stored in TempDB. In general, you should have
multiple tempdb files, although the exact number depends on the server's workload.

Title: How to Start SQL Server without TempDB

Body:
Before you try anything make sure you backup your data. If one drive failed, another one might fail and leave you without your data. Drives that are purchases at around the same time tend to fail around the same time too.

You need to do that even if some of the data is stored in a RAID array - RAID isn't the same as a backup. If something happens to the array, your best case scenario is that you'll wait for a few hours to recover the data. Worst case, you could lose it all.

The process is described in The SQL Server Instance That Will not Start in the TempDB location does not exist section, and other sites like Start SQL Server without tempdb.

You'll have to start SQL Server with Minimal Configuration. In that state, tempdb isn't used. You can do this with the -f command-line parameter. You can specify this parameter in the service's property page, or by calling sqlservr.exe -f from the command line, eg:

sqlservr -f

Another option is to use the -t3608 trace flag which starts only the master database.

sqlservr -t3608

After that, you need to connect to the server with the sqlcmd utility, eg :

sqlcmd -S myservername -E

to connect using Windows authentication.

Once you do this, you can go to the master database and change the file location of the tempdb files:

USE master;
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = tempdev, FILENAME = 'E:\SQLData\tempdb.mdf');
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = templog, FILENAME = 'F:\SQLLog\templog.ldf');
GO

After that, remove the parameters from the service (if you set them there) and restart the service.

Finally, you may have to reconsider the placement of TempDB. TempDB is used heavily for sorting, calculating window functions or in situations where the available RAM isn't enough. Some operations require creating intermediate results, which get stored in TempDB. In general, you should have
multiple tempdb files, although the exact number depends on the server's workload.


问:
Can create culture for en-EN on local dev machine
I just deployed our application to our azure staging environment and ran into an issue with the en-EN culture not being supported. After some digging I find out that there is no such culture, and I should use en-GB or en-USinstead.

But, now to my question. On my local development machine I've got no problems creating a CultureInfo with en-EN.

```<code>CultureInfo ci = new CultureInfo("en-EN");
Console.WriteLine("culture: "+ ci.ThreeLetterISOLanguageName);
</code>```

Outputs culture: eng

I also tried enumerating all cultures with CultureInfo.GetCultures(CultureTypes.AllCultures); and there's no corresponding en-EN culture in the result.

So, what's going on, why can I create a culture which shouldn't exist?

答:
As the documentation states:

Starting with apps that run under the .NET Framework 4 or later on Windows 7 or later, the method attempts to retrieve a CultureInfo object whose identifier is name from the operating system; if the operating system does not support that culture, and if name is not the name of a supplementary or replacement culture, the method throws a CultureNotFoundException exception.

So basically, your OS has en-EN as an alternate name of an existing culture (more likely en-US) while it's not there on the Azure VM.

The solution is: use a real culture name (which you can find here)

Body:
I just deployed our application to our azure staging environment and ran into an issue with the en-EN culture not being supported. After some digging I find out that there is no such culture, and I should use en-GB or en-USinstead.

But, now to my question. On my local development machine I've got no problems creating a CultureInfo with en-EN.

CultureInfo ci = new CultureInfo("en-EN");
Console.WriteLine("culture: "+ ci.ThreeLetterISOLanguageName);

Outputs culture: eng

I also tried enumerating all cultures with CultureInfo.GetCultures(CultureTypes.AllCultures); and there's no corresponding en-EN culture in the result.

So, what's going on, why can I create a culture which shouldn't exist?


问:
Swift 3 found nil when Firebase DB persistence is enabled
In my app I am using Firebase db to store my data, I have everything working as it should, with my tableview populating with the data from the db.  However I have found that on initial start it is quite slow to download the data, so I enable persistence in AppDelegate.  When I did this and ran the app it crashes on load with an unexpectedly found nil error.

```<code>FIRDatabase.database().persistenceEnabled = true
</code>```

is the line I added to AppDelegate under didFinishLaunching section.

The error occurs in this class on the line I have marked

```<code>import Foundation
import FirebaseDatabase
import CoreLocation

struct newTracks {

//Declerations
var locationManager = CLLocationManager()
let name: String!
let lat: Double!
let lon: Double!
let countryImage: String!
let link: String!
let ref: FIRDatabaseReference?
let distance: Double

//Initialize
init(name: String, trackId: Int, postcode: String, trackType: String, trackURL: String, locID: Int, lat: Double, lon: Double, phoneNumber: String, email: String, rating: Double, numrating: Double, totalrating: Double, countryImage: String, link: String, distance: Double) {
    self.name = name
    self.ref = nil
    self.lat = lat
    self.lon = lon
    self.countryImage = countryImage
    self.link = link
    self.distance = distance
 }

//Initialize data from Firebase
init(snapshot: FIRDataSnapshot) {

    let snapshotValue = snapshot.value as! [String: AnyObject]
    name = snapshotValue["name"] as! String
    lat = snapshotValue["lat"]as! Double
    lon = snapshotValue["long"]as! Double
    ref = snapshot.ref
    countryImage = snapshotValue["country"] as! String   <--  Unexpectedly found nil
    link = snapshotValue["link"] as! String

    let currentLat = self.locationManager.location!.coordinate.latitude
    let currentLon = self.locationManager.location!.coordinate.longitude
    let myLocation = CLLocation(latitude: currentLat, longitude: currentLon)
    let loc = CLLocation(latitude: lat, longitude: lon)
    let distanceInMiles = round(myLocation.distance(from: loc) / 1609.34)
    distance = distanceInMiles

}

func toAnyObject() -> Any {
    return [
        "name": name,
        "lat": lat,
        "lon": lon,
        "countryImage": countryImage,
        "link": link,
        "distance": distance
    ]

 }

}
</code>```

I don't get why this works ok when persistence isn't switched on, but when I enable it it crashes.  Any help is much appreciated.

答:
You have marked countryImage as Optional value. Your snapshot may not have value for "country".
Try to change:

```<code>let countryImage: String!
</code>```

to:

```<code>let countryImage: String
</code>```

EDIT:
Maybe, when you are turning persistance on, your application is taking old data from cache. And this data doesn't have ["country"] in snapshot value. So it founds nil -> throwing error. Check your snapshotValue through breakpoint. And check if it has value for country

Hope it helps

Body:
In my app I am using Firebase db to store my data, I have everything working as it should, with my tableview populating with the data from the db.  However I have found that on initial start it is quite slow to download the data, so I enable persistence in AppDelegate.  When I did this and ran the app it crashes on load with an unexpectedly found nil error.

FIRDatabase.database().persistenceEnabled = true

is the line I added to AppDelegate under didFinishLaunching section.

The error occurs in this class on the line I have marked

import Foundation
import FirebaseDatabase
import CoreLocation

struct newTracks {

//Declerations
var locationManager = CLLocationManager()
let name: String!
let lat: Double!
let lon: Double!
let countryImage: String!
let link: String!
let ref: FIRDatabaseReference?
let distance: Double

//Initialize
init(name: String, trackId: Int, postcode: String, trackType: String, trackURL: String, locID: Int, lat: Double, lon: Double, phoneNumber: String, email: String, rating: Double, numrating: Double, totalrating: Double, countryImage: String, link: String, distance: Double) {
    self.name = name
    self.ref = nil
    self.lat = lat
    self.lon = lon
    self.countryImage = countryImage
    self.link = link
    self.distance = distance
 }

//Initialize data from Firebase
init(snapshot: FIRDataSnapshot) {

    let snapshotValue = snapshot.value as! [String: AnyObject]
    name = snapshotValue["name"] as! String
    lat = snapshotValue["lat"]as! Double
    lon = snapshotValue["long"]as! Double
    ref = snapshot.ref
    countryImage = snapshotValue["country"] as! String   <--  Unexpectedly found nil
    link = snapshotValue["link"] as! String

    let currentLat = self.locationManager.location!.coordinate.latitude
    let currentLon = self.locationManager.location!.coordinate.longitude
    let myLocation = CLLocation(latitude: currentLat, longitude: currentLon)
    let loc = CLLocation(latitude: lat, longitude: lon)
    let distanceInMiles = round(myLocation.distance(from: loc) / 1609.34)
    distance = distanceInMiles

}

func toAnyObject() -> Any {
    return [
        "name": name,
        "lat": lat,
        "lon": lon,
        "countryImage": countryImage,
        "link": link,
        "distance": distance
    ]

 }

}

I don't get why this works ok when persistence isn't switched on, but when I enable it it crashes.  Any help is much appreciated.

Body:
You have marked countryImage as Optional value. Your snapshot may not have value for "country".
Try to change:

let countryImage: String!

to:

let countryImage: String

EDIT:
Maybe, when you are turning persistance on, your application is taking old data from cache. And this data doesn't have ["country"] in snapshot value. So it founds nil -> throwing error. Check your snapshotValue through breakpoint. And check if it has value for country

Hope it helps


问:
WebDriverException: Message: unknown error: jQuery is not defined error in robot framework
I am using Selenium2Library '1.7.4' and Robot Framework 2.9.2 (Python 2.7.8 on win32). If I try to give locator as jQuery, the following exception occurs: WebDriverException: Message: unknown error: jQuery is not defined. Please advise which version of Selenium2Library and 'Robot Framework' combination works to identify jQuery as a locator.

答:
From Selenium 3.0 - Gecko driver is required to run automation scripts in firefox

Selenium version less than 3.0 works.

Try with the following versions:

robotframework (3.0.2)

robotframework-selenium2library (1.8.0)

selenium (2.53.1)