问:
SSLv2Hello - javax.net.ssl.SSLException: Received fatal alert: unexpected_message
I am trying to call an SSL protected web service running on JDK7 / WildFly 8.2 with a Java 6 (update 31) based client.

The first problem I encountered on the client was:

javax.net.ssl.SSLException: Received fatal alert: unexpected_message

By setting javax.net.debug to all on both sides, I got the following hint on the server side:

javax.net.ssl.SSLHandshakeException: SSLv2Hello is disabled

Quick research shows that,

SSLv2Hello disabled by default on the client: In Java SE 7, SSLv2Hello is removed from the default enabled protocol list on the client.

So I have tried to enable SSLv2Hello on WildFly in standalone.xml:

```<code><https-listener name="https"
                socket-binding="https"
                security-realm="UndertowRealm"
                enabled-protocols="SSLv2, SSLv2Hello, TLSv1, TLSv1.1, TLSv1.2"
                />
</code>```

And the result on the server is:

javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)

So I realize, I should be trying to force TLS on the client instead of enabling SSLv2Hello on the server. I have tried to set System.setProperty("https.protocols", "TLSv1"); before my web service call with no effect.

What should I configure and how, to get the handshake working?

I have printed the supported cipher suites from the default SSLSocketFactory on the server:

```<code>TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
TLS_RSA_WITH_AES_128_CBC_SHA,
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
SSL_RSA_WITH_3DES_EDE_CBC_SHA,
TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
TLS_ECDHE_RSA_WITH_RC4_128_SHA,
SSL_RSA_WITH_RC4_128_SHA,
TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
TLS_ECDH_RSA_WITH_RC4_128_SHA,
SSL_RSA_WITH_RC4_128_MD5,
TLS_EMPTY_RENEGOTIATION_INFO_SCSV
</code>```

答:
You don't need to enable SSLv2 at the server. You need to disable the SSLv2Hello pseudo-protocol at the client, by removing SSLv2Hello from the enabled TLS protocols and leaving the others:

```<code>System.setProperty("https.protocols", "TLSv1,TLSV1.1,TLSV1.2");
</code>```

and maybe SSLv3 if that makes it happy: it won't for much longer, so try not to have to do that.

Note that it is a pseudo-protocol. It is not SSLv2, it is a compatibility measure to allow certain arguably broken servers to accept the hello. The session however operates at SSLv3 or above. It is also obsolete.

Body:
I am trying to call an SSL protected web service running on JDK7 / WildFly 8.2 with a Java 6 (update 31) based client.

The first problem I encountered on the client was:

javax.net.ssl.SSLException: Received fatal alert: unexpected_message

By setting javax.net.debug to all on both sides, I got the following hint on the server side:

javax.net.ssl.SSLHandshakeException: SSLv2Hello is disabled

Quick research shows that,

SSLv2Hello disabled by default on the client: In Java SE 7, SSLv2Hello is removed from the default enabled protocol list on the client.

So I have tried to enable SSLv2Hello on WildFly in standalone.xml:

<https-listener name="https"
                socket-binding="https"
                security-realm="UndertowRealm"
                enabled-protocols="SSLv2, SSLv2Hello, TLSv1, TLSv1.1, TLSv1.2"
                />

And the result on the server is:

javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)

So I realize, I should be trying to force TLS on the client instead of enabling SSLv2Hello on the server. I have tried to set System.setProperty("https.protocols", "TLSv1"); before my web service call with no effect.

What should I configure and how, to get the handshake working?

I have printed the supported cipher suites from the default SSLSocketFactory on the server:

TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
TLS_RSA_WITH_AES_128_CBC_SHA,
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
SSL_RSA_WITH_3DES_EDE_CBC_SHA,
TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
TLS_ECDHE_RSA_WITH_RC4_128_SHA,
SSL_RSA_WITH_RC4_128_SHA,
TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
TLS_ECDH_RSA_WITH_RC4_128_SHA,
SSL_RSA_WITH_RC4_128_MD5,
TLS_EMPTY_RENEGOTIATION_INFO_SCSV

Body:
You don't need to enable SSLv2 at the server. You need to disable the SSLv2Hello pseudo-protocol at the client, by removing SSLv2Hello from the enabled TLS protocols and leaving the others:

System.setProperty("https.protocols", "TLSv1,TLSV1.1,TLSV1.2");

and maybe SSLv3 if that makes it happy: it won't for much longer, so try not to have to do that.

Note that it is a pseudo-protocol. It is not SSLv2, it is a compatibility measure to allow certain arguably broken servers to accept the hello. The session however operates at SSLv3 or above. It is also obsolete.


来源: stackexchange

问:
How can you check if SQL command is still running? Or is it frozen/dead...?
I created an index for my ginormous (250 million+ records) SQL table and it has been several hours. How can I tell if it's still going? Or if the process is frozen/dead?

If you have an answer about how to check if SQL (SQLite3) is still running in general, that'd be super. However, if you have an approach for my specific case, that's good as well. This is what I did.

CREATE INDEX index_name ON table_name(column_name);

答:
Have you tried to check:

```<code>sp_who2
</code>```

You can also use active to see active connections:

```<code>sp_who2 active
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Have you tried to check:

sp_who2

You can also use active to see active connections:

sp_who2 active


问:
Retrieve list of tasks in a queue in Celery
How can I retrieve a list of tasks in a queue that are yet to be processed?</p>

答:
I've come to the conclusion the best way to get the number of jobs on a queue is to use rabbitmqctl as has been suggested several times here. To allow any chosen user to run the command with sudo I followed the instructions here (I did skip editing the profile part as I don't mind typing in sudo before the command.)

I also grabbed jamesc's grep and cut snippet and wrapped it up in subprocess calls.

```<code>from subprocess import Popen, PIPE
p1 = Popen(["sudo", "rabbitmqctl", "list_queues", "-p", "[name of your virtula host"], stdout=PIPE)
p2 = Popen(["grep", "-e", "^celery\s"], stdin=p1.stdout, stdout=PIPE)
p3 = Popen(["cut", "-f2"], stdin=p2.stdout, stdout=PIPE)
p1.stdout.close()
p2.stdout.close()
print("number of jobs on queue: %i" % int(p3.communicate()[0]))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've come to the conclusion the best way to get the number of jobs on a queue is to use rabbitmqctl as has been suggested several times here. To allow any chosen user to run the command with sudo I followed the instructions here (I did skip editing the profile part as I don't mind typing in sudo before the command.)

I also grabbed jamesc's grep and cut snippet and wrapped it up in subprocess calls.

from subprocess import Popen, PIPE
p1 = Popen(["sudo", "rabbitmqctl", "list_queues", "-p", "[name of your virtula host"], stdout=PIPE)
p2 = Popen(["grep", "-e", "^celery\s"], stdin=p1.stdout, stdout=PIPE)
p3 = Popen(["cut", "-f2"], stdin=p2.stdout, stdout=PIPE)
p1.stdout.close()
p2.stdout.close()
print("number of jobs on queue: %i" % int(p3.communicate()[0]))


问:
Sap Hana: function like "age" in PostgreSQL
Is there a function in SAP HANA which has the same semantics as age in PostgreSQL, that is, which returns the difference between a given time stamp and the current time stamp?

I know

```<code>ADD_YEARS(COLUMN_NAME, 2) <= NOW()
</code>```

in SAP HANA would correspond to

```<code>(extract (year from age( COLUMN_NAME )) <= 2 )
</code>```

in PostgreSQL. Unfortunately, this is not an option for me, since I don't have the information <= 2. What I am looking for is a way to translate age(COLUMN_NAME) (PostgreSQL) to SAP HANA.

Any ideas?

答:
This worked for me to calculate age in years in SPS11:</p>

```<code>if(format(now(), 'MMDD') >= format("DateOfBirth", 'MMDD'),
    int(component(now(), 1)) - int(component("DateOfBirth", 1)),
        if(int(component(now(), 1)) = int(component("DateOfBirth", 1)), 0,
            int(component(now(), 1)) - int(component("DateOfBirth", 1)) - 1))
</code>```

Body:
Is there a function in SAP HANA which has the same semantics as age in PostgreSQL, that is, which returns the difference between a given time stamp and the current time stamp?

I know

ADD_YEARS(COLUMN_NAME, 2) <= NOW()

in SAP HANA would correspond to

(extract (year from age( COLUMN_NAME )) <= 2 )

in PostgreSQL. Unfortunately, this is not an option for me, since I don't have the information <= 2. What I am looking for is a way to translate age(COLUMN_NAME) (PostgreSQL) to SAP HANA.

Any ideas?

Body:
This worked for me to calculate age in years in SPS11:

if(format(now(), 'MMDD') >= format("DateOfBirth", 'MMDD'),
    int(component(now(), 1)) - int(component("DateOfBirth", 1)),
        if(int(component(now(), 1)) = int(component("DateOfBirth", 1)), 0,
            int(component(now(), 1)) - int(component("DateOfBirth", 1)) - 1))


问:
how to version packages in golang?
I've read a whole bunch of articles and SO questions on importing 3rd party go packages which all seems straight forward, but what I don't understand is that none that I have read make any references to versioning. In Dartlang there's the pubspec file that defines your package including its version and its dependencies including their required versions. What if I do a go get github.com/gorilla/sessions and write my app then 6 months later I have to clear my directories and re get everything again, in which time that package has been update and broken backwards compatibility with my code that was using the older version?

答:
I use dep as a dependency management tool for golang project. Please use the following link dep tool for more info.

dep is a dependency management tool for Go. It requires Go 1.9 or newer to compile.

dep was the "official experiment." The Go toolchain, as of 1.11, has (experimentally) adopted an approach that sharply diverges from dep. As a result, we are continuing development of dep, but gearing work primarily towards the development of an alternative prototype for versioning behavior in the toolchain.

Current status: January 2019

dep is safe for production use.

Title: how to version packages in golang?

ContentLicense: CC BY-SA 4.0


问:
iOS app doesn't show on iTunes Connect when trying to deploy on testflight
I've read a lot of tutorials and stackoverflow questions similar but I'm unable to figure out what's happening.

So I an an iPad application that I can successfully build in Xcode and on iTunes connect see the app version processing...

After a certain amount of time, it just disappears from the menu. As in it's no longer visible.

I've been following guides similar to: https://www.raywenderlich.com/133121/testflight-tutorial-ios-beta-testing

But the screenshots on internal testing show's a Select Version To Test option which I don't see:

Does anyone have any idea on how to debug this or what's going on? Because the Archive bundle looks like it's deploying it to the app store, I can see it on the iOS Builds activity but after processing I can't find it anywhere.

答:
Recently we faced this issue couple of times. In iOS Builds section it shows Processing and after some time it disappears.

Reason is due to some errors/ issues with the ipa submitted to iTunesConnect.

Apple sends the error messages to people added in the Users and Roles section of iTunesConnect. You can check the people added in the the Users & Roles section and see the mails sent from Apple for any errors related to the app


问:
Python - reordering items in list by moving some items to the front while keeping the rest in the same order
I am trying to reorder items in a list in a way illustrated by the following example:

Suppose the list before reordering is:

```<code>list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code>```

I want to implement a method called reorder_list(list, custom_order) such that:

```<code>list1 = reorder_list(list1, [3, 6, 12, 9])
print(list1)

Out: [3, 6, 9, 1, 2, 4, 5, 7, 8, 10]
</code>```

Explanation: [3, 6, 12, 9] is a custom order I am specifying. 12 is not in  list1 so it will be ignored. 3,6,9 are in list1, so they get moved to the front of the list and their order is the same as in [3, 6, 12, 9]. The remaining items in list1 are after 3,6,9 and in the original order.

Is there is an easier way (and a Pythonic way) than implementing the C-like loop code. For my purpose I care more about code simplicity than performance.

答:
```<code>def reorder_list(list_main, custom_order):
    # initializing empty list
    list1 = list()

    # to add values of custom list to list1 which are present in main list
    for value in custom_order:
        # add only the values which are present in main list
        if value in list_main:
            list1.append(value)
    # to add remaining element of main list to list1 which are not present in list1
    for value in list_main:
        if value not in list1:
            list1.append(value)

    return  list1

list1 = [1,2,3,4,5,6,7,8,9,10]
list1 = reorder_list(list1, [3,6,12,9])
print(list1)
</code>```

Body:
I am trying to reorder items in a list in a way illustrated by the following example:

Suppose the list before reordering is:

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I want to implement a method called reorder_list(list, custom_order) such that:

list1 = reorder_list(list1, [3, 6, 12, 9])
print(list1)

Out: [3, 6, 9, 1, 2, 4, 5, 7, 8, 10]

Explanation: [3, 6, 12, 9] is a custom order I am specifying. 12 is not in  list1 so it will be ignored. 3,6,9 are in list1, so they get moved to the front of the list and their order is the same as in [3, 6, 12, 9]. The remaining items in list1 are after 3,6,9 and in the original order.

Is there is an easier way (and a Pythonic way) than implementing the C-like loop code. For my purpose I care more about code simplicity than performance.


问:
Perl print vietnamese characters
I tried to read the vietnamese address from Mysql databases through perl program. But it display some special characters which is not recognize. When i see the string in phpMyAdmin is ok. And using php to retrieve and print the string also no problem. Just only using perl to print out the string will become weird.

Original word

```<code>QL37, Phố Vôi, tt. Vôi, Lạng Giang, Bắc Giang, Vietnam
</code>```

After print become

```<code>QL37, Pho├í Vo├ói, tt. Vo├ói, La├»ng Giang, Ba├⌐c Giang, Vietnam
</code>```

The database structure

```<code>CREATE TABLE `address` (
    `Address_Id` int(11) NOT NULL,
    `Coordinate_Lat` float(15,6) NOT NULL,
    `Coordinate_Long` float(15,6) NOT NULL,
    `Address` varchar(300) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
</code>```

Perl Code

```<code>my $sql = "SELECT * FROM `address`";
my $sth = $DBIconnect->prepare($sql);
$sth->execute or die "SQL Error: $DBIconnect::errstr\n";
while (my $row = $sth->fetchrow_hashref) {
    print $row->{'Address'};
}
</code>```

Print Screen

LINK1 - PHPMyAdmin look fine

LINK2 - Retrieve and print out error

答:
I did try set at DBI connetion with the following code. But still the same result.

```<code>my $dsn= "dbi:mysql:database=$database:$host;mysql_connnect_timeout=15;user=$user;password=$password";
my $DBI = DBI->connect($dsn, {mysql_enable_utf8 => 1}) or die "Unable to connect: $DBI::errstr\n";
$DBI->do("SET NAMES utf8");
$DBI->do("SET CHARACTER SET utf8");
</code>```

After that i copy out the string and test without connection to database. I'm using the Encode for print. Only the cp850 and cp437 can convert atleast the symbol ô

```<code>use utf8;
use Encode 'encode';

$address="QL37, Phố Vôi, tt. Vôi, Lạng Giang, Bắc Giang, Vietnam";

print $address."\n";
# QL37, Ph? V⌠i, tt. V⌠i, L?ng Giang, B?c Giang, Vietnam
print encode cp850 => $address."\n";
# QL37, Ph? Vôi, tt. Vôi, L?ng Giang, B?c Giang, Vietnam
print encode cp1252 => $address."\n";
# QL37, Ph? V⌠i, tt. V⌠i, L?ng Giang, B?c Giang, Vietnam
print encode cp437 => $address."\n";
# QL37, Ph? Vôi, tt. Vôi, L?ng Giang, B?c Giang, Vietnam
print encode cp1258 => $address."\n";
# QL37, Ph? V⌠i, tt. V⌠i, L?ng Giang, B?c Giang, Vietnam
print encode VISCII => $address."\n";
# QL37, Ph? V⌠i, tt. V⌠i, L?ng Giang, B?c Giang, Vietnam
</code>```

Actually the main problem is after i process the data and need insert back to database. The print command is just for my debug. i have try to insert the address back to msyql, the string will become weird also.

Title: Perl print vietnamese characters

Body:
I tried to read the vietnamese address from Mysql databases through perl program. But it display some special characters which is not recognize. When i see the string in phpMyAdmin is ok. And using php to retrieve and print the string also no problem. Just only using perl to print out the string will become weird.

Original word

QL37, Phố Vôi, tt. Vôi, Lạng Giang, Bắc Giang, Vietnam

After print become

QL37, Pho├í Vo├ói, tt. Vo├ói, La├»ng Giang, Ba├⌐c Giang, Vietnam

The database structure

CREATE TABLE `address` (
    `Address_Id` int(11) NOT NULL,
    `Coordinate_Lat` float(15,6) NOT NULL,
    `Coordinate_Long` float(15,6) NOT NULL,
    `Address` varchar(300) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Perl Code

my $sql = "SELECT * FROM `address`";
my $sth = $DBIconnect->prepare($sql);
$sth->execute or die "SQL Error: $DBIconnect::errstr\n";
while (my $row = $sth->fetchrow_hashref) {
    print $row->{'Address'};
}

Print Screen

LINK1 - PHPMyAdmin look fine

LINK2 - Retrieve and print out error

Body:
I did try set at DBI connetion with the following code. But still the same result.

my $dsn= "dbi:mysql:database=$database:$host;mysql_connnect_timeout=15;user=$user;password=$password";
my $DBI = DBI->connect($dsn, {mysql_enable_utf8 => 1}) or die "Unable to connect: $DBI::errstr\n";
$DBI->do("SET NAMES utf8");
$DBI->do("SET CHARACTER SET utf8");

After that i copy out the string and test without connection to database. I'm using the Encode for print. Only the cp850 and cp437 can convert atleast the symbol ô

use utf8;
use Encode 'encode';

$address="QL37, Phố Vôi, tt. Vôi, Lạng Giang, Bắc Giang, Vietnam";

print $address."\n";
# QL37, Ph? V⌠i, tt. V⌠i, L?ng Giang, B?c Giang, Vietnam
print encode cp850 => $address."\n";
# QL37, Ph? Vôi, tt. Vôi, L?ng Giang, B?c Giang, Vietnam
print encode cp1252 => $address."\n";
# QL37, Ph? V⌠i, tt. V⌠i, L?ng Giang, B?c Giang, Vietnam
print encode cp437 => $address."\n";
# QL37, Ph? Vôi, tt. Vôi, L?ng Giang, B?c Giang, Vietnam
print encode cp1258 => $address."\n";
# QL37, Ph? V⌠i, tt. V⌠i, L?ng Giang, B?c Giang, Vietnam
print encode VISCII => $address."\n";
# QL37, Ph? V⌠i, tt. V⌠i, L?ng Giang, B?c Giang, Vietnam

Actually the main problem is after i process the data and need insert back to database. The print command is just for my debug. i have try to insert the address back to msyql, the string will become weird also.


问:
C# + WPF : how should I do proper checks/guards/casts when accessing control values?
This is probably pretty basic, but I'm just picking up C# after many years working with other languages, and I've unfortunately grown used to loose and dynamic typing.  Now, in building a WPF form with a lot of checkboxes, I notice that my code to do simple things like determine whether a checkbox is checked is actually quite complicated due to the need to check for nulls and cast the results.  I end up with helper functions like:

```<code>    private bool isChecked(CheckBox control) {
        return control != null && control.IsChecked != null && control.IsChecked.HasValue && (bool)control.IsChecked;
    }
</code>```

so that in my logic code, I can just do

```<code>    if (isChecked(opticsCheckBox))
    {
        // whatever I need to do if opticsCheckBox is checked
    }
</code>```

Is this the normal way of doing things in C# (with WPF), or am I missing something simple?  Basically I'm finding the nested layers of conditionals to check every object for null all the time to be a warning sign of bad code (and the fact that I could forget a check).  Not sure what I should be doing though.

Should I be using try ... catch everywhere even though the control not being present or checked isn't really an exceptional condition?  That seems to me like it would end up being just as cluttered.

Another example to clarify:
When I would like to write something like:

```<code>    maxWeight = (int)maxWeightComboBox.SelectedItem;
</code>```

I find myself instead writing:

```<code>    if (maxWeightComboBox != null && maxWeightComboBox.SelectedItem != null)
    {
        ComboBoxItem item = (ComboBoxItem)maxWeightComboBox.SelectedItem;
        maxWeight = Int32.Parse(item.Content.ToString());
    }
</code>```

答: With nullable types (including references), you can use the ?? operator to specify a default value to be used if the object is null. So control.IsChecked != null && control.IsChecked could be replaced by control.IsChecked ?? false. This doesn't solve all your problems, but it helps to reduce the amount of code you type in some cases.

Body:
This is probably pretty basic, but I'm just picking up C# after many years working with other languages, and I've unfortunately grown used to loose and dynamic typing.  Now, in building a WPF form with a lot of checkboxes, I notice that my code to do simple things like determine whether a checkbox is checked is actually quite complicated due to the need to check for nulls and cast the results.  I end up with helper functions like:

    private bool isChecked(CheckBox control) {
        return control != null && control.IsChecked != null && control.IsChecked.HasValue && (bool)control.IsChecked;
    }

so that in my logic code, I can just do

    if (isChecked(opticsCheckBox))
    {
        // whatever I need to do if opticsCheckBox is checked
    }

Is this the normal way of doing things in C# (with WPF), or am I missing something simple?  Basically I'm finding the nested layers of conditionals to check every object for null all the time to be a warning sign of bad code (and the fact that I could forget a check).  Not sure what I should be doing though.

Should I be using try ... catch everywhere even though the control not being present or checked isn't really an exceptional condition?  That seems to me like it would end up being just as cluttered.

Another example to clarify:
When I would like to write something like:

    maxWeight = (int)maxWeightComboBox.SelectedItem;

I find myself instead writing:

    if (maxWeightComboBox != null && maxWeightComboBox.SelectedItem != null)
    {
        ComboBoxItem item = (ComboBoxItem)maxWeightComboBox.SelectedItem;
        maxWeight = Int32.Parse(item.Content.ToString());
    }


问:
I can load data from database with ajax and show in modal include ckeditor but i can't edit/save those data. I used Codeigniter 3

I can Load data with ajax but, I can't save data with ajax in ckeditor

Here's my ajax in view

```<code>$.ajax({

    url : "<?php echo base_url('admin/perusahaan_baik/edit_narasi_gcg')?>/" + id,
    type: "GET",
    dataType: "JSON",
    success: function(data)
    {

        $('[name="id"]').val(data.id);
        $('[name="posting_date"]').val(data.posting_date);
        $('[name="description"]').val(CKEDITOR.instances.description.setData(data.description));
</code>```

$('#modal_narasi').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Perusahaan Baik'); // Set title to Bootstrap modal title
},
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error get data from ajax');
        }
    });

Here's my controller

```<code>    $data = array(

            'posting_date' => $this->input->post('posting_date'),
            'description' => $this->input->post('description')
        );

    $this->narasi_model->update_narasi_gcg(array('id' => $this->input->post('id')), $data);

    echo json_encode(array("status" => TRUE));
</code>```

Here's my model

```<code>    public function get_by_id($id)
    {
        $this->db->from($this->table);
        $this->db->where('id',$id);
        $query = $this->db->get();

        return $query->row();
    }

    public function update_narasi_gcg($where, $data)
    {
        $this->db->update($this->table, $data, $where);
        return $this->db->affected_rows();
    }
</code>```

Here's my div

```<code>                    <div class="form-group">
                        <label class="control-label col-md-3">Posisi ID</label>
                        <div class="col-md-9">
                            <textarea name="description" id="description" rows="10" cols="80">

                      </textarea>
                        </div>
                    </div>
</code>```

答:
I input this code and it works. Thanks yall

```<code>CKEDITOR.instances['description'].on('change',function(){
CKEDITOR.instances['description'].updateElement();
});
</code>```

Body:
I can Load data with ajax but, I can't save data with ajax in ckeditor

Here's my ajax in view

$.ajax({

    url : "<?php echo base_url('admin/perusahaan_baik/edit_narasi_gcg')?>/" + id,
    type: "GET",
    dataType: "JSON",
    success: function(data)
    {

        $('[name="id"]').val(data.id);
        $('[name="posting_date"]').val(data.posting_date);
        $('[name="description"]').val(CKEDITOR.instances.description.setData(data.description));

$('#modal_narasi').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Perusahaan Baik'); // Set title to Bootstrap modal title
},
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error get data from ajax');
        }
    });

Here's my controller

    $data = array(

            'posting_date' => $this->input->post('posting_date'),
            'description' => $this->input->post('description')
        );

    $this->narasi_model->update_narasi_gcg(array('id' => $this->input->post('id')), $data);

    echo json_encode(array("status" => TRUE));

Here's my model

    public function get_by_id($id)
    {
        $this->db->from($this->table);
        $this->db->where('id',$id);
        $query = $this->db->get();

        return $query->row();
    }

    public function update_narasi_gcg($where, $data)
    {
        $this->db->update($this->table, $data, $where);
        return $this->db->affected_rows();
    }

Here's my div

                        Posisi ID

                            <textarea name="description" id="description" rows="10" cols="80">

                      </textarea>

Body:
I input this code and it works. Thanks yall

CKEDITOR.instances['description'].on('change',function(){
CKEDITOR.instances['description'].updateElement();
});


问:
Different Loggers with Different configurations Log4j
```<code>import org.apache.log4j.*;

public class LoggingInJava {

    public static void main(String[] args) {
        PropertyConfigurator.configure("mylog4j1.properties");
        myLogger.info("1");
        PropertyConfigurator.configure("mylog4j2.properties");
        myLogger2.info("2");

        myLogger.info("3");
    }
}
</code>```

I am beginner in logging.

I have two different properties files  - mylog4j1.properties has fileappender which outputs to file1  and mylog4j2.properties has fileAppender which outputs to file2 .

I want myLogger1 to work with mylog4j1 configurations and similar for next .

But if I write my code as above , I am not getting expected result .

Expected Result:

file1: 1  3

  file2: 2

Actual  Result:

file1: 1
  file2: 2 3

I did try learning from other questions from stackoverflow but even then I couldnt figure it out .

Please help me find my mistake or whether I am making conceptual error in Log4j framework.

答:
Why you use two properties files? You can do this from 1 properties file.

Here is the sample for, how implement that

```<code># Direct log messages to a log file
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.File=/home/logs/firstLog.log
log4j.appender.FILE.MaxFileSize=1MB
log4j.appender.FILE.MaxBackupIndex=1
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.Append=true
log4j.appender.FILE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n

log4j.appender.SECOND=org.apache.log4j.RollingFileAppender
log4j.appender.SECOND.File=/home/logs/secondLog.log
log4j.appender.SECOND.MaxFileSize=1MB
log4j.appender.SECOND.MaxBackupIndex=1
log4j.appender.SECOND.layout=org.apache.log4j.PatternLayout
log4j.appender.SECOND.Append=true
log4j.appender.SECOND.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n

# Root logger option
log4j.rootLogger=TRACE, FILE

log4j.category.testngLogger=DEBUG, SECOND
log4j.additivity.testngLogger=false
</code>```

Body:
import org.apache.log4j.*;

public class LoggingInJava {

    public static void main(String[] args) {
        PropertyConfigurator.configure("mylog4j1.properties");
        myLogger.info("1");
        PropertyConfigurator.configure("mylog4j2.properties");
        myLogger2.info("2");

        myLogger.info("3");
    }
}

I am beginner in logging.

I have two different properties files  - mylog4j1.properties has fileappender which outputs to file1  and mylog4j2.properties has fileAppender which outputs to file2 .

I want myLogger1 to work with mylog4j1 configurations and similar for next .

But if I write my code as above , I am not getting expected result .

Expected Result:

file1: 1  3

  file2: 2

Actual  Result:

file1: 1
  file2: 2 3

I did try learning from other questions from stackoverflow but even then I couldnt figure it out .

Please help me find my mistake or whether I am making conceptual error in Log4j framework.

Body:
Why you use two properties files? You can do this from 1 properties file.

Here is the sample for, how implement that

# Direct log messages to a log file
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.File=/home/logs/firstLog.log
log4j.appender.FILE.MaxFileSize=1MB
log4j.appender.FILE.MaxBackupIndex=1
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.Append=true
log4j.appender.FILE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n

log4j.appender.SECOND=org.apache.log4j.RollingFileAppender
log4j.appender.SECOND.File=/home/logs/secondLog.log
log4j.appender.SECOND.MaxFileSize=1MB
log4j.appender.SECOND.MaxBackupIndex=1
log4j.appender.SECOND.layout=org.apache.log4j.PatternLayout
log4j.appender.SECOND.Append=true
log4j.appender.SECOND.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n

# Root logger option
log4j.rootLogger=TRACE, FILE

log4j.category.testngLogger=DEBUG, SECOND
log4j.additivity.testngLogger=false


问:
How to upload a .mp3 file in HTML / Javascript and send to Java backend
We're trying to upload a song (.mp3) file from a JSP frontend written in HTML / Javascript. We need to upload to our Java backend using websockets. Does anyone have any suggestions on how we would could go about doing this?

Currently we are doing something like this on our JSP file:

```<code>    <h1>Please Choose a Song file</h1>
    <form name = "JSONUploadForm">
        <input type = "file" name="file" accept = ".mp3"/> <br/>
        <input type = "button" value = "Click to upload!" name = "button" onClick = "submitSong();"/>
    </form>
</code>```

Then we have our javascript function submitSong()

```<code>function submitSong(){
    var songStuffs = document.getElementById("file");
    console.log(songStuffs); --> we get "null" here
    sendMessage(songStuffs);
    alert("song sent");
}

function sendMessage(val, string) {
    socket.send(string);
    return false;
}
</code>```

Also, here is our connect to server function. However, this functions correctly.

```<code>function connectToServer() {
    socket = new
    WebSocket("ws://localhost:8080/Project/socket");
    socket.onopen = function(event) {
    console.log("connected!");
}
</code>```

You can also see our server side (.java file):

```<code>@OnMessage
public void onMessage(String message, Session session) throws IOException, EncodeException {
        FileWriter fw = new FileWriter(new File(songName + ".mp3"));
        fw.write(song);

        BufferedReader fr = new BufferedReader(new FileReader(songName + ".mp3"));
        String data = fr.readLine();

        System.out.println("Song: " + data); --> Here we get "song: null"
}
</code>```

Any suggestions would be greatly appreciated!

答:
Try with this, If you have to upload file you should add enctype in form.

```<code><form enctype="multipart/form-data">
      <input type = "file" name="file" id="song" accept = ".mp3"/>
</form>
</code>```

Update:

You can use simply WebSocketFileTransfer plugin to send your file. This plugin helps in with many features like Auth, progress status, file/blob compatibility.

```<code>var songStuffs = document.getElementById("song").files[0];
var transfer = new WebSocketFileTransfer({
    url: 'ws://ip:port/path/to/upload_web_socket_server',
    file: songStuffs,
    progress: function(event) {
        // Update the progress bar
    },
    success: function(event) {
        // Do something
    }
  });

transfer.start();
</code>```

Body:
We're trying to upload a song (.mp3) file from a JSP frontend written in HTML / Javascript. We need to upload to our Java backend using websockets. Does anyone have any suggestions on how we would could go about doing this?

Currently we are doing something like this on our JSP file:

Please Choose a Song file

    <form name = "JSONUploadForm">
        <input type = "file" name="file" accept = ".mp3"/>

        <input type = "button" value = "Click to upload!" name = "button" onClick = "submitSong();"/>
    </form>

Then we have our javascript function submitSong()

function submitSong(){
    var songStuffs = document.getElementById("file");
    console.log(songStuffs); --> we get "null" here
    sendMessage(songStuffs);
    alert("song sent");
}

function sendMessage(val, string) {
    socket.send(string);
    return false;
}

Also, here is our connect to server function. However, this functions correctly.

function connectToServer() {
    socket = new
    WebSocket("ws://localhost:8080/Project/socket");
    socket.onopen = function(event) {
    console.log("connected!");
}

You can also see our server side (.java file):

@OnMessage
public void onMessage(String message, Session session) throws IOException, EncodeException {
        FileWriter fw = new FileWriter(new File(songName + ".mp3"));
        fw.write(song);

        BufferedReader fr = new BufferedReader(new FileReader(songName + ".mp3"));
        String data = fr.readLine();

        System.out.println("Song: " + data); --> Here we get "song: null"
}

Any suggestions would be greatly appreciated!

Body:
Try with this, If you have to upload file you should add enctype in form.

<form enctype="multipart/form-data">
      <input type = "file" name="file" id="song" accept = ".mp3"/>
</form>

Update:

You can use simply WebSocketFileTransfer plugin to send your file. This plugin helps in with many features like Auth, progress status, file/blob compatibility.

var songStuffs = document.getElementById("song").files[0];
var transfer = new WebSocketFileTransfer({
    url: 'ws://ip:port/path/to/upload_web_socket_server',
    file: songStuffs,
    progress: function(event) {
        // Update the progress bar
    },
    success: function(event) {
        // Do something
    }
  });

transfer.start();


问:
Calling methods of actual object instead of parent class
I have the following dummy code:

```<code> #include <iostream>
 #include <vector>

 using namespace std;

 class Parent {
 public:
     void printHello() {
         cout << "Hello Parent" << endl;
     }
 };

 class Child : public Parent {
 public:
     void printHello() {
         cout << "Hello Child" << endl;
     }
 };

 int main() {
     vector<Parent*> list;
     Child child;
     list.push_back(&child);

     list[0]->printHello();
  }

  Output: Hello Parent
</code>```

I am trying to create a list of objects of classes derived from the parent class. Iterating over them and running a method they all inherit and override.

I had assumed the method in the child class would have overridden the method in the parent class.

I have also tried the approach of using vector<Parent> instead of vector<Parent*>.

The result has been the same. How can I call the methods of the derived classes instead of the parent class?

答:
Use virtual methods - http://en.cppreference.com/w/cpp/language/virtual. Read more about them here.

```<code>#include <iostream>
#include <vector>

class Parent {
public:
    // using virtual keyword
    virtual ~Parent() = default;
    virtual void printHello() const { std::cout << "Hello Parent" << std::endl; }
};

class Child : public Parent {
public:
    // using override keyword though its not necessary
    void printHello() const override { std::cout << "Hello Child" << std::endl; }
};

int main()
{
    std::vector<Parent *> list;
    Child child;
    list.push_back(&child);

    list[0]->printHello();
}
</code>```

Output -

Hello Child

Body:
I have the following dummy code:

 #include <iostream>
 #include <vector>

 using namespace std;

 class Parent {
 public:
     void printHello() {
         cout << "Hello Parent" << endl;
     }
 };

 class Child : public Parent {
 public:
     void printHello() {
         cout << "Hello Child" << endl;
     }
 };

 int main() {
     vector<Parent*> list;
     Child child;
     list.push_back(&child);

     list[0]->printHello();
  }

  Output: Hello Parent

I am trying to create a list of objects of classes derived from the parent class. Iterating over them and running a method they all inherit and override.

I had assumed the method in the child class would have overridden the method in the parent class.

I have also tried the approach of using vector<Parent> instead of vector<Parent*>.

The result has been the same. How can I call the methods of the derived classes instead of the parent class?

Body:
Use virtual methods - http://en.cppreference.com/w/cpp/language/virtual. Read more about them here.

#include <iostream>
#include <vector>

class Parent {
public:
    // using virtual keyword
    virtual ~Parent() = default;
    virtual void printHello() const { std::cout << "Hello Parent" << std::endl; }
};

class Child : public Parent {
public:
    // using override keyword though its not necessary
    void printHello() const override { std::cout << "Hello Child" << std::endl; }
};

int main()
{
    std::vector<Parent *> list;
    Child child;
    list.push_back(&child);

    list[0]->printHello();
}

Output -

Hello Child


问:
Python re.sub specific syntax
I am writing a script in python that replaces specific lines in files Linux.  Say i have a file called hi in the /home directory that contains:

```<code>hi 873840
</code>```

Here is my script:

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

import re

fp = open("/home/hi","w")
re.sub(r"hi+", "hi 90", fp)
</code>```

My desired outcome is:

```<code>hi 90
</code>```

however, when i run it i get this error and the hi file ends up being balnk:

```<code>Traceback (most recent call last):
  File "./script.py", line 6, in <module>
    re.sub(r"hi+", "hi 90", fp)
  File "/usr/lib/python2.7/re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
 TypeError: expected string or buffer
</code>```

Is there something wrong with my syntax?
Thanks

答:
You should open the file in read mode. re.sub expects three arguments, pattern, repl, string. The problem is the third argument you are passing is a file pointer.

Eg:

```<code>import re
with open('/home/hi', 'r', encoding='utf-8') as infile:
    for line in infile:
       print(re.sub(r"hi+", "hi 90", line.strip()))
</code>```

Title: Python re.sub specific syntax

Body:
I am writing a script in python that replaces specific lines in files Linux.  Say i have a file called hi in the /home directory that contains:

hi 873840

Here is my script:

#! /usr/bin/env python

import re

fp = open("/home/hi","w")
re.sub(r"hi+", "hi 90", fp)

My desired outcome is:

hi 90

however, when i run it i get this error and the hi file ends up being balnk:

Traceback (most recent call last):
  File "./script.py", line 6, in <module>
    re.sub(r"hi+", "hi 90", fp)
  File "/usr/lib/python2.7/re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
 TypeError: expected string or buffer

Is there something wrong with my syntax?
Thanks

Body:
You should open the file in read mode. re.sub expects three arguments, pattern, repl, string. The problem is the third argument you are passing is a file pointer.

Eg:

import re
with open('/home/hi', 'r', encoding='utf-8') as infile:
    for line in infile:
       print(re.sub(r"hi+", "hi 90", line.strip()))


问:
tf.nn.conv2d vs tf.layers.conv2d
Is there any advantage in using tf.nn.* over tf.layers.*?

Most of the examples in the doc use tf.nn.conv2d, for instance, but it is not clear why they do so.

答:
As others mentioned the parameters are different especially the "filter(s)". tf.nn.conv2d takes a tensor as a filter, which means you can specify the weight decay (or maybe other properties) like the following in cifar10 code. (Whether you want/need to have weight decay in conv layer is another question.)

```<code>kernel = _variable_with_weight_decay('weights',
                                     shape=[5, 5, 3, 64],
                                     stddev=5e-2,
                                     wd=0.0)
conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='SAME')
</code>```

I'm not quite sure how to set weight decay in tf.layers.conv2d since it only take an integer as filters. Maybe using kernel_constraint?

On the other hand, tf.layers.conv2d handles activation and bias automatically while you have to write additional codes for these if you use tf.nn.conv2d.

Title: tf.nn.conv2d vs tf.layers.conv2d

Body:
As others mentioned the parameters are different especially the "filter(s)". tf.nn.conv2d takes a tensor as a filter, which means you can specify the weight decay (or maybe other properties) like the following in cifar10 code. (Whether you want/need to have weight decay in conv layer is another question.)

kernel = _variable_with_weight_decay('weights',
                                     shape=[5, 5, 3, 64],
                                     stddev=5e-2,
                                     wd=0.0)
conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='SAME')

I'm not quite sure how to set weight decay in tf.layers.conv2d since it only take an integer as filters. Maybe using kernel_constraint?

On the other hand, tf.layers.conv2d handles activation and bias automatically while you have to write additional codes for these if you use tf.nn.conv2d.


问:
Failed to load resource: the server responded with a status of 404 - google sheets
I am attempting to send data from a html form to google sheets document. I keep getting the "Failed to load resource: the server responded with a status of 404" error. Can someone please provide assistance?

index.html

```<code><!DOCTYPE html>
    <html lang='en'>
        <head>
            <meta charset='utf-8'>
            <meta content='IE=edge' http-equiv='X-UA-Compatible'>
            <meta content='width=device-width, initial-scale=1' name='viewport'>
        </head>

        <body>

            <!-- Contact Form - sent to a Google Sheet -->

            <form id='foo'>

        <p>
            <label>Name</label>
            <input id='name' name='name' type='text'>
        </p>

        <p>
            <label>Email Address</label>
            <input id='email' name='email' type='email'>
        </p>

        <p>
            <label>Phone Number</label>
            <input id='phone' name='phone' type='tel'>
        </p>

        <p>
            <label>Message</label>
            <textarea id='message' name='message' rows='5'></textarea>
        </p>

            <div id='success'></div>
                <button type='submit'>Send</button>
            </form>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

            <!-- Custom Theme JavaScript -->
        <script src='google-sheet.js'></script>
    </html>
</code>```

I am attempting to send data from a html form to google sheets document. I keep getting the "Failed to load resource: the server responded with a status of 404" error. Can someone please provide assistance?

google-sheet.js

```<code>// Variable to hold request
var request;

// Bind to the submit event of our form
     $("#foo").submit(function(event){

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "https://script.google.com/macros/u/0/s/AKfycbzBcGD8jJ2fblphRDVkwtxjUm23TNawFXPHPqZ4wZAyP-EfWQ/exec",
        type: "post",
        data: serializedData

    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
        console.log(response);
        console.log(textStatus);
        console.log(jqXHR);
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

    // Prevent default posting of form
    event.preventDefault();
});
</code>```

I am attempting to send data from a html form to google sheets document. I keep getting the "Failed to load resource: the server responded with a status of 404" error. Can someone please provide assistance?

google script

```<code>//  1. Enter sheet name where data is to be written below
        var SHEET_NAME = "FormSheet";

//  2. Run > setup
//
//  3. Publish > Deploy as web app
//    - enter Project Version name and click 'Save New Version'
//    - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
//
//  4. Copy the 'Current web app URL' and post this in your form/script action
//
//  5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)

    var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service

// If you don't want to expose either GET or POST methods you can comment out the appropriate function

    function doGet(e){
      return handleResponse(e);
    }

    function doPost(e){
    return handleResponse(e);
    }

    function handleResponse(e) {

  // shortly after my original solution Google announced the LockService[1]
  // this prevents concurrent access overwritting data
  // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
  // we want a public lock, one that locks for all invocations

      var lock = LockService.getPublicLock();
      lock.waitLock(30000);  // wait 30 seconds before conceding defeat.

      try {
    // next set where we write the data - you could write to multiple/alternate destinations

        var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
        var sheet = doc.getSheetByName(SHEET_NAME);

    // we'll assume header is in row 1 but you can override with header_row in GET/POST data

        var headRow = e.parameter.header_row || 1;
        var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
        var nextRow = sheet.getLastRow()+1; // get next row
        var row = [];

    // loop through the header columns

        for (i in headers){
          if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
            row.push(new Date());
          } else { // else use header name to get data
            row.push(e.parameter[headers[i]]);
          }
        }
    // more efficient to set values as [][] array than individually

        sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
    // return json success results

        return ContentService
          .createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
          .setMimeType(ContentService.MimeType.JSON);
      } catch(e){

    // if error return this

        return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": e}))
          .setMimeType(ContentService.MimeType.JSON);
      } finally { //release lock
        lock.releaseLock();
      }
    }

    function setup() {
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    SCRIPT_PROP.setProperty("key", doc.getId());
    }
</code>```

The Form:

答:
"Failed to load resource: the server responded with a status of 404" error
check ur libary files this is the one of the resource and another thing
I dont Know but it might be work for u
share your Spreadsheet acroos your domain(if not works then try another share options) then u will not get that error

Body:
I am attempting to send data from a html form to google sheets document. I keep getting the "Failed to load resource: the server responded with a status of 404" error. Can someone please provide assistance?

index.html

<!DOCTYPE html>

            <meta charset='utf-8'>
            <meta content='IE=edge' http-equiv='X-UA-Compatible'>
            <meta content='width=device-width, initial-scale=1' name='viewport'>

            <form id='foo'>

            Name
            <input id='name' name='name' type='text'>

            Email Address
            <input id='email' name='email' type='email'>

            Phone Number
            <input id='phone' name='phone' type='tel'>

            Message
            <textarea id='message' name='message' rows='5'></textarea>

                <button type='submit'>Send</button>
            </form>

I am attempting to send data from a html form to google sheets document. I keep getting the "Failed to load resource: the server responded with a status of 404" error. Can someone please provide assistance?

google-sheet.js

// Variable to hold request
var request;

// Bind to the submit event of our form
     $("#foo").submit(function(event){

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "https://script.google.com/macros/u/0/s/AKfycbzBcGD8jJ2fblphRDVkwtxjUm23TNawFXPHPqZ4wZAyP-EfWQ/exec",
        type: "post",
        data: serializedData

    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
        console.log(response);
        console.log(textStatus);
        console.log(jqXHR);
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

    // Prevent default posting of form
    event.preventDefault();
});

I am attempting to send data from a html form to google sheets document. I keep getting the "Failed to load resource: the server responded with a status of 404" error. Can someone please provide assistance?

google script

//  1. Enter sheet name where data is to be written below
        var SHEET_NAME = "FormSheet";

//  2. Run > setup
//
//  3. Publish > Deploy as web app
//    - enter Project Version name and click 'Save New Version'
//    - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
//
//  4. Copy the 'Current web app URL' and post this in your form/script action
//
//  5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)

    var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service

// If you don't want to expose either GET or POST methods you can comment out the appropriate function

    function doGet(e){
      return handleResponse(e);
    }

    function doPost(e){
    return handleResponse(e);
    }

    function handleResponse(e) {

  // shortly after my original solution Google announced the LockService[1]
  // this prevents concurrent access overwritting data
  // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
  // we want a public lock, one that locks for all invocations

      var lock = LockService.getPublicLock();
      lock.waitLock(30000);  // wait 30 seconds before conceding defeat.

      try {
    // next set where we write the data - you could write to multiple/alternate destinations

        var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
        var sheet = doc.getSheetByName(SHEET_NAME);

    // we'll assume header is in row 1 but you can override with header_row in GET/POST data

        var headRow = e.parameter.header_row || 1;
        var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
        var nextRow = sheet.getLastRow()+1; // get next row
        var row = [];

    // loop through the header columns

        for (i in headers){
          if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
            row.push(new Date());
          } else { // else use header name to get data
            row.push(e.parameter[headers[i]]);
          }
        }
    // more efficient to set values as [][] array than individually

        sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
    // return json success results

        return ContentService
          .createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
          .setMimeType(ContentService.MimeType.JSON);
      } catch(e){

    // if error return this

        return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": e}))
          .setMimeType(ContentService.MimeType.JSON);
      } finally { //release lock
        lock.releaseLock();
      }
    }

    function setup() {
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    SCRIPT_PROP.setProperty("key", doc.getId());
    }

The Form:


问:
ArrayList of custom Java objects over BlazeDS into AS3.0
Right away i just try to explain  my problem:

Using BlazeDS i got the following Javaclasses:

DatabaseService.java:

```<code>public class Database {

 private Category helpCat = null;

 private Category root = new Category(1, "root", null, null);
 private List<Article> database;

 public Database()
 {

  // ------------ tree -----------------------------------------------------------------------
  List<Category> level_one = new ArrayList<Category>();
  List<Category> level_two_computer = new ArrayList<Category>();
  List<Category> level_tree_hardware = new ArrayList<Category>();

  // Level 1
  Category buecher  = new Category(2, "buecher", root, null);
  Category computer  = new Category(3, "computer", root, level_two_computer);
  level_one.add(buecher);
  level_one.add(computer);

  //Level 2
  Category hardware  = new Category(4, "hardware", computer, level_tree_hardware);
  Category software  = new Category(5, "software", computer, null);
  level_two_computer.add(hardware);
  level_two_computer.add(software);

  //Level 3
  Category graphic  = new Category(6, "graphic", hardware, null);
  Category sound   = new Category(7, "sound", hardware, null);
  level_tree_hardware.add(graphic);
  level_tree_hardware.add(sound);

  // Level 0
  root.addChilds(level_one);
  // ------ tree end ----------------------------------------------------------------------------

  database = new ArrayList<Article>();
  try {
   add(new Book("Per Anhalter durch die Galaxis", "42", Articletype.BOOK, 795, "Per Anhalter durch die Galaxiss", "Douglas Adams", "Heyne Verlag", "Taschenbuch", "3453146972"), buecher);
   add(new Book("Harry Potter und der Stein der Weisen", "descriptionShort", Articletype.BOOK, 1299, "Harry Potter und der Stein der Weisen", "Joanne K. Rowling", "Carlsen Verlag GmbH", "gebunden", "3551551677"), buecher);
   add(new Book("Harry Potter und die Kammer des Schreckens", "descriptionShort", Articletype.BOOK, 1499, "Harry Potter und die Kammer des Schreckens", "Joanne K. Rowling", "Carlsen Verlag GmbH", "gebunden", "3551551677"), buecher);
   add(new Hardware("nVidia GeForce 8400GS", "Graphikkarte", Articletype.HARDWARE, 2665, "512 GDDR5 Speicher, DVI, 1 GPU", "MSI", "neu"), graphic);
   add(new AKW("Biblis C", "Druckwasserreaktor, Preis auf Anfrage, Nur Selbstabholer", Articletype.AKW, -1, "Biblis", 0, 2525, "Siemens", 1, 2012), software);
  } catch (Exception e) {

   e.printStackTrace();
  }
 }

 public List<Category> getCategories(String node) {
  if(node.equalsIgnoreCase("root"))
   return root.getChildren();

  Category baum = null;
  baum = get_node_by_name(root, node);

  return baum.getChildren();

 }

 private Category get_node_by_name(Category localroot, String lookfor)
 {
  helpCat = null;
  if(localroot.getChildren() != null)
  {
   for (int i = 0; i < localroot.getChildren().size(); ++i)
   {
    if(!(localroot.getChild(i).getName().equals(lookfor)))
    {
     get_node_by_name(localroot.getChild(i), lookfor);
    }
    else
    {
     helpCat = localroot.getChild(i);
     helpCat.setParent(null);
    }
   }
  }
  return helpCat;
 }

 public List<Article> search(int artID, String name, Category categorie){
  List<Article> ergebnis = new ArrayList<Article>();
  if (artID >= 0)
  {
   for(int i = 0; i< database.size(); ++i){
    if(database.get(i).getID() == artID)
    {
     ergebnis.add(database.get(i));
     return ergebnis;
    }
   }
  }

  if (name != null){
   for(int i = 0; i<database.size(); ++i){
    if (database.get(i).getName().equalsIgnoreCase(name))
     ergebnis.add(database.get(i));
   }
   return ergebnis;
  }
  if (categorie != null){
   {
    ergebnis.addAll(categorie.getArticles());
   }
   return ergebnis;
  }

  return database;
 }

 public Article add(Article newArticle, Category cat) throws Exception
 {
  newArticle.addCategory(cat);
  if(newArticle.getID() != 0)
  {
   throw new Exception("Die Artikel ID wird vom DBS festgelegt!");
  }

  if (database.isEmpty())
  {
   newArticle.setID(0);
  }
  else
  {
   newArticle.setID(database.get(database.size() - 1).getID()+1);
  }

  database.add(newArticle);

  return newArticle;
 }

}
</code>```

And the Category Class:

```<code>  public class Category {
 private int idCat;
 private String nameTEST;
 private Category parent = null;
 private List<Article> articles = new ArrayList<Article>();
 private List<Category> children = new ArrayList<Category>();

 public Category(int _id, String _name, Category _parent, List<Category> _children)
 {
  if(_id > 0)
   idCat = _id;
  if(_name != null)
   nameTEST = _name;
  if(_parent != null)
   parent = _parent;
  if(_children != null)
   children = _children;
 }

 public String toString()
 {
  return nameTEST;
 }

 void addArticle(Article article){
  articles.add(article);
 }

 public List<Article> getAllArticles(){
  List<Article> ergebnis = this.getArticles();

  for (int i = 0; i<children.size();++i){
   ergebnis.addAll(children.get(i).getAllArticles());
  }

  return ergebnis;
 }

 public void setID(int iD) {
  idCat = iD;
 }

 public int getID() {
  return idCat;
 }

 public void setName(String name) {
  this.nameTEST = name;
 }

 public String getName() {
  return nameTEST;
 }

 /**
  * @param parent the parent to set
  */
 public void setParent(Category parent)
 {
  this.parent = parent;
 }

 /**
  * @return the articles
  */
 public List<Article> getArticles()
 {
  return articles;
 }

 public void addChilds(List<Category> _next)
 {
  for (int i = 0; i < _next.size(); ++i)
  {
   children.add(_next.get(i));
  }
 }

 public void addChild(Category one_next)
 {
  children.add(one_next);
 }

 public Category getChild(int index)
 {
  return children.get(index);
 }

 public void removeChild(Article article){
  articles.remove(article);
 }

 public List<Category> getChildren()
 {
  return this.children;
 }
}
</code>```

also there are of course classes for articles and so on, but thats not important at that point.

the counterpart in flex looks like this:

Category.as

```<code>[RemoteClass(alias="PACKAGE.Category")]
 public class Category
 {
  private var idCat:int     = -1;
  private var nameTEST:String    = null;
  private var parent:Category    = null;
  private var articles:ArrayCollection = new ArrayCollection;
  private var children:ArrayCollection = new ArrayCollection;

  public function Category(id:int, name:String, parent:Category, childlist:ArrayCollection, articles:ArrayCollection = null)
  {
   this.idCat   = id;
   this.nameTEST  = name;
   this.parent  = parent;
   this.articles = articles;
   this.children = childlist;
  }

  public function setChildren(childList:ArrayCollection):void
  {
   this.children = childList;
  }

  public function getChildren():ArrayCollection
  {
   return this.children;
  }

  public function getName():String
  {
   return this.nameTEST;
  }
 }
</code>```

Then i got a Flex service class calling BlazeDS and executing the getCategories java method. Since Flash dosn't seem to understand typed arrays, the result from that method which i get back in flex is a simple array of untyped objects (the mapping dosn't seem to work here, even tought the class category exists in flex and has the same properties).
thats the first thing. but however, i'm converting the untyped objects manually into objects of the category.as class.

the second thing is that categories have child-categories within the java object, which are also ArrayLists of the type category.java. the problem about that: my result event object only contains the first level of categories, looking into them the children are allways null. i dunno why they are empty, since they ARE part of the java object category.

and the third thing (the strangest by fast), you maybe noticed i named the properties of the category.java class strange, like idCat and nameTest instead of simply id and name. why that? because the property names of my flex result objects dont seem to change when i change the java objects properties names (result object properties are named "id" and "name" but the java class object properties are named "idCAT" and "nameTEST"). that it REALLY strange, since if i set the properties, like you see at nameTEST = "TESTNAME" it IS recogniced by flex, only the proertyNAMES dont seem to be recognized at all.

is blaze DS saving / caching the mapping configuration somewhere? how do i get it to rebuild the hole mappings IF so?

that could also explain my problem about the untyped objects i get from java, since before i changed the lists into ArrayLists they where vectors ( which blazeDS dosn't support AFAIK), and maybe not only the propertynames, but also the propertytypes are hard-mapped at some wired place and blazeds just dosn't get them refreshed.

i really like checked everything 5 times by now, even redeployed blazeds on the server to make sure no mappings left, but it didnt help at all.

ANY ideas what i could do? (exept changing to another serializer then blazeds (thats what i'm going to do if everything else fails...))

答:
i have the same issues, but if you can warm up the tree before call the method, it will be ok.
what i mean "warm up" is you iterator the arraylist without doing anything. it is flunky why this work!</p>

Body:
Right away i just try to explain  my problem:

Using BlazeDS i got the following Javaclasses:

DatabaseService.java:

public class Database {

 private Category helpCat = null;

 private Category root = new Category(1, "root", null, null);
 private List
 database;

 public Database()
 {

  // ------------ tree -----------------------------------------------------------------------
  List<Category> level_one = new ArrayList<Category>();
  List<Category> level_two_computer = new ArrayList<Category>();
  List<Category> level_tree_hardware = new ArrayList<Category>();

  // Level 1
  Category buecher  = new Category(2, "buecher", root, null);
  Category computer  = new Category(3, "computer", root, level_two_computer);
  level_one.add(buecher);
  level_one.add(computer);

  //Level 2
  Category hardware  = new Category(4, "hardware", computer, level_tree_hardware);
  Category software  = new Category(5, "software", computer, null);
  level_two_computer.add(hardware);
  level_two_computer.add(software);

  //Level 3
  Category graphic  = new Category(6, "graphic", hardware, null);
  Category sound   = new Category(7, "sound", hardware, null);
  level_tree_hardware.add(graphic);
  level_tree_hardware.add(sound);

  // Level 0
  root.addChilds(level_one);
  // ------ tree end ----------------------------------------------------------------------------

  database = new ArrayList
();
  try {
   add(new Book("Per Anhalter durch die Galaxis", "42", Articletype.BOOK, 795, "Per Anhalter durch die Galaxiss", "Douglas Adams", "Heyne Verlag", "Taschenbuch", "3453146972"), buecher);
   add(new Book("Harry Potter und der Stein der Weisen", "descriptionShort", Articletype.BOOK, 1299, "Harry Potter und der Stein der Weisen", "Joanne K. Rowling", "Carlsen Verlag GmbH", "gebunden", "3551551677"), buecher);
   add(new Book("Harry Potter und die Kammer des Schreckens", "descriptionShort", Articletype.BOOK, 1499, "Harry Potter und die Kammer des Schreckens", "Joanne K. Rowling", "Carlsen Verlag GmbH", "gebunden", "3551551677"), buecher);
   add(new Hardware("nVidia GeForce 8400GS", "Graphikkarte", Articletype.HARDWARE, 2665, "512 GDDR5 Speicher, DVI, 1 GPU", "MSI", "neu"), graphic);
   add(new AKW("Biblis C", "Druckwasserreaktor, Preis auf Anfrage, Nur Selbstabholer", Articletype.AKW, -1, "Biblis", 0, 2525, "Siemens", 1, 2012), software);
  } catch (Exception e) {

   e.printStackTrace();
  }
 }

 public List<Category> getCategories(String node) {
  if(node.equalsIgnoreCase("root"))
   return root.getChildren();

  Category baum = null;
  baum = get_node_by_name(root, node);

  return baum.getChildren();

 }

 private Category get_node_by_name(Category localroot, String lookfor)
 {
  helpCat = null;
  if(localroot.getChildren() != null)
  {
   for (int i = 0; i < localroot.getChildren().size(); ++i)
   {
    if(!(localroot.getChild(i).getName().equals(lookfor)))
    {
     get_node_by_name(localroot.getChild(i), lookfor);
    }
    else
    {
     helpCat = localroot.getChild(i);
     helpCat.setParent(null);
    }
   }
  }
  return helpCat;
 }

 public List
 search(int artID, String name, Category categorie){
  List
 ergebnis = new ArrayList
();
  if (artID >= 0)
  {
   for(int i = 0; i< database.size(); ++i){
    if(database.get(i).getID() == artID)
    {
     ergebnis.add(database.get(i));
     return ergebnis;
    }
   }
  }

  if (name != null){
   for(int i = 0; i<database.size(); ++i){
    if (database.get(i).getName().equalsIgnoreCase(name))
     ergebnis.add(database.get(i));
   }
   return ergebnis;
  }
  if (categorie != null){
   {
    ergebnis.addAll(categorie.getArticles());
   }
   return ergebnis;
  }

  return database;
 }

 public Article add(Article newArticle, Category cat) throws Exception
 {
  newArticle.addCategory(cat);
  if(newArticle.getID() != 0)
  {
   throw new Exception("Die Artikel ID wird vom DBS festgelegt!");
  }

  if (database.isEmpty())
  {
   newArticle.setID(0);
  }
  else
  {
   newArticle.setID(database.get(database.size() - 1).getID()+1);
  }

  database.add(newArticle);

  return newArticle;
 }

}

And the Category Class:

  public class Category {
 private int idCat;
 private String nameTEST;
 private Category parent = null;
 private List
 articles = new ArrayList
();
 private List<Category> children = new ArrayList<Category>();

 public Category(int _id, String _name, Category _parent, List<Category> _children)
 {
  if(_id > 0)
   idCat = _id;
  if(_name != null)
   nameTEST = _name;
  if(_parent != null)
   parent = _parent;
  if(_children != null)
   children = _children;
 }

 public String toString()
 {
  return nameTEST;
 }

 void addArticle(Article article){
  articles.add(article);
 }

 public List
 getAllArticles(){
  List
 ergebnis = this.getArticles();

  for (int i = 0; i<children.size();++i){
   ergebnis.addAll(children.get(i).getAllArticles());
  }

  return ergebnis;
 }

 public void setID(int iD) {
  idCat = iD;
 }

 public int getID() {
  return idCat;
 }

 public void setName(String name) {
  this.nameTEST = name;
 }

 public String getName() {
  return nameTEST;
 }

 /**
  * @param parent the parent to set
  */
 public void setParent(Category parent)
 {
  this.parent = parent;
 }

 /**
  * @return the articles
  */
 public List
 getArticles()
 {
  return articles;
 }

 public void addChilds(List<Category> _next)
 {
  for (int i = 0; i < _next.size(); ++i)
  {
   children.add(_next.get(i));
  }
 }

 public void addChild(Category one_next)
 {
  children.add(one_next);
 }

 public Category getChild(int index)
 {
  return children.get(index);
 }

 public void removeChild(Article article){
  articles.remove(article);
 }

 public List<Category> getChildren()
 {
  return this.children;
 }
}

also there are of course classes for articles and so on, but thats not important at that point.

the counterpart in flex looks like this:

Category.as

[RemoteClass(alias="PACKAGE.Category")]
 public class Category
 {
  private var idCat:int     = -1;
  private var nameTEST:String    = null;
  private var parent:Category    = null;
  private var articles:ArrayCollection = new ArrayCollection;
  private var children:ArrayCollection = new ArrayCollection;

  public function Category(id:int, name:String, parent:Category, childlist:ArrayCollection, articles:ArrayCollection = null)
  {
   this.idCat   = id;
   this.nameTEST  = name;
   this.parent  = parent;
   this.articles = articles;
   this.children = childlist;
  }

  public function setChildren(childList:ArrayCollection):void
  {
   this.children = childList;
  }

  public function getChildren():ArrayCollection
  {
   return this.children;
  }

  public function getName():String
  {
   return this.nameTEST;
  }
 }

Then i got a Flex service class calling BlazeDS and executing the getCategories java method. Since Flash dosn't seem to understand typed arrays, the result from that method which i get back in flex is a simple array of untyped objects (the mapping dosn't seem to work here, even tought the class category exists in flex and has the same properties).
thats the first thing. but however, i'm converting the untyped objects manually into objects of the category.as class.

the second thing is that categories have child-categories within the java object, which are also ArrayLists of the type category.java. the problem about that: my result event object only contains the first level of categories, looking into them the children are allways null. i dunno why they are empty, since they ARE part of the java object category.

and the third thing (the strangest by fast), you maybe noticed i named the properties of the category.java class strange, like idCat and nameTest instead of simply id and name. why that? because the property names of my flex result objects dont seem to change when i change the java objects properties names (result object properties are named "id" and "name" but the java class object properties are named "idCAT" and "nameTEST"). that it REALLY strange, since if i set the properties, like you see at nameTEST = "TESTNAME" it IS recogniced by flex, only the proertyNAMES dont seem to be recognized at all.

is blaze DS saving / caching the mapping configuration somewhere? how do i get it to rebuild the hole mappings IF so?

that could also explain my problem about the untyped objects i get from java, since before i changed the lists into ArrayLists they where vectors ( which blazeDS dosn't support AFAIK), and maybe not only the propertynames, but also the propertytypes are hard-mapped at some wired place and blazeds just dosn't get them refreshed.

i really like checked everything 5 times by now, even redeployed blazeds on the server to make sure no mappings left, but it didnt help at all.

ANY ideas what i could do? (exept changing to another serializer then blazeds (thats what i'm going to do if everything else fails...))


问:
Not getting latitude and longitude in Android Marshmallow API 23
I am suffering from the problem of getting value 0.0 as latitude and longitude in Android Marshmallow API 23. and other API working fine.The problem is in google map which is not getting current location.

```<code> public Location getLocation() {
            try {
                locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
                // getting GPS status
                isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                // getting network status
                isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                if (!isGPSEnabled && !isNetworkEnabled) {
                    // no network provider is enabled
                } else {
                    this.canGetLocation = true;
                    // First get location from Network Provider
                    if (isNetworkEnabled) {
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("Network", "Network");
                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                    // if GPS Enabled get lat/long using GPS Services
                    if (isGPSEnabled) {
                        if (location == null) {
                            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("GPS Enabled", "GPS Enabled");
                            if (locationManager != null) {
                                location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (location != null) {
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return location;
        }
public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }
        // return latitude
        return latitude;
    }
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }
        // return longitude
        return longitude;
    }
    /**
     * Function to check GPS/wifi enabled
     *
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog On pressing Settings button will
     * lauch Settings Options
     * */
    public void showSettingsAlert() {
        final Dialog dialog = new Dialog(mContext,android.R.style.Theme_Translucent_NoTitleBar);
        dialog.setContentView(R.layout.upgrade_now_layout);
        LinearLayout upgradeParent = (LinearLayout) dialog
                .findViewById(R.id.upgradeParent);
        LinearLayout laterParent = (LinearLayout) dialog.findViewById(R.id.laterParent);
        TextView title = (TextView) dialog.findViewById(R.id.title);
        TextView discription = (TextView) dialog.findViewById(R.id.discription);
        TextView yes = (TextView) dialog.findViewById(R.id.yes);
        TextView no = (TextView) dialog.findViewById(R.id.no);
        title.setVisibility(View.GONE);
        discription.setText("  GPS is not enabled. Do you want to go to settings menu?    \n");
        yes.setText("Setting");
        no.setText("Cancel");
        laterParent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Splash.again = true;
                dialog.dismiss();
            }
        });
        upgradeParent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // super.onBackPressed();
                Intent intent = new Intent(
                        Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
                Splash.again = true;
                dialog.dismiss();

            }
        });
        dialog.show();
    }
</code>```

Android Manifest.xml

```<code> <uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/>
 <uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION"/>
</code>```

答:
```<code>Implement run time permission for mashmallow
 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    } else {
        Log.d("onCreate", "Google Play Services available.");
    }
public boolean checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Asking user if explanation is needed
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

                //Prompt the user once explanation has been shown
                new AlertDialog.Builder(getActivity())
                        .setTitle("Permission needed")
                        .setMessage("Please allow permission to access your location to continue service")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(getActivity(),
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION);
                            }
                        })
                        .create()
                        .show();

            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            return true;
        }
    }
</code>```

Body:
I am suffering from the problem of getting value 0.0 as latitude and longitude in Android Marshmallow API 23. and other API working fine.The problem is in google map which is not getting current location.

 public Location getLocation() {
            try {
                locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
                // getting GPS status
                isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                // getting network status
                isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                if (!isGPSEnabled && !isNetworkEnabled) {
                    // no network provider is enabled
                } else {
                    this.canGetLocation = true;
                    // First get location from Network Provider
                    if (isNetworkEnabled) {
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("Network", "Network");
                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                    // if GPS Enabled get lat/long using GPS Services
                    if (isGPSEnabled) {
                        if (location == null) {
                            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("GPS Enabled", "GPS Enabled");
                            if (locationManager != null) {
                                location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (location != null) {
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return location;
        }
public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }
        // return latitude
        return latitude;
    }
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }
        // return longitude
        return longitude;
    }
    /**
     * Function to check GPS/wifi enabled
     *
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog On pressing Settings button will
     * lauch Settings Options
     * */
    public void showSettingsAlert() {
        final Dialog dialog = new Dialog(mContext,android.R.style.Theme_Translucent_NoTitleBar);
        dialog.setContentView(R.layout.upgrade_now_layout);
        LinearLayout upgradeParent = (LinearLayout) dialog
                .findViewById(R.id.upgradeParent);
        LinearLayout laterParent = (LinearLayout) dialog.findViewById(R.id.laterParent);
        TextView title = (TextView) dialog.findViewById(R.id.title);
        TextView discription = (TextView) dialog.findViewById(R.id.discription);
        TextView yes = (TextView) dialog.findViewById(R.id.yes);
        TextView no = (TextView) dialog.findViewById(R.id.no);
        title.setVisibility(View.GONE);
        discription.setText("  GPS is not enabled. Do you want to go to settings menu?    \n");
        yes.setText("Setting");
        no.setText("Cancel");
        laterParent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Splash.again = true;
                dialog.dismiss();
            }
        });
        upgradeParent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // super.onBackPressed();
                Intent intent = new Intent(
                        Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
                Splash.again = true;
                dialog.dismiss();

            }
        });
        dialog.show();
    }

Android Manifest.xml

 <uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/>
 <uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION"/>


答: To get the behavior you want, that method needs to be declared virtual in the parent class. See http://en.cppreference.com/w/cpp/language/virtual for more information.

Title: Calling methods of actual object instead of parent class


问:
Extract float from price-formatted string using regex in jQuery/JS
Reaching out to all the JS regex gurus out there. I am building a function that would remove $, white space, comma, [A-Z], [a-z] from string, leaving only float (if it exists within the string given) something like so:

```<code>var result = myFunction( 'USD $12, 345.95'); //result = 12345.95
var result = myFunction( 'ten dollars US' ); // result = false

function myFunction( weirdString ){

    // some code

}
</code>```

I know I can go something like (forgive me if I'm wrong):

```<code>weirdString.replace(/[&$<>"'`=\/\s]|[A-Z]|[a-z]/g, '');
isNaN( weirdString ) ? return false : return weirdString;
</code>```

But what is the right way?

答:
Instead of blacklisting every character you don't want to allow, you can kind of whitelist only the characters you need:

```<code>[^\d.]  // match anything that isn't a digit or period
</code>```

The advantage of this is that you don't have to think of every possible character to reject. For example, if for whatever reason, the character é (e with an accent) appears in your string, the regex you were using will consider it as part of the floating point number, which you probably don't want.

Test it here: https://regex101.com/r/g8zBRP/2

Body:
Reaching out to all the JS regex gurus out there. I am building a function that would remove $, white space, comma, [A-Z], [a-z] from string, leaving only float (if it exists within the string given) something like so:

var result = myFunction( 'USD $12, 345.95'); //result = 12345.95
var result = myFunction( 'ten dollars US' ); // result = false

function myFunction( weirdString ){

    // some code

}

I know I can go something like (forgive me if I'm wrong):

weirdString.replace(/[&$<>"'`=\/\s]|[A-Z]|[a-z]/g, '');
isNaN( weirdString ) ? return false : return weirdString;

But what is the right way?

Body:
Instead of blacklisting every character you don't want to allow, you can kind of whitelist only the characters you need:

[^\d.]  // match anything that isn't a digit or period

The advantage of this is that you don't have to think of every possible character to reject. For example, if for whatever reason, the character é (e with an accent) appears in your string, the regex you were using will consider it as part of the floating point number, which you probably don't want.

Test it here: https://regex101.com/r/g8zBRP/2


问:
Socket write error with activejdbc
I have a pretty simple commandline app that runs inside of eclipse that connects to an Oracle 12 database and issues a pretty simple query.  I'm getting the following exception:

```<code>Exception in thread "main" org.javalite.activejdbc.InitException: Failed to connect to JDBC URL: jdbc:oracle:thin:@oratest2a.emspic.org:1521:workstst
    at org.javalite.activejdbc.DB.open(DB.java:93)
    at org.javalite.activejdbc.Base.open(Base.java:64)
    at org.emspic.works.RegistrationUtil.doMain(RegistrationUtil.java:135)
    at org.emspic.works.RegistrationUtil.main(RegistrationUtil.java:75)
Caused by: java.sql.SQLRecoverableException: IO Error: Connection reset by peer: socket write error
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:752)
    at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:666)
</code>```

Code throwing the exception is basically this:

```<code>        // use properties to open the datasource for work
        System.out.println("Opening database connection.");
        logger.info("Opening database");
        String dbDriver = dbProps.get("dbDriver");
        String dbURL = dbProps.get("dbURL");
        String username = dbProps.get("username");
        String password = dbProps.get("password");

        Base.open(dbDriver, dbURL, username, password);
        logger.info("Database successfully opened.");
</code>```

Everything I've googled indicates the problem is a "network issue"...except that on this same machine, I am currently connected to the very table I'm trying to open via TOAD...and I also am running a jboss as server connecting to that very same database...so there is no way it is a network problem.

I'm at a total loss.

Java1.8, ojdbc7.jar, all running on a Microsoft Surface Pro 3..., Oracle version is 12.0.2 running remotely.

答: Your exception has nothing to do with AcitveJDBC. There is a problem with your Oracle configuration. I bet you will get the same exception if you try just JDBC with the same parameters. When/if you fix your issue with JDBC, ActiveJDBC will work just fine. </p>

Title: Socket write error with activejdbc

Body:
I have a pretty simple commandline app that runs inside of eclipse that connects to an Oracle 12 database and issues a pretty simple query.  I'm getting the following exception:

Exception in thread "main" org.javalite.activejdbc.InitException: Failed to connect to JDBC URL: jdbc:oracle:thin:@oratest2a.emspic.org:1521:workstst
    at org.javalite.activejdbc.DB.open(DB.java:93)
    at org.javalite.activejdbc.Base.open(Base.java:64)
    at org.emspic.works.RegistrationUtil.doMain(RegistrationUtil.java:135)
    at org.emspic.works.RegistrationUtil.main(RegistrationUtil.java:75)
Caused by: java.sql.SQLRecoverableException: IO Error: Connection reset by peer: socket write error
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:752)
    at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:666)

Code throwing the exception is basically this:

        // use properties to open the datasource for work
        System.out.println("Opening database connection.");
        logger.info("Opening database");
        String dbDriver = dbProps.get("dbDriver");
        String dbURL = dbProps.get("dbURL");
        String username = dbProps.get("username");
        String password = dbProps.get("password");

        Base.open(dbDriver, dbURL, username, password);
        logger.info("Database successfully opened.");

Everything I've googled indicates the problem is a "network issue"...except that on this same machine, I am currently connected to the very table I'm trying to open via TOAD...and I also am running a jboss as server connecting to that very same database...so there is no way it is a network problem.

I'm at a total loss.

Java1.8, ojdbc7.jar, all running on a Microsoft Surface Pro 3..., Oracle version is 12.0.2 running remotely.


问:
IIS 10.0 Detailed Error - 404.0 - Not Found - After Windows 10 Update
I'm quite confused that what happened to my Web Api Application or IIS after Windows 10 Update.

Some controllers like the following are working perfectly :

```<code>[RoutePrefix("api/test")]
public class TestController : ApiController {
    [HttpPost]
    [Route("test01/{str}")]
    public IHttpActionResult Test01([FromUri]string str) {
        return Ok(str);
    }
}
</code>```

But some others like this don't work and return IIS 10.0 Detailed Error - 404.0 - Not Found:

```<code>[RoutePrefix("api/companies")]
public class CompaniesController : ApiController {
    [HttpPost]
    [Route("test/{str}")]
    public IHttpActionResult PostCompany([FromUri]string str) {
        return Ok(str);
    }
}
</code>```

Note: I've removed updates of Windows and Visual Studio. Even reinstalled Visual Studio and restarted IIS from windows features but didn't make any change.

Now I'm thinking about reinstalling operating system. What's your suggestion?

More Info: I've tested it on my co-worker's machine and all its actions work as expected.

答:
After trying lots of solutions related to operating system, visual studio and iis, I found the real problem which was caused by referencing another web-api project with the same controller names.

I'm not quiet sure whether it is a bug or not, I haven't expected such behavior, though.

Body:
I'm quite confused that what happened to my Web Api Application or IIS after Windows 10 Update.

Some controllers like the following are working perfectly :

[RoutePrefix("api/test")]
public class TestController : ApiController {
    [HttpPost]
    [Route("test01/{str}")]
    public IHttpActionResult Test01([FromUri]string str) {
        return Ok(str);
    }
}

But some others like this don't work and return IIS 10.0 Detailed Error - 404.0 - Not Found:

[RoutePrefix("api/companies")]
public class CompaniesController : ApiController {
    [HttpPost]
    [Route("test/{str}")]
    public IHttpActionResult PostCompany([FromUri]string str) {
        return Ok(str);
    }
}

Note: I've removed updates of Windows and Visual Studio. Even reinstalled Visual Studio and restarted IIS from windows features but didn't make any change.

Now I'm thinking about reinstalling operating system. What's your suggestion?

More Info: I've tested it on my co-worker's machine and all its actions work as expected.


问:
Solution for Must use scalare variable in asp.net
```<code>protected void showData()
{
    DataTable dt = new DataTable();

    SqlDataAdapter adapt = new SqlDataAdapter("select @orderID, @buyersName, @deliveryAddress, @productID, @productName, @category, @image, @price, @paymentMode, @holderName, @OrderDate, @PhoneNo from tblOrderDetails", con);
    adapt.Fill(dt);

    GridView1.DataSource = dt;
    GridView1.DataBind();
}
</code>```

This code is showing an error:

Must use scalar variable @orderId

What do I have to correct?

答:
```<code>"select @orderID, @buyersName, @deliveryAddress, @productID, @productName, @category, @image, @price, @paymentMode, @holderName, @OrderDate, @PhoneNo from tblOrderDetails", con);
</code>```

This code is wrong.You need to remove @ from the column name.
This link may help you.

Body:
protected void showData()
{
    DataTable dt = new DataTable();

    SqlDataAdapter adapt = new SqlDataAdapter("select @orderID, @buyersName, @deliveryAddress, @productID, @productName, @category, @image, @price, @paymentMode, @holderName, @OrderDate, @PhoneNo from tblOrderDetails", con);
    adapt.Fill(dt);

    GridView1.DataSource = dt;
    GridView1.DataBind();
}

This code is showing an error:

Must use scalar variable @orderId

What do I have to correct?

Body:
"select @orderID, @buyersName, @deliveryAddress, @productID, @productName, @category, @image, @price, @paymentMode, @holderName, @OrderDate, @PhoneNo from tblOrderDetails", con);

This code is wrong.You need to remove @ from the column name.
This link may help you.


问:
Conditional formatting multiple rules to single cell
I have used one formula to change the font colour if a cell contains the text "complete" & another formula to add a light blue fill to the entire row if the word "odd" appears in a cell which is in a different column to the first formula.

The conditions seem to clash & although I have changed and played with the order of the conditions & checked there is no conflict in the fill/background or the font colour, even when changing the font colour manually again the fill from the second formula returns the font the cell to black although it is set to automatic in the conditional formatting rule with the fill ?

I wonder where i am going wrong as everything suggests the two conditions should work fine together though when the fill is applied the font goes back to black when it should be green ?

Have you any suggestions ?

答: I found the issue, I needed to press clear on the font section of the formatting on the fill condition and then clear on the fill. Basically as a rule I press clear on anything not required in that condition and this seems to avoid the conflict and run upto 6 rules on the same cell with no problems!</p>