问:
MySql syntax error in Eclipse(java)
I'm using Eclipse along with Xampp. I have written this code which should connect to the server, create database, table and fill it with some names:

```<code>import java.sql.*;

public class Database {

    public static void main(String[] args)
    {
        String user = "root" , pass = "" , url =
"jdbc:mysql://127.0.0.1:3306/";
        try
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conn = DriverManager.getConnection(url, user, pass);
            Statement stat = conn.createStatement();

            stat.execute("CREATE DATABASE IF NOT EXISTS Database");
            stat.execute("USE Database");

            stat.execute("DROP TABLE IF EXISTS Names");
            stat.execute("CREATE TABLE Names ("+
                    "id BIGINT NOT NULL AUTO_INCREMENT,"
                    + "fname VARCHAR(25),"
                    + "lname VARCHAR(25),"
                    + "PRIMARY KEY(id)"
                    + ")");

            stat.execute("INSERT INTO Names (fname , lname) VALUES"+"('Jan',
'Kowalski'), (Ala', 'Kowalski'), ('James', 'Bobo')");

            ResultSet res = stat.executeQuery("SELECT * FROM Names WHERE
lname = 'Kowalski'");
            while (res.next())
            {
                System.out.println(res.getString("fname") + " " +
res.getString("lname"));
            }
            System.out.println("");

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }

}
</code>```

And i get the following error :

```<code>com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error
in your SQL syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near 'Database' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2497)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2455)
at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:839)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:739)
at Database.main(Database.java:14)
</code>```

I've tried looking up in some documentation and see if there was something I missed but couldn't find anything.

答:
You need to give that database of your's a name besides Database because that's a reserved word in MySQL. Replace these two lines:

```<code>stat.execute("CREATE DATABASE IF NOT EXISTS MyDatabase");
stat.execute("USE MyDatabase");
</code>```

replacing MyDatabase with whatever you want to name it.

Title: MySql syntax error in Eclipse(java)

Body:
I'm using Eclipse along with Xampp. I have written this code which should connect to the server, create database, table and fill it with some names:

import java.sql.*;

public class Database {

    public static void main(String[] args)
    {
        String user = "root" , pass = "" , url =
"jdbc:mysql://127.0.0.1:3306/";
        try
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conn = DriverManager.getConnection(url, user, pass);
            Statement stat = conn.createStatement();

            stat.execute("CREATE DATABASE IF NOT EXISTS Database");
            stat.execute("USE Database");

            stat.execute("DROP TABLE IF EXISTS Names");
            stat.execute("CREATE TABLE Names ("+
                    "id BIGINT NOT NULL AUTO_INCREMENT,"
                    + "fname VARCHAR(25),"
                    + "lname VARCHAR(25),"
                    + "PRIMARY KEY(id)"
                    + ")");

            stat.execute("INSERT INTO Names (fname , lname) VALUES"+"('Jan',
'Kowalski'), (Ala', 'Kowalski'), ('James', 'Bobo')");

            ResultSet res = stat.executeQuery("SELECT * FROM Names WHERE
lname = 'Kowalski'");
            while (res.next())
            {
                System.out.println(res.getString("fname") + " " +
res.getString("lname"));
            }
            System.out.println("");

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }

}

And i get the following error :

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error
in your SQL syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near 'Database' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2497)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2455)
at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:839)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:739)
at Database.main(Database.java:14)

I've tried looking up in some documentation and see if there was something I missed but couldn't find anything.

Body:
You need to give that database of your's a name besides Database because that's a reserved word in MySQL. Replace these two lines:

stat.execute("CREATE DATABASE IF NOT EXISTS MyDatabase");
stat.execute("USE MyDatabase");

replacing MyDatabase with whatever you want to name it.


来源: stackexchange

问:
OpenSSL implements PKCS#1 v2.1?
I'm using OpenSSL to do a encryption module for my project. I need a RSA PKCS#1 v2.1 implementation. How can I check if OpenSSL implements PKCS#1 v2.1?

Some people says that is implemented:

RFC 3447(pkcs#1 v2.1): Is it implemented in Openssl ? If so from which version?

But in the documentation is PKCS#1 v2.0.

So, is it implemented? If not, where can I found a library with PKCS#1 v2.1?

答:
I'm sorry to say that your requirements are not that sensible.

The PKCS#1 standards define various algorithms that may be used. They also provide names for them such as RSAES-OAEP and RSAES-PKCS1-v1_5 (which is the original encryption scheme introduced in PKCS#1 v1.5). These schemes are fully compatible with the schemes described in PKCS#1 v2.0.

Fortunately for you you should be able to use OpenSSL without issue. It's very unlikely to fail. But first you need to know the algorithm and possible algorithm parameters (for OAEP / MGF1) you should be using.

So try it out and come back if it does fail.

ContentLicense: CC BY-SA 3.0

Title: OpenSSL implements PKCS#1 v2.1?


问:
Compiling driver for ARMv7 vs ARMv5
I've managed to compile a driver for an ARM based device, but the driver crashed when I try to load it.
here is the output from cpuinfo:

```<code>Processor       : ARMv7 Processor rev 2 (v7l)
BogoMIPS        : 999.42
Features        : swp half thumb fastmult vfp edsp neon vfpv3
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x3
CPU part        : 0xc08
CPU revision    : 2
</code>```

Here is the uname -r output

```<code>2.6.37
</code>```

modinfo driver.ko

```<code>filename:       cp210x.ko
description:    Silicon Labs CP210x RS232 serial adaptor driver
license:        GPL
vermagic:       2.6.37 mod_unload ARMv7
vermagic:       2.6.37 mod_unload modversions ARMv5
parm:           debug:Enable verbose debugging messages
</code>```

As you can I've added an extra vermagic (2.6.37 mod_unload ARMv7) so it will match the target system.

So if I understand this correct, I've compiled this module for an ARMv5 cpu, while the target is v7. Could this be the cause of the device driver crashing?

The device has this driver, but its embedded into an other driver package from the hw producer. This package also load some drivers that we cannot use. This driver package is not load, but I guess this indicate that this driver should work on this hardware some how.

here is the crash log

```<code>modprobe cp210x.ko
Unable to handle kernel NULL pointer dereference at virtual address 0000000a
pgd = ca1fc000
[0000000a] *pgd=870dd031, *pte=00000000, *ppte=00000000
Internal error: Oops: 17 [#1]
last sysfs file: /sys/kernel/uevent_seqnum
Modules linked in: dahdi_dummy dahdi cmemk syslink ipt_MASQUERADE nf_nat iptable_filter ip_tables ipt_LOG xt_state nf_conntrack_ftp nf_conntrack_ipv4 nf_conntrack nf_defrag_ipv4 xt_recent xt_mac xt_limit work_led reset_button ipv6
CPU: 0    Not tainted  (2.6.37 #1)
PC is at sys_init_module+0xfe0/0x1460
LR is at sys_init_module+0xe7c/0x1460
pc : [<c00836e8>]    lr : [<c0083584>]    psr: 20000013
sp : cc5e9ed0  ip : bf3828dc  fp : cc5e8000
r10: bf385ca8  r9 : cf3bcb4e  r8 : 000000c5
r7 : 00000027  r6 : bf382544  r5 : bf38266c  r4 : bf385ca8
r3 : 00000000  r2 : c7c9f000  r1 : 0000000a  r0 : 0000000a
Flags: nzCv  IRQs on  FIQs on  Mode SVC_32  ISA ARM  Segment user
Control: 10c5387d  Table: 8a1fc019  DAC: 00000015
Process modprobe (pid: 2676, stack limit = 0xcc5e82e8)
Stack: (0xcc5e9ed0 to 0xcc5ea000)
9ec0:                                     bf382544 00000001 000ac048 bf382550
9ee0: 000000c5 cf3bd5a4 cf3b8000 000055f4 cf3bd20c cf3bd128 cf3bc2a0 c7c9f000
9f00: 0000266c 000028dc 00000000 00000000 00000017 00000018 00000010 0000000d
9f20: 00000009 00000000 6e72656b 00006c65 00000000 00000000 00000000 00000000
9f40: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
9f60: 00000000 00000000 c9a19540 00000000 ca2403c0 00000006 c9a19540 00000000
9f80: ca2403c0 000055f4 00000000 00000006 00000080 c0037c28 cc5e8000 00000000
9fa0: 00000001 c0037a80 000055f4 00000000 000ac998 000055f4 000ac048 000ac978
9fc0: 000055f4 00000000 00000006 00000080 000ac008 000ac028 000ac998 00000001
9fe0: bebaf968 bebaf958 00017764 40214740 60000010 000ac998 c1e38bcc 03de8ad9
[<c00836e8>] (sys_init_module+0xfe0/0x1460) from [<c0037a80>] (ret_fast_syscall+0x0/0x30)
Code: e7923103 e1a03133 e3130001 15963128 (17d33000)
---[ end trace 6e8943127db36208 ]---
Segmentation fault
</code>```

答:
I hade to change the cp210x.c file and comment out where there was any use of mutex. this was the only place: </p>

```<code>static void cp210x_close(struct usb_serial_port *port)
{
        dbg("%s - port %d", __func__, port->number);

        usb_serial_generic_close(port);

        /* mutex_lock(&port->serial->disc_mutex);*/
        if (!port->serial->disconnected)
                cp210x_set_config_single(port, CP210X_IFC_ENABLE, UART_DISABLE);
        /* mutex_unlock(&port->serial->disc_mutex);*/
}
</code>```

Title: Compiling driver for ARMv7 vs ARMv5

Body:
I've managed to compile a driver for an ARM based device, but the driver crashed when I try to load it.
here is the output from cpuinfo:

Processor       : ARMv7 Processor rev 2 (v7l)
BogoMIPS        : 999.42
Features        : swp half thumb fastmult vfp edsp neon vfpv3
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x3
CPU part        : 0xc08
CPU revision    : 2

Here is the uname -r output

2.6.37

modinfo driver.ko

filename:       cp210x.ko
description:    Silicon Labs CP210x RS232 serial adaptor driver
license:        GPL
vermagic:       2.6.37 mod_unload ARMv7
vermagic:       2.6.37 mod_unload modversions ARMv5
parm:           debug:Enable verbose debugging messages

As you can I've added an extra vermagic (2.6.37 mod_unload ARMv7) so it will match the target system.

So if I understand this correct, I've compiled this module for an ARMv5 cpu, while the target is v7. Could this be the cause of the device driver crashing?

The device has this driver, but its embedded into an other driver package from the hw producer. This package also load some drivers that we cannot use. This driver package is not load, but I guess this indicate that this driver should work on this hardware some how.

here is the crash log

modprobe cp210x.ko
Unable to handle kernel NULL pointer dereference at virtual address 0000000a
pgd = ca1fc000
[0000000a] *pgd=870dd031, *pte=00000000, *ppte=00000000
Internal error: Oops: 17 [#1]
last sysfs file: /sys/kernel/uevent_seqnum
Modules linked in: dahdi_dummy dahdi cmemk syslink ipt_MASQUERADE nf_nat iptable_filter ip_tables ipt_LOG xt_state nf_conntrack_ftp nf_conntrack_ipv4 nf_conntrack nf_defrag_ipv4 xt_recent xt_mac xt_limit work_led reset_button ipv6
CPU: 0    Not tainted  (2.6.37 #1)
PC is at sys_init_module+0xfe0/0x1460
LR is at sys_init_module+0xe7c/0x1460
pc : [<c00836e8>]    lr : [<c0083584>]    psr: 20000013
sp : cc5e9ed0  ip : bf3828dc  fp : cc5e8000
r10: bf385ca8  r9 : cf3bcb4e  r8 : 000000c5
r7 : 00000027  r6 : bf382544  r5 : bf38266c  r4 : bf385ca8
r3 : 00000000  r2 : c7c9f000  r1 : 0000000a  r0 : 0000000a
Flags: nzCv  IRQs on  FIQs on  Mode SVC_32  ISA ARM  Segment user
Control: 10c5387d  Table: 8a1fc019  DAC: 00000015
Process modprobe (pid: 2676, stack limit = 0xcc5e82e8)
Stack: (0xcc5e9ed0 to 0xcc5ea000)
9ec0:                                     bf382544 00000001 000ac048 bf382550
9ee0: 000000c5 cf3bd5a4 cf3b8000 000055f4 cf3bd20c cf3bd128 cf3bc2a0 c7c9f000
9f00: 0000266c 000028dc 00000000 00000000 00000017 00000018 00000010 0000000d
9f20: 00000009 00000000 6e72656b 00006c65 00000000 00000000 00000000 00000000
9f40: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
9f60: 00000000 00000000 c9a19540 00000000 ca2403c0 00000006 c9a19540 00000000
9f80: ca2403c0 000055f4 00000000 00000006 00000080 c0037c28 cc5e8000 00000000
9fa0: 00000001 c0037a80 000055f4 00000000 000ac998 000055f4 000ac048 000ac978
9fc0: 000055f4 00000000 00000006 00000080 000ac008 000ac028 000ac998 00000001
9fe0: bebaf968 bebaf958 00017764 40214740 60000010 000ac998 c1e38bcc 03de8ad9
[<c00836e8>] (sys_init_module+0xfe0/0x1460) from [<c0037a80>] (ret_fast_syscall+0x0/0x30)
Code: e7923103 e1a03133 e3130001 15963128 (17d33000)
---[ end trace 6e8943127db36208 ]---
Segmentation fault

Body:
I hade to change the cp210x.c file and comment out where there was any use of mutex. this was the only place:

static void cp210x_close(struct usb_serial_port *port)
{
        dbg("%s - port %d", __func__, port->number);

        usb_serial_generic_close(port);

        /* mutex_lock(&port->serial->disc_mutex);*/
        if (!port->serial->disconnected)
                cp210x_set_config_single(port, CP210X_IFC_ENABLE, UART_DISABLE);
        /* mutex_unlock(&port->serial->disc_mutex);*/
}


问:
SQL Server 2014 - How to find Distinct records
I have a list of Contact that have First Names, Last Names and Email addresses. Some Email addresses have multiple First and Last Names. I am more concerned about the Email Addresses. I really just want the top name for that Email Address.

My Code doesn't work obviously:

```<code>SELECT Salutation
, FirstName
, LastName
, EmailAddress
FROM Contact
--GROUP BY EmailAddress  ---I know a Group by will surely help
</code>```

I have tried

```<code>SELECT max(Salutation)
    ,max(FirstName)
    ,max(LastName)
    ,max(EMailAddress)
FROM Contact
WHERE EMailAddress NOT LIKE ''
GROUP BY EMailAddress
</code>```

This worked but I'm wondering if there is a better way to do it.

答:
How do you define top name?

Using max() for names can easily return results with mixed names, e.g. 'Aaron Bertrand' and 'Itzik Ben-Gan' would return 'Itzik Bertrand'. If you have mixed Salutation then you will always get 'Mrs.' from 'Mr.' and 'Mrs.' which might not be appropriate either.

using top with ties and row_number():

```<code>select top 1 with ties
    Salutation
  , FirstName
  , LastName
  , EmailAddress
from contact
where EmailAddress <> ''
order by row_number() over (
  partition by EmailAddress
  order by FirstName /* your 'top' criteria here, FirstName is a placeholder */
  );
</code>```

cross apply() version:

```<code>select distinct
    x.Salutation
  , x.FirstName
  , x.LastName
  , t.EmailAddress
from contact t
  cross apply (
    select top 1
        i.Salutation
      , i.FirstName
      , i.LastName
    from t as i
    where i.EmailAddress = t.EmailAddress
    order by i.FirstName
    ) as x
where t.EmailAddress <> ''
</code>```

common table expression with row_number() version:

```<code>;with cte as (
  select *
    , rn = row_number() over (
             partition by EmailAddress
                 order by FirstName
            )
  from contact
  where EmailAddress <> ''
)
select
    Salutation
  , FirstName
  , LastName
  , EmailAddress
from cte
where rn = 1;
</code>```

I prefer using common table expressions, but the query inside it works just as well in the from clause:

row_number() in a subquery version:

```<code>select
    Salutation
  , FirstName
  , LastName
  , EmailAddress
from (
  select *
    , rn = row_number() over (
             partition by EmailAddress
                 order by FirstName
            )
    from contact
    where EmailAddress <> ''
  ) s
where rn = 1;
</code>```

Body:
I have a list of Contact that have First Names, Last Names and Email addresses. Some Email addresses have multiple First and Last Names. I am more concerned about the Email Addresses. I really just want the top name for that Email Address.

My Code doesn't work obviously:

SELECT Salutation
, FirstName
, LastName
, EmailAddress
FROM Contact
--GROUP BY EmailAddress  ---I know a Group by will surely help

I have tried

SELECT max(Salutation)
    ,max(FirstName)
    ,max(LastName)
    ,max(EMailAddress)
FROM Contact
WHERE EMailAddress NOT LIKE ''
GROUP BY EMailAddress

This worked but I'm wondering if there is a better way to do it.

Body:
How do you define top name?

Using max() for names can easily return results with mixed names, e.g. 'Aaron Bertrand' and 'Itzik Ben-Gan' would return 'Itzik Bertrand'. If you have mixed Salutation then you will always get 'Mrs.' from 'Mr.' and 'Mrs.' which might not be appropriate either.

using top with ties and row_number():

select top 1 with ties
    Salutation
  , FirstName
  , LastName
  , EmailAddress
from contact
where EmailAddress <> ''
order by row_number() over (
  partition by EmailAddress
  order by FirstName /* your 'top' criteria here, FirstName is a placeholder */
  );

cross apply() version:

select distinct
    x.Salutation
  , x.FirstName
  , x.LastName
  , t.EmailAddress
from contact t
  cross apply (
    select top 1
        i.Salutation
      , i.FirstName
      , i.LastName
    from t as i
    where i.EmailAddress = t.EmailAddress
    order by i.FirstName
    ) as x
where t.EmailAddress <> ''

common table expression with row_number() version:

;with cte as (
  select *
    , rn = row_number() over (
             partition by EmailAddress
                 order by FirstName
            )
  from contact
  where EmailAddress <> ''
)
select
    Salutation
  , FirstName
  , LastName
  , EmailAddress
from cte
where rn = 1;

I prefer using common table expressions, but the query inside it works just as well in the from clause:

row_number() in a subquery version:

select
    Salutation
  , FirstName
  , LastName
  , EmailAddress
from (
  select *
    , rn = row_number() over (
             partition by EmailAddress
                 order by FirstName
            )
    from contact
    where EmailAddress <> ''
  ) s
where rn = 1;


问:
Match word followed by space and N number of digits
I'm trying to match a word followed by one space or tab character and 5 number digits. For example

```<code>some noise text off 12345 some noise text again.
</code>```

Another example would be :

```<code>Some noise text off 12345.
</code>```

The regex should match "off 12345".
Number may be followed by punctuation marks.
The pattern should match the word "off" and not any other word behind the number.

Thanks

答:
You can use a simple regex like this

```<code>off\s\d{5}
</code>```

Working demo

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to match a word followed by one space or tab character and 5 number digits. For example

some noise text off 12345 some noise text again.

Another example would be :

Some noise text off 12345.

The regex should match "off 12345".
Number may be followed by punctuation marks.
The pattern should match the word "off" and not any other word behind the number.

Thanks

Body:
You can use a simple regex like this

off\s\d{5}

Working demo


问:
Data To Munge: Stock Trading, Exchange Trading
I know that a lot of this information is probably entirely privatized, but does anyone know of a good source of real time information on what kind of trading activity is where in the market?  It doesn't need to be fast enough to actually make informed trading decisions based on it, I'm more looking to aggregate it into some beautiful graphics.  For fun.  Because I have personal problems.

I'd be grateful for any help!

答:
The best I'm aware of is the Yahoo Finance API.  It'll give you delayed prices and some bid/ask stuff.  There's a description of how it works here:
http://www.gummy-stuff.org/Yahoo-data.htm

ContentLicense: CC BY-SA 2.5


问:
list buttons responsive design
How can I put this button inline to be responsive?
had tried doing  but doesnt work.

```<code><div class="form-group btn-group"  >
    <ul class="btn-group list-inline social "  style="display: flex;">
      <li class="col-xs-12">
        <button type="submit" class="btn  btn-default" name="btn-login" id="btn-login">
          <span class="glyphicon glyphicon-log-in"></span>   Sign In
        </button>
      </li>
      <li class="col-xs-12">
        <a href="<?=$fbLoginUrl ?>" class="btn btn-social btn-facebook" style="float:left;margin-right:5px, color:#3B5998">Sign in with Facebook </a>
      </li>
      <li class="col-xs-12">
        <a href="register.php" class="btn btn-social btn-default" style="float:right;">Sign UP Here </a>
      </li>
    </ul>

  </div>
</code>```

答:
You better use @media queries. Set the @media query based on your target screen. Your button's text is too lengthy as well so it would be best if you display your lists by block to prevent overlapping the screen size.

Mobile View:

```<code>@media all and (max-width: 479px) {
ul.btn-group {
display: block;
}
ul.btn-group li {
display: block;
}
}
</code>```

Title: list buttons responsive design

Body:
How can I put this button inline to be responsive?
had tried doing  but doesnt work.

        <button type="submit" class="btn  btn-default" name="btn-login" id="btn-login">
             Sign In
        </button>

        <a href="<?=$fbLoginUrl ?>" class="btn btn-social btn-facebook" style="float:left;margin-right:5px, color:#3B5998">Sign in with Facebook

        Sign UP Here

Body:
You better use @media queries. Set the @media query based on your target screen. Your button's text is too lengthy as well so it would be best if you display your lists by block to prevent overlapping the screen size.

Mobile View:

@media all and (max-width: 479px) {
ul.btn-group {
display: block;
}
ul.btn-group li {
display: block;
}
}


问:
Visual Studio unknown build error. The fully qualified name must be less than 260 characters
I'm having trouble while building my WPF solution. Everytime I try to build it, I get this error message:

Unknown build error, 'The specified path, file name, or both are too
  long. The fully qualified file name must be less than 260 characters,
  and the directory name must be less than 248 characters.'

Someone can help me? I've already verified all the fields and their extension paths are ok. Can this be a problem with the TortoiseSVN or something like this? I recently added a folder to my solution, can be something with this?

答:
I had a similar issue where the compiler reported that there was a problem with the file ASPNETCOMPILER. The actual issue was that the solution contained a node_modules folder, and this folder can contain very lengthy paths, and it looks like the compiler can't handle this.

Windows 8.1 and 10 have an option to increase the Win32 path limit:

Open Group Policy Editor (Press Windows+R and type gpedit.msc and hit Enter)

From the Group Policy Editor window, navigate to the following node: Local Computer Policy\Computer Configuration\Administrative Templates\System\Filesystem

Doubleclick on Enable Win32 long paths option and enable it.

This may allow you to temporarily move the problem folder out of the build, which may allow you to successfully build, then you may be able to add the folder back into the solution without affecting anything.

See here for additional reference - https://www.microfocus.com/documentation/filr/filr-4/filr-desktop/t47bx2ogpfz7.html


问:
using ngCookies angular for login
I'm a beginner in angular. I want to use ngCookie for login. I'm using ajax get user information from a PHP backend, and if I have a user name, a logout button will be shown. Here is my code:

```<code>$http({
  method:'POST',
  url:'login.php',
  data:$.param(vm.formData),
  headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(Success);

function Success(response) {
  $cookies.get('username') = response.data.username;
  $cookies.put('username','username');
}
</code>```

Here is my html

```<code><div ng-show="username">
    <li><a href="">Hello {{username}}</a></li>
    <li><a href="">Log out</a></li>
</div>
</code>```

Error:

angular.js:12520 ReferenceError: Invalid left-hand side in assignment

答:
This is probably the error

```<code>$cookies.get('username') = response.data.username;
</code>```

If you want to assign a value to username try this

```<code>// Setting a cookie for the user
$cookies.put('currentUser', response.data.username);
// Retrieving a cookie for the user
var currentUser = $cookies.get('currentUser');
</code>```

For a logout button you could try

```<code><body ng-controller="MainCtrl">
<button ng-if="user">Log Out</button>
</body>

angular.controller("MainCtrl",function($scope,$cookies){
$scope.user = $cookies.get("currentUser");
});
</code>```

Title: using ngCookies angular for login

Body:
I'm a beginner in angular. I want to use ngCookie for login. I'm using ajax get user information from a PHP backend, and if I have a user name, a logout button will be shown. Here is my code:

$http({
  method:'POST',
  url:'login.php',
  data:$.param(vm.formData),
  headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(Success);

function Success(response) {
  $cookies.get('username') = response.data.username;
  $cookies.put('username','username');
}

Here is my html

Hello {{username}}

Log out

Error:

angular.js:12520 ReferenceError: Invalid left-hand side in assignment

Body:
This is probably the error

$cookies.get('username') = response.data.username;

If you want to assign a value to username try this

// Setting a cookie for the user
$cookies.put('currentUser', response.data.username);
// Retrieving a cookie for the user
var currentUser = $cookies.get('currentUser');

For a logout button you could try

<body ng-controller="MainCtrl">
<button ng-if="user">Log Out</button>
</body>

angular.controller("MainCtrl",function($scope,$cookies){
$scope.user = $cookies.get("currentUser");
});


问:
Using bagof/3 only for the side effect
Solving a very simple exercise in Prolog: print all numbers from 1 to 100, but instead of the number, print 'Fuzz' if number is a multiple of 3, 'Buzz' if multiple of 5, and 'FizzBuzz' if both.

I ended up doing the following:

```<code>fizzbuzz :- forall( between(1, 100, X), fizzbuzz(X) ).
fizzbuzz(X) :- ( write_fb(X) ; write_n(X) ), nl.

write_fb(X) :- bagof(_, fb(X), _).
fb(X) :- X rem 3 =:= 0, write('Fizz').
fb(X) :- X rem 5 =:= 0, write('Buzz').

write_n(X) :- write(X).
</code>```

but isn't there any predicate or a control structure that would avoid using bagof/3 only for its side effect? (I am always a bit unsure with using predicates only for the side effects).

答:
The problem:

Print all numbers from 1 to 100, but instead of the number, print 'Fuzz' if number is a multiple of 3, 'Buzz' if multiple of 5, and 'FizzBuzz' if both.

I think the fact that you encountered this peculiarity about bagof is an indication of a "smell" in your program. I find that happens to me a lot with Prolog. Prolog is actually a very minimal kit with not very much provided. I have learned over time that if I encounter a need for something that is NOT in that minimal kit, or my usage seems to betray the intended usage of a builtin feature, then almost always it is because there is a "smell" in my current approach.

More about "smell" here : https://en.wikipedia.org/wiki/Code_smell

I think the "smell" in your current approach becomes apparent when we outline a general sketch of the procedural flow that your program currently entails:

generate

print

transform

The problem is that you are trying to "print" BEFORE you "transform" .
You want to "print" AFTER you "transform", like this:

generate

transform

print

With this in mind we can rewrite the problem statement:

The NEW problem:

Solve for all each number:

Generate each number from 1 to 100, but transform each number into an each message, into each message 'Fuzz' if the each number is a multiple of 3, into each message 'Buzz' if the each number is a multiple of 5, into each message 'FizzBuzz' if the each number is both, then print each message.

The following is a program that aims to solve the above stated problem.

The program listing is followed by an example query session.

```<code>*/

/* -- prolog setup -- */

:-  ( op(10'1150,'yfx','forall')    )   .

:-  ( op(10'1150,'fy','if') )   .
:-  ( op(10'1140,'yfx','then') )    .
:-  ( op(10'1140,'yfx','else') )    .

(if IF then THEN else ELSE) :- (IF *-> THEN ; ELSE) .
(if IF then THEN) :- (IF *-> THEN ; (throw(false(IF)))) .

term_expansion((if IF then THEN else ELSE),((IF :- THEN *-> (true) ; ELSE)))    .
term_expansion((if IF then THEN),((IF :- THEN *-> (true) ; (throw(false(IF))))))    .

/* -- program -- */

if
(
  program(_)
)
then
(
  (
    if
    (
      generate(NUMBER)
    )
    then
    (
      true
    )
  )
  forall
  (
    if
    (
      transform(NUMBER,MESSAGE)
    )
    then
    (
      if
      (
        accept(NUMBER,MESSAGE)
      )
      then
      (
        if
        (
          echo(NUMBER)
        )
        then
        (
          echo(MESSAGE)
        )
      )
      else
      (
        true
      )
    )
  )
)
.

if
(
  generate(NUMBER)
)
then
(
  between(1,100,NUMBER)
)
.

if
(
  transform(NUMBER,MESSAGE)
)
then
(
  if
  (
    multiple_of_3(NUMBER)
  )
  then
  (
    if
    (
      multiple_of_5(NUMBER)
    )
    then
    (
      MESSAGE='FizzBuzz'
    )
    else
    (
      MESSAGE='Fuzz'
    )
  )
  else
  (
    if
    (
      multiple_of_5(NUMBER)
    )
    then
    (
      MESSAGE='Buzz'
    )
    else
    (
      % this contingency is undefined in the problem statement %
      true
    )
  )
)
.

if
(
  multiple_of_3(NUMBER)
)
then
(
  NUMBER rem 10'3 =:= 10'0
)
else
(
  false
)
.

if
(
  multiple_of_5(NUMBER)
)
then
(
  NUMBER rem 10'5 =:= 10'0
)
else
(
  false
)
.

if
(
  accept(NUMBER,MESSAGE)
)
then
(
  if
  (
    true
  )
  then
  (
    true
  )
  else
  (
    false
  )
)
else
(
  false
)
.

if
(
  echo(MESSAGE)
)
then
(
  if
  (
    writeq(MESSAGE)
  )
  then
  (
    nl
  )
)
.

/*

example query
=============

?-
program(_)
.

3
'Fuzz'
5
'Buzz'
6
'Fuzz'
9
'Fuzz'
12
'Fuzz'
15
'FizzBuzz'
18
'Fuzz'

[ ... and so on as expected ... ]

90
'FizzBuzz'
93
'Fuzz'
95
'Buzz'
96
'Fuzz'
99
'Fuzz'
100
'Buzz'
true.

?-
</code>```

However, the program as currently presented does not quite produce the intended output as presented above.

In the program above there is a marker:

```<code>  % this contingency is undefined in the problem statement %
</code>```

Issue needs to be resolved before the program is 100% satisfactory.

Tested using swi-prolog and yap.

Title: Using bagof/3 only for the side effect

Body:
Solving a very simple exercise in Prolog: print all numbers from 1 to 100, but instead of the number, print 'Fuzz' if number is a multiple of 3, 'Buzz' if multiple of 5, and 'FizzBuzz' if both.

I ended up doing the following:

fizzbuzz :- forall( between(1, 100, X), fizzbuzz(X) ).
fizzbuzz(X) :- ( write_fb(X) ; write_n(X) ), nl.

write_fb(X) :- bagof(_, fb(X), _).
fb(X) :- X rem 3 =:= 0, write('Fizz').
fb(X) :- X rem 5 =:= 0, write('Buzz').

write_n(X) :- write(X).

but isn't there any predicate or a control structure that would avoid using bagof/3 only for its side effect? (I am always a bit unsure with using predicates only for the side effects).

Body:
The problem:

Print all numbers from 1 to 100, but instead of the number, print 'Fuzz' if number is a multiple of 3, 'Buzz' if multiple of 5, and 'FizzBuzz' if both.

I think the fact that you encountered this peculiarity about bagof is an indication of a "smell" in your program. I find that happens to me a lot with Prolog. Prolog is actually a very minimal kit with not very much provided. I have learned over time that if I encounter a need for something that is NOT in that minimal kit, or my usage seems to betray the intended usage of a builtin feature, then almost always it is because there is a "smell" in my current approach.

More about "smell" here : https://en.wikipedia.org/wiki/Code_smell

I think the "smell" in your current approach becomes apparent when we outline a general sketch of the procedural flow that your program currently entails:

generate

print

transform

The problem is that you are trying to "print" BEFORE you "transform" .
You want to "print" AFTER you "transform", like this:

generate

transform

print

With this in mind we can rewrite the problem statement:

The NEW problem:

Solve for all each number:

Generate each number from 1 to 100, but transform each number into an each message, into each message 'Fuzz' if the each number is a multiple of 3, into each message 'Buzz' if the each number is a multiple of 5, into each message 'FizzBuzz' if the each number is both, then print each message.

The following is a program that aims to solve the above stated problem.

The program listing is followed by an example query session.

*/

/* -- prolog setup -- */

:-  ( op(10'1150,'yfx','forall')    )   .

:-  ( op(10'1150,'fy','if') )   .
:-  ( op(10'1140,'yfx','then') )    .
:-  ( op(10'1140,'yfx','else') )    .

(if IF then THEN else ELSE) :- (IF *-> THEN ; ELSE) .
(if IF then THEN) :- (IF *-> THEN ; (throw(false(IF)))) .

term_expansion((if IF then THEN else ELSE),((IF :- THEN *-> (true) ; ELSE)))    .
term_expansion((if IF then THEN),((IF :- THEN *-> (true) ; (throw(false(IF))))))    .

/* -- program -- */

if
(
  program(_)
)
then
(
  (
    if
    (
      generate(NUMBER)
    )
    then
    (
      true
    )
  )
  forall
  (
    if
    (
      transform(NUMBER,MESSAGE)
    )
    then
    (
      if
      (
        accept(NUMBER,MESSAGE)
      )
      then
      (
        if
        (
          echo(NUMBER)
        )
        then
        (
          echo(MESSAGE)
        )
      )
      else
      (
        true
      )
    )
  )
)
.

if
(
  generate(NUMBER)
)
then
(
  between(1,100,NUMBER)
)
.

if
(
  transform(NUMBER,MESSAGE)
)
then
(
  if
  (
    multiple_of_3(NUMBER)
  )
  then
  (
    if
    (
      multiple_of_5(NUMBER)
    )
    then
    (
      MESSAGE='FizzBuzz'
    )
    else
    (
      MESSAGE='Fuzz'
    )
  )
  else
  (
    if
    (
      multiple_of_5(NUMBER)
    )
    then
    (
      MESSAGE='Buzz'
    )
    else
    (
      % this contingency is undefined in the problem statement %
      true
    )
  )
)
.

if
(
  multiple_of_3(NUMBER)
)
then
(
  NUMBER rem 10'3 =:= 10'0
)
else
(
  false
)
.

if
(
  multiple_of_5(NUMBER)
)
then
(
  NUMBER rem 10'5 =:= 10'0
)
else
(
  false
)
.

if
(
  accept(NUMBER,MESSAGE)
)
then
(
  if
  (
    true
  )
  then
  (
    true
  )
  else
  (
    false
  )
)
else
(
  false
)
.

if
(
  echo(MESSAGE)
)
then
(
  if
  (
    writeq(MESSAGE)
  )
  then
  (
    nl
  )
)
.

/*

example query
=============

?-
program(_)
.

3
'Fuzz'
5
'Buzz'
6
'Fuzz'
9
'Fuzz'
12
'Fuzz'
15
'FizzBuzz'
18
'Fuzz'

[ ... and so on as expected ... ]

90
'FizzBuzz'
93
'Fuzz'
95
'Buzz'
96
'Fuzz'
99
'Fuzz'
100
'Buzz'
true.

?-

However, the program as currently presented does not quite produce the intended output as presented above.

In the program above there is a marker:

  % this contingency is undefined in the problem statement %

Issue needs to be resolved before the program is 100% satisfactory.

Tested using swi-prolog and yap.


问:
How to create a single Calendar object with a Date object and a string that holds the time. - JAVA
I am currently trying to make a Calendar object. One function returns a Date object which holds the Month, Day and year. And another function returns a string object holding the time.

How do I use both of this information to create a single Calendar object?

I am using Java

Thank you.

答:
```<code>import java.text.SimpleDateFormat;
import java.util.Calender;
import java.util.Date;

public class Test {
    @SuppressWarnings("deprecation")
    public static void main (String args[]) {

    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = sdf.parse("2011-03-17");
        // suppose your method return date object like prior line date object.

        //now you get time from a method which returns date String like time below:
        String time = "23:44:33";
        String splitTime[] = time.split(":");

        // Now create a single CAlender object containing time and date

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DATE, date.getDate());
        calendar.set(Calendar.MONTH, date.getMonth());
        calendar.set(Calendar.YEAR, date.getYear());
        // till this point we have set the date

        // now we will set the time
        calendar.set(Calendar.HOUR, Integer.parseInt(splitTime[0]));
        calendar.set(Calendar.MINUTE, Integer.parseInt(splitTime[1]));
        calendar.set(Calendar.SECOND, Integer.parseInt(splitTime[2]));

        System.out.println(sdf1.format(calendar.getTime()));

        //You will get the desired result
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

But
Fetching day, month, year from date obbject is Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR/MONTH/DAY). Refer Java Doc for more information.

For year we need to add 1900 in year what we get from d.getYear(). Because it provides year - 1900. Still, deprecated code shouldn't be used. Use Calender class only.

Hope you got your answer !!!!
</code>```


答:
To be more generic, you can use

```<code>\b\w+\s\d{5}\b
</code>```

Here \b matches the boundaries. If you do not use it, you may incorrectly match something like

```<code>123off 12345
off 1234567
</code>```

Title: Match word followed by space and N number of digits

Body:
To be more generic, you can use

\b\w+\s\d{5}\b

Here \b matches the boundaries. If you do not use it, you may incorrectly match something like

123off 12345
off 1234567


问:
Enable directory listing in Google Cloud Storage
Is it possible to enable Directory listing in Google Cloud Storage?

I was thinking on having a "domain bucket" and use it to list all the contents, similar to Nginx's autoindex on or Apache's Options +Indexes.

If I make the bucket public all contents will be listed as a XML, but not like a directory listing.

答: You might want to take a look at s3-bucket-listing. It's for Amazon S3 but works with GCS as well.</p>


问:
c++ cast int to double not working
```<code>int main(){
    srand(time(0));
    int numOfTimes;
    int randNum;
    int oneRoll = 0, twoRoll = 0, threeRoll = 0, fourRoll = 0, fiveRoll = 0, sixRoll = 0;
    int onePercent, twoPercent, threePercent, fourPercent, fivePercent, sixPercent;

    int count = 0;
    cout << "How many times would you like to roll the dice?\n";
    cin >> numOfTimes;

    while (numOfTimes <= 0){
        cout << "Invalid entry enter a number greater than 0\n";
        cout << "How many times would you like to roll the dice?\n";
        cin >> numOfTimes;
    }

    while (count < numOfTimes)
        {
            randNum = rand() % 6 + 1;

            switch (randNum)
                {
                case 1:
                    oneRoll++;
                    break;
                case 2:
                    twoRoll++;
                    break;
                case 3:
                    threeRoll++;
                    break;
                case 4:
                    fourRoll++;
                    break;
                case 5:
                    fiveRoll++;
                    break;
                case 6:
                    sixRoll++;
                    break;
                default:
                    cout << "\n";
                }

            count++;
        }

    onePercent = (int)((oneRoll*100.0) /numOfTimes);
    twoPercent = (int)((twoRoll*100.0) / numOfTimes);

    cout << " # Rolled          # Times % Times" << endl;
    cout << "---------  --------    --------" << endl;
    cout << "1      " << oneRoll << "       " <<double (onePercent)  << endl;
    cout << "2      " << twoRoll << "       " << "" << endl;
    cout << "3      " << threeRoll << "     " << ""<< endl;
    cout << "4      " << fourRoll << "      " <<""  << endl;
    cout << "5      " << fiveRoll << "      " <<""  << endl;
    cout << "6      " << sixRoll << "       " <<"" << endl;
</code>```

<p>I need it to print out the the one percent as a double. So I converted it as an int then to a double so it only prints two zeros like this (14.00) but its not converting at all its only printing 14 </p>

答:
The main problem, just as Barmar mentioned in his comment, is that although you want the value to be printed to 2 decimal points, you round off the number in onePercent when you do:

```<code>onePercent = (int)((oneRoll*100.0) /numOfTimes); // Casting to "int" rounds off the number
</code>```

Also, the declared data type for onePercent is int from the start:

```<code>int onePercent, twoPercent, threePercent, fourPercent, fivePercent, sixPercent; // onePercent is an "int" here
</code>```

So you don't need a typecast of int, because you're casting an int to an int.

Therefore, even if you print onePercentwith 2 decimal-point precision, you will always get .00 as a result.

I would recommend taking off the (int) cast from that expression itself, and changing the initial data type of onePercent to type double. If you do not want to change the data types for the other variables declared alongside onePercent, then declare onePercent as a double on another line. That way, the precision of the value after the calculation will be maintained, and you will be able to output it to 2 decimal places.

As an aside, to specify the number of decimal places to output, the setprecision() function can be used:

```<code>cout << setprecision(2) << ... << endl; // The value passed to "setprecision" is up to you.
</code>```

Title: c++ cast int to double not working

Body:
int main(){
    srand(time(0));
    int numOfTimes;
    int randNum;
    int oneRoll = 0, twoRoll = 0, threeRoll = 0, fourRoll = 0, fiveRoll = 0, sixRoll = 0;
    int onePercent, twoPercent, threePercent, fourPercent, fivePercent, sixPercent;

    int count = 0;
    cout << "How many times would you like to roll the dice?\n";
    cin >> numOfTimes;

    while (numOfTimes <= 0){
        cout << "Invalid entry enter a number greater than 0\n";
        cout << "How many times would you like to roll the dice?\n";
        cin >> numOfTimes;
    }

    while (count < numOfTimes)
        {
            randNum = rand() % 6 + 1;

            switch (randNum)
                {
                case 1:
                    oneRoll++;
                    break;
                case 2:
                    twoRoll++;
                    break;
                case 3:
                    threeRoll++;
                    break;
                case 4:
                    fourRoll++;
                    break;
                case 5:
                    fiveRoll++;
                    break;
                case 6:
                    sixRoll++;
                    break;
                default:
                    cout << "\n";
                }

            count++;
        }

    onePercent = (int)((oneRoll*100.0) /numOfTimes);
    twoPercent = (int)((twoRoll*100.0) / numOfTimes);

    cout << " # Rolled          # Times % Times" << endl;
    cout << "---------  --------    --------" << endl;
    cout << "1      " << oneRoll << "       " <<double (onePercent)  << endl;
    cout << "2      " << twoRoll << "       " << "" << endl;
    cout << "3      " << threeRoll << "     " << ""<< endl;
    cout << "4      " << fourRoll << "      " <<""  << endl;
    cout << "5      " << fiveRoll << "      " <<""  << endl;
    cout << "6      " << sixRoll << "       " <<"" << endl;

I need it to print out the the one percent as a double. So I converted it as an int then to a double so it only prints two zeros like this (14.00) but its not converting at all its only printing 14

Body:
The main problem, just as Barmar mentioned in his comment, is that although you want the value to be printed to 2 decimal points, you round off the number in onePercent when you do:

onePercent = (int)((oneRoll*100.0) /numOfTimes); // Casting to "int" rounds off the number

Also, the declared data type for onePercent is int from the start:

int onePercent, twoPercent, threePercent, fourPercent, fivePercent, sixPercent; // onePercent is an "int" here

So you don't need a typecast of int, because you're casting an int to an int.

Therefore, even if you print onePercentwith 2 decimal-point precision, you will always get .00 as a result.

I would recommend taking off the (int) cast from that expression itself, and changing the initial data type of onePercent to type double. If you do not want to change the data types for the other variables declared alongside onePercent, then declare onePercent as a double on another line. That way, the precision of the value after the calculation will be maintained, and you will be able to output it to 2 decimal places.

As an aside, to specify the number of decimal places to output, the setprecision() function can be used:

cout << setprecision(2) << ... << endl; // The value passed to "setprecision" is up to you.


问:
How to modify a link?
I need to modify this link to go to

```<code>channels/params[:channel_id]/messages
</code>```

here is the current link

```<code><%= link_to pluralize(@channel.messages.size, 'message') %>
</code>```

result of rake routes

```<code>{:action=>"index", :controller=>"messages"}  POST   /channels/:channel_id/messages(.:format)
{:action=>"create", :controller=>"messages"}new_channel_message GET    /channels/:channel_id/messages/new(.:format)
{:action=>"new", :controller=>"messages"} edit_channel_message GET    /channels/:channel_id/messages/:id/edit(.:format)
{:action=>"edit", :controller=>"messages"}channel_message GET    /channels/:channel_id/messages/:id(.:format)
{:action=>"show", :controller=>"messages"} PUT    /channels/:channel_id/messages/:id(.:format)
{:action=>"update", :controller=>"messages"} DELETE /channels/:channel_id/messages/:id(.:format)
{:action=>"destroy", :controller=>"messages"} channels GET    /channels(.:format)
{:action=>"index", :controller=>"channels"} POST   /channels(.:format)
{:action=>"create", :controller=>"channels"}  new_channel GET    /channels/new(.:format)
{:action=>"new", :controller=>"channels"} edit_channel GET    /channels/:id/edit(.:format)
{:action=>"edit", :controller=>"channels"}channel GET    /channels/:id(.:format)
{:action=>"show", :controller=>"channels"}PUT    /channels/:id(.:format)
{:action=>"update", :controller=>"channels"} DELETE /channels/:id(.:format)
</code>```

答:
You don't really need to "modify" it, since it most likely never worked anyway :)

Search for the path macro for your route, using:

```<code>rake routes
</code>```

Then you can use the correct macro, which most likely is something like channel_message. You'll reach something like this:

```<code><%= link_to pluralize(@channel.messages.size, 'message'), channel_message_path(@channel) %>
</code>```

Title: How to modify a link?

Body:
I need to modify this link to go to

channels/params[:channel_id]/messages

here is the current link

<%= link_to pluralize(@channel.messages.size, 'message') %>

result of rake routes

{:action=>"index", :controller=>"messages"}  POST   /channels/:channel_id/messages(.:format)
{:action=>"create", :controller=>"messages"}new_channel_message GET    /channels/:channel_id/messages/new(.:format)
{:action=>"new", :controller=>"messages"} edit_channel_message GET    /channels/:channel_id/messages/:id/edit(.:format)
{:action=>"edit", :controller=>"messages"}channel_message GET    /channels/:channel_id/messages/:id(.:format)
{:action=>"show", :controller=>"messages"} PUT    /channels/:channel_id/messages/:id(.:format)
{:action=>"update", :controller=>"messages"} DELETE /channels/:channel_id/messages/:id(.:format)
{:action=>"destroy", :controller=>"messages"} channels GET    /channels(.:format)
{:action=>"index", :controller=>"channels"} POST   /channels(.:format)
{:action=>"create", :controller=>"channels"}  new_channel GET    /channels/new(.:format)
{:action=>"new", :controller=>"channels"} edit_channel GET    /channels/:id/edit(.:format)
{:action=>"edit", :controller=>"channels"}channel GET    /channels/:id(.:format)
{:action=>"show", :controller=>"channels"}PUT    /channels/:id(.:format)
{:action=>"update", :controller=>"channels"} DELETE /channels/:id(.:format)

Body:
You don't really need to "modify" it, since it most likely never worked anyway :)

Search for the path macro for your route, using:

rake routes

Then you can use the correct macro, which most likely is something like channel_message. You'll reach something like this:

<%= link_to pluralize(@channel.messages.size, 'message'), channel_message_path(@channel) %>


问:
Transposing individual elements of a Python Dictionary
I have a python super dictionary that is made of individual dictionaries and currently looks like this:

```<code>raw_data1 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
raw_data2 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
raw_data3 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
top_dictionary = {
'raw_data1': raw_data1,
'raw_data2': raw_data2,
'raw_data3': raw_data3
}
print top_dictionary
</code>```

I would like to transpose the individual dictionaries in my top_dictionary  in a way such that all the value fields get transposed to the Value Column and the date is appended as a row item. The column name of the value field becomes a row for the Description column.

As an example the value in top_dictionary with the key: 'raw_data1' will then look like:

```<code>raw_data1 = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13','2017-03-14','2017-03-14','2017-03-14','2017-03-15','2017-03-15','2017-03-15'],'Value':[35.6,-7.8,24,56.7,56,-31,41,56,53,41,-3.4,5],'Desc':['SP','1M','3M','SP','1M','3M','SP','1M','3M','SP','1M','3M']}
</code>```

I know how to do this for each individual dictionary by using the pandas melt function but how do I do this for my top_dictionary such that all elements inside it get transposed accordingly?

答:
Check the "Series_Date" output... if you don't want it sorted, remove the sorted method in the function.  I only sorted it to match your specified output.    </p>

```<code>def make_dict(dict_in, val_cols):
    d_out = {}
    d_out['Value'] = pd.DataFrame(dict_in)[val_cols].values.flatten()
    d_out['Series_Date'] = sorted(dict_in['Series_Date'] * len(val_cols))
    d_out['Desc'] = val_cols * len(val_cols)
    return d_out

new_dict = {k: make_dict(v, ['SP','1M', '3M']) for k, v in top_dictionary.items()}
</code>```

Body:
I have a python super dictionary that is made of individual dictionaries and currently looks like this:

raw_data1 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
raw_data2 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
raw_data3 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
top_dictionary = {
'raw_data1': raw_data1,
'raw_data2': raw_data2,
'raw_data3': raw_data3
}
print top_dictionary

I would like to transpose the individual dictionaries in my top_dictionary  in a way such that all the value fields get transposed to the Value Column and the date is appended as a row item. The column name of the value field becomes a row for the Description column.

As an example the value in top_dictionary with the key: 'raw_data1' will then look like:

raw_data1 = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13','2017-03-14','2017-03-14','2017-03-14','2017-03-15','2017-03-15','2017-03-15'],'Value':[35.6,-7.8,24,56.7,56,-31,41,56,53,41,-3.4,5],'Desc':['SP','1M','3M','SP','1M','3M','SP','1M','3M','SP','1M','3M']}

I know how to do this for each individual dictionary by using the pandas melt function but how do I do this for my top_dictionary such that all elements inside it get transposed accordingly?

Body:
Check the "Series_Date" output... if you don't want it sorted, remove the sorted method in the function.  I only sorted it to match your specified output.

def make_dict(dict_in, val_cols):
    d_out = {}
    d_out['Value'] = pd.DataFrame(dict_in)[val_cols].values.flatten()
    d_out['Series_Date'] = sorted(dict_in['Series_Date'] * len(val_cols))
    d_out['Desc'] = val_cols * len(val_cols)
    return d_out

new_dict = {k: make_dict(v, ['SP','1M', '3M']) for k, v in top_dictionary.items()}


问:
Saxon API (saxon9HE) output is not generating proper xml
I am using below code for xsl transform.

```<code>var processor = new Processor();

XsltCompiler xslComp = processor.NewXsltCompiler();
            XsltExecutable xslExec = xslComp.Compile(xslUri);
            XsltTransformer xslTrans = xslExec.Load();
            XdmDestination xdmD = new XdmDestination();
            Serializer serializer = processor.NewSerializer();

            using (FileStream fs = File.Open(xmlPath, FileMode.Open))
            {
                xslTrans.SetInputStream(fs, schemaUri); // set baseUri
                xslTrans.Run(xdmD);
            }

            XdmNode value = null;

            if (xdmD != null)
            {
                value = xdmD.XdmNode;
            }
</code>```

Here is sample input xsl:

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:nf="urn:ietf:params:xml:ns:netconf:base:1.0" >
  <xsl:output method="xml" indent="no"/>

  <xsl:template match="/">
    <xsl:value-of select="concat('<?xml',substring-after(//root/text(),'<?xml'))" disable-output-escaping="yes"
/>
  </xsl:template>
</xsl:stylesheet>
</code>```

Sample input xml:

```<code><root>
<![CDATA[

<?xml version="1.0" encoding="ISO-8859-1"?>
<nf:rpc-reply xmlns:nf="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns="http://www.cisco.com/nxos:1.0:vms">
<nf:data>
  <show>
   <svs>
    <connections>
        <conn-name>qa-gdc1</conn-name>
    </connections>
   </svs>
  </show>
</nf:data>
</nf:rpc-reply>

]]>
</root>
</code>```

Output:

```<code>&lt?xml version="1.0" encoding="ISO-8859-1"?&gt
&ltnf:rpc-reply xmlns:nf="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns="http://www.cisco.com/nxos:1.0:vms"&gt
&ltnf:data&gt
  &ltshow&gt
   &ltsvs&gt
    &ltconnections&gt
        &ltconn-name>qa-gdc1</conn-name&gt
    &lt/connections&gt
   &lt/svs&gt
  &lt/show&gt
&lt/nf:data&gt
&lt/nf:rpc-reply&gt
</code>```

答:
(As I already explained in private email)

disable-output-escaping is an instruction to the serializer. It therefore has no effect if the result tree is not serialized. (You are creating a serializer, but you are not using it as the destination for the transformation.)

Body:
I am using below code for xsl transform.

var processor = new Processor();

XsltCompiler xslComp = processor.NewXsltCompiler();
            XsltExecutable xslExec = xslComp.Compile(xslUri);
            XsltTransformer xslTrans = xslExec.Load();
            XdmDestination xdmD = new XdmDestination();
            Serializer serializer = processor.NewSerializer();

            using (FileStream fs = File.Open(xmlPath, FileMode.Open))
            {
                xslTrans.SetInputStream(fs, schemaUri); // set baseUri
                xslTrans.Run(xdmD);
            }

            XdmNode value = null;

            if (xdmD != null)
            {
                value = xdmD.XdmNode;
            }

Here is sample input xsl:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:nf="urn:ietf:params:xml:ns:netconf:base:1.0" >
  <xsl:output method="xml" indent="no"/>

  <xsl:template match="/">
    <xsl:value-of select="concat('<?xml',substring-after(//root/text(),'<?xml'))" disable-output-escaping="yes"
/>
  </xsl:template>
</xsl:stylesheet>

Sample input xml:

<root>
<![CDATA[

<?xml version="1.0" encoding="ISO-8859-1"?>
<nf:rpc-reply xmlns:nf="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns="http://www.cisco.com/nxos:1.0:vms">
<nf:data>
  <show>
   <svs>
    <connections>
        <conn-name>qa-gdc1</conn-name>
    </connections>
   </svs>
  </show>
</nf:data>
</nf:rpc-reply>

]]>
</root>

Output:

&lt?xml version="1.0" encoding="ISO-8859-1"?&gt
&ltnf:rpc-reply xmlns:nf="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns="http://www.cisco.com/nxos:1.0:vms"&gt
&ltnf:data&gt
  &ltshow&gt
   &ltsvs&gt
    &ltconnections&gt
        &ltconn-name>qa-gdc1</conn-name&gt
    &lt/connections&gt
   &lt/svs&gt
  &lt/show&gt
&lt/nf:data&gt
&lt/nf:rpc-reply&gt


问:
Use function to echo SQL results from external php file
I'm getting weird results when trying to kind of make a "templating engine". Basically, I want to be able to use PHP variables that contain data from an SQL database.

What happens is that everything works properly with the PHP side, what does not is the page that needs to display this information (index.php).

I'm working on a way to get the website's name from the sql database, so I have something like that on my index:

```<code> <?php

 include ('php/data/sitename.php');

 ?>

 <!DOCTYPE html>
  <html>
    <head>
    <title><?php echo $sitename; ?> - Home</title>
      <!--Import Google Icon Font-->
      <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <!--Import materialize.css-->
      <link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>
      <!--Let browser know website is optimized for mobile-->
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>
    <body>
    <div class="container">
        <!-- HEADER: Navbar -->
        <?php $navbar; ?>
        <!-- MAIN: Index Page contents -->
        <?php $page_index ?>
        <!-- FOOTER: Footer -->
        <?php $footer; ?>
        <?php $sitename; ?>
    </div>
      <!--Import jQuery before materialize.js-->
      <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
      <script type="text/javascript" src="js/materialize.min.js"></script>
    </body>
  </html>
</code>```

This variable comes from a file (that has been included) called sitename.php, with the following code:

```<code><?php
include ('../db.php');

$sql = "SELECT id, sitename FROM GeneralData";
$getname = mysqli_query($conn, $sql);

if ($getname->num_rows > 0) {
    while($row = $getname->fetch_assoc()) {
        $sitename = $row['sitename'];
        echo $sitename;
    }
}

?>
</code>```

Yes, I used echo $sitename;, I know it wont echo the actual data, but I did it to test some things, and here are the results:

Including the file sitename.php to index.php will do nothing, it would be like if it did not exist. However, if I write "echo "123";" on it, it will echo 123 on index. What does not work is what I need.

If I go to sitename.php directly, it will simply output the correct SQL value I requested because I told it to echo (as I stated before). But, it wont work in index, it will simply not work.

Also, I'll leave my project structure here. It might help.

What can I do?
Thanks in advance!

答:
try set GLOBAL for sitename

```<code>GLOBAL $sitename;
</code>```

or

```<code>GLOBALS['sitename'];
$sitename = ...
</code>```

EDIT
try use

```<code>   $path = $_SERVER['DOCUMENT_ROOT'];
   $path .= "/yourpath/yourfile.php";
   include_once($path);
</code>```

Body:
I'm getting weird results when trying to kind of make a "templating engine". Basically, I want to be able to use PHP variables that contain data from an SQL database.

What happens is that everything works properly with the PHP side, what does not is the page that needs to display this information (index.php).

I'm working on a way to get the website's name from the sql database, so I have something like that on my index:

 <?php

 include ('php/data/sitename.php');

 ?>

 <!DOCTYPE html>

    <title><?php echo $sitename; ?> - Home</title>

      <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      <link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>

      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

        <?php $navbar; ?>

        <?php $page_index ?>

        <?php $footer; ?>
        <?php $sitename; ?>

This variable comes from a file (that has been included) called sitename.php, with the following code:

<?php
include ('../db.php');

$sql = "SELECT id, sitename FROM GeneralData";
$getname = mysqli_query($conn, $sql);

if ($getname->num_rows > 0) {
    while($row = $getname->fetch_assoc()) {
        $sitename = $row['sitename'];
        echo $sitename;
    }
}

?>

Yes, I used echo $sitename;, I know it wont echo the actual data, but I did it to test some things, and here are the results:

Including the file sitename.php to index.php will do nothing, it would be like if it did not exist. However, if I write "echo "123";" on it, it will echo 123 on index. What does not work is what I need.

If I go to sitename.php directly, it will simply output the correct SQL value I requested because I told it to echo (as I stated before). But, it wont work in index, it will simply not work.

Also, I'll leave my project structure here. It might help.

What can I do?
Thanks in advance!

Body:
try set GLOBAL for sitename

GLOBAL $sitename;

or

GLOBALS['sitename'];
$sitename = ...

EDIT
try use

   $path = $_SERVER['DOCUMENT_ROOT'];
   $path .= "/yourpath/yourfile.php";
   include_once($path);


问:
Is there any problem to using this code in a Thread ? (Delphi)
i use this code in a thread (through Indy Onexecute event) . is there any problem ?</p>

```<code>function TFrmMain.ShellExecute_AndWait(FileName, Params: string): bool;
var
  exInfo: TShellExecuteInfo;
  Ph: DWORD;
begin
  FillChar(exInfo, SizeOf(exInfo), 0);
  with exInfo do
  begin
    cbSize := SizeOf(exInfo);
    fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_DDEWAIT;
    Wnd := GetActiveWindow();
    exInfo.lpVerb := 'open';
    exInfo.lpParameters := PChar(Params);
    lpFile := PChar(FileName);
    nShow := SW_NORMAL;
  end;
  if ShellExecuteEx(@exInfo) then
    Ph := exInfo.hProcess
  else
  begin
    Result := true;
    exit;
  end;
  while WaitForSingleObject(exInfo.hProcess, 50) <> WAIT_OBJECT_0 do
  begin

  end;
  CloseHandle(Ph);
  Result := true;
end;
</code>```

答:
MSDN has this advice:

Because ShellExecuteEx can delegate execution to Shell extensions (data sources, context menu handlers, verb implementations) that are activated using Component Object Model (COM), COM should be initialized before ShellExecuteEx is called. Some Shell extensions require the COM single-threaded apartment (STA) type. In that case, COM should be initialized as shown here:

```<code>CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE)
</code>```

There are instances where ShellExecuteEx does not use one of these types of Shell extension and those instances would not require COM to be initialized at all. Nonetheless, it is good practice to always initalize COM before using this function.

(In Delphi, you'd of course replace the first parameter with nil and use or for the bitwise operation.)

Raymond Chen recently wrote about the consequences of getting this wrong. The specific example was that the function might fail with the Error_Access_Denied error code.

That's the only potential multithreading issue I see in your code. Below are further things that occurred to me when I read your code, although they have nothing to do with multithreading (and not even much to do with Indy).

You have a peculiar way of waiting for the program to stop running. You repeatedly wait for 50 milliseconds at a time, but if the process isn't finished yet, you do nothing but wait again. Describe your intention more accurately by specifying Infinite for the timeout.

The function always returns True. If there's no useful return value, then you should just make it a procedure so there's no return value at all. Don't confuse the caller with useless information. If you're going to keep it as a function, then use the Delphi native type Boolean instead of the Windows compatibility type Bool for the return type.

I'm a little wary about the idea of a server executing user-interactive programs upon receipt of network messages.

Notice when MSDN says you might not get a process handle. There are cases when ShellExecuteEx can service your request without creating a new process, so you'll have nothing to wait on.

The user might end up using the program awhile, and your server will be stuck waiting all that time. I wonder whether it really needs to wait at all. Is the client going to be waiting for a response from the server, too?

Body:
i use this code in a thread (through Indy Onexecute event) . is there any problem ?

function TFrmMain.ShellExecute_AndWait(FileName, Params: string): bool;
var
  exInfo: TShellExecuteInfo;
  Ph: DWORD;
begin
  FillChar(exInfo, SizeOf(exInfo), 0);
  with exInfo do
  begin
    cbSize := SizeOf(exInfo);
    fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_DDEWAIT;
    Wnd := GetActiveWindow();
    exInfo.lpVerb := 'open';
    exInfo.lpParameters := PChar(Params);
    lpFile := PChar(FileName);
    nShow := SW_NORMAL;
  end;
  if ShellExecuteEx(@exInfo) then
    Ph := exInfo.hProcess
  else
  begin
    Result := true;
    exit;
  end;
  while WaitForSingleObject(exInfo.hProcess, 50) <> WAIT_OBJECT_0 do
  begin

  end;
  CloseHandle(Ph);
  Result := true;
end;

Body:
MSDN has this advice:

Because ShellExecuteEx can delegate execution to Shell extensions (data sources, context menu handlers, verb implementations) that are activated using Component Object Model (COM), COM should be initialized before ShellExecuteEx is called. Some Shell extensions require the COM single-threaded apartment (STA) type. In that case, COM should be initialized as shown here:

CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE)

There are instances where ShellExecuteEx does not use one of these types of Shell extension and those instances would not require COM to be initialized at all. Nonetheless, it is good practice to always initalize COM before using this function.

(In Delphi, you'd of course replace the first parameter with nil and use or for the bitwise operation.)

Raymond Chen recently wrote about the consequences of getting this wrong. The specific example was that the function might fail with the Error_Access_Denied error code.

That's the only potential multithreading issue I see in your code. Below are further things that occurred to me when I read your code, although they have nothing to do with multithreading (and not even much to do with Indy).

You have a peculiar way of waiting for the program to stop running. You repeatedly wait for 50 milliseconds at a time, but if the process isn't finished yet, you do nothing but wait again. Describe your intention more accurately by specifying Infinite for the timeout.

The function always returns True. If there's no useful return value, then you should just make it a procedure so there's no return value at all. Don't confuse the caller with useless information. If you're going to keep it as a function, then use the Delphi native type Boolean instead of the Windows compatibility type Bool for the return type.

I'm a little wary about the idea of a server executing user-interactive programs upon receipt of network messages.

Notice when MSDN says you might not get a process handle. There are cases when ShellExecuteEx can service your request without creating a new process, so you'll have nothing to wait on.

The user might end up using the program awhile, and your server will be stuck waiting all that time. I wonder whether it really needs to wait at all. Is the client going to be waiting for a response from the server, too?


问:
Visual Studio 2013: auto-refresh solution explorer in "show all files" mode
Is there any way or some unobvious workaround to make the Solution Explorer refresh automatically (in Show All Files mode) when there are changes to the project directory tree? Currently if I rebuild a project with different output settings (which would add some files and remove some others), no changes would get reflected in Solution Explorer until I manually click refresh button. Doesn't seem too convenient for a tool aimed at programming, i.e. automating repetitive tasks...

Update

A picture is worth a thousand words:

My relevant options @ Tools > Options > Environment > Documents:

Let's assume that Release directory is empty and Show All Files mode enabled

Now, I build my Release config... Build succeeds, but no changes are visible in Solution Explorer:

Only after I hit refresh button manually can I see the results of build process:

So I'm basically asking if there are ways to make Solution Explorer update automatically when changes occur, not to make externally modified files auto-reload in VS editors.

答: That was impossible in VS 2013 and 2015, but with 2017 Microsoft did the right thing and revamped the Solution Explorer a bit - now there is clear and logical separation between solution (virtual) and folder (physical) views, and changes to the filesystem are now tracked and displayed automatically.</p>


问:
How to count checked checkbox with Javascript?
I would like to count the checkboxes that are checked and display the count in the Div.

Here is my HTML :

```<code><form name="liste_figurine" method="post">

<input type="checkbox" id="radio-1" class="z" name="chck1[]" onclick="updateCount()" />
<input type="checkbox" id="radio-2" class="z" name="chck2[]" onclick="updateCount()" />

</form>

<div id="y"></div>
</code>```

Here is my JS :

```<code>function updateCount {
    var x = $(".z:checked").length;
    document.getElementById("y").innerHTML = x;
};
</code>```

Here is an exemple : https://jsfiddle.net/r3todbs6/3/

Sorry, I'm not really used to JS... What is wrong with my code ?

Finally, it's working but I have one last issue : the onclick must contain 2 functions and I don't manage to make them working together.

Now this function works, alone : onclick="updateCount()"

This other function works also, alone : onclick="document.getElementById(\'radio-'.$ligne['id'].'-2\').checked = false"

But these two functions doesn't work, together :
onclick="updateCount(); fx2(document.getElementById(\'radio-'.$ligne['id'].'-1\').checked = false);"

What is wrong with the third proposition ? Is it a syntax error ?

答:
Use length

```<code>function updateCount(){
    var x = $("input:checked").length;
    $("#y").html(x);
};
</code>```

Body:
I would like to count the checkboxes that are checked and display the count in the Div.

Here is my HTML :

<form name="liste_figurine" method="post">

<input type="checkbox" id="radio-1" class="z" name="chck1[]" onclick="updateCount()" />
<input type="checkbox" id="radio-2" class="z" name="chck2[]" onclick="updateCount()" />

</form>

Here is my JS :

function updateCount {
    var x = $(".z:checked").length;
    document.getElementById("y").innerHTML = x;
};

Here is an exemple : https://jsfiddle.net/r3todbs6/3/

Sorry, I'm not really used to JS... What is wrong with my code ?

Finally, it's working but I have one last issue : the onclick must contain 2 functions and I don't manage to make them working together.

Now this function works, alone : onclick="updateCount()"

This other function works also, alone : onclick="document.getElementById(\'radio-'.$ligne['id'].'-2\').checked = false"

But these two functions doesn't work, together :
onclick="updateCount(); fx2(document.getElementById(\'radio-'.$ligne['id'].'-1\').checked = false);"

What is wrong with the third proposition ? Is it a syntax error ?

Body:
Use length

function updateCount(){
    var x = $("input:checked").length;
    $("#y").html(x);
};


问:
Flashing listBox in c#
i want to know if it's possible to flash listbox.
I'm creating a chat application (client-server) with c# and winform and i want to make my listbox flash when i receive a new message.
It's possible ? thank you</p>

答:
Hi "Flash" mean Clear?

How to: Add and Clear Items in a ListBox Control

https://msdn.microsoft.com/en-us/library/ms228375(v=vs.90).aspx

```<code>private void button1_Click(object sender, System.EventArgs e)
{
   listBox1.Items.Add("Sally");
   listBox1.Items.Add("Craig");
}

private void button2_Click(object sender, System.EventArgs e)
{
   listBox1.Items.Clear();
}
</code>```

Title: Flashing listBox in c#

Body:
Hi "Flash" mean Clear?

How to: Add and Clear Items in a ListBox Control

https://msdn.microsoft.com/en-us/library/ms228375(v=vs.90).aspx

private void button1_Click(object sender, System.EventArgs e)
{
   listBox1.Items.Add("Sally");
   listBox1.Items.Add("Craig");
}

private void button2_Click(object sender, System.EventArgs e)
{
   listBox1.Items.Clear();
}


问:
Connecting to GMail programmatically using C or Visual Basic
I'm trying to make a small program (in either C or Visual Basic) to simply connect to a gmail email account. Then a simple if statement which will be if new mail received, label.text = "new mail" etc.

I have spent hours and hours searching and I still can't figure this out without paying for scripts.

Any help on this would be gratefully appreciated :) :)

Cheers

答:
Google provides a read-only data feed to view the contents of a Gmail inbox:

http://code.google.com/apis/gmail/docs/inbox_feed.html

You should be able to use that feed to get the info you need for your application.


问:
SameSite cookie in Java application
Do you know any Java cookie implementation which allows to set a custom flag for cookie, like SameSite=strict? It seems that javax.servlet.http.Cookie has a strictly limited set of flags which can be added.

答:
I am not a JEE expert, but I think that because that cookie property is a somewhat new invention, you cannot expect it to be present in Java EE 7 interfaces or implementations. The Cookie class is missing a setter for generic properties, as it seems. But instead of adding the cookie to your HttpServletResponse via

response.addCookie(myCookie)
```
<p>you can simply set the corresponding HTTP header field via</p>
<pre class="lang-java prettyprint-override"><code>response.setHeader("Set-Cookie", "key=value; HttpOnly; SameSite=strict")
</code>```

Update: Thanks to @mwyrzyk for pointing out that setHeader() overwrites all existing headers of the same name. So if you happen have other Set-Cookie headers in your response already, of course you would use addHeader() with the same parameters instead.

Update: Starting with Jakarta Servlet API, generic getAttribute() and setAttribute() methods have been added to the Cookie class.

Title: SameSite cookie in Java application

Body:
I am not a JEE expert, but I think that because that cookie property is a somewhat new invention, you cannot expect it to be present in Java EE 7 interfaces or implementations. The Cookie class is missing a setter for generic properties, as it seems. But instead of adding the cookie to your HttpServletResponse via

response.addCookie(myCookie)

you can simply set the corresponding HTTP header field via

response.setHeader("Set-Cookie", "key=value; HttpOnly; SameSite=strict")

Update: Thanks to @mwyrzyk for pointing out that setHeader() overwrites all existing headers of the same name. So if you happen have other Set-Cookie headers in your response already, of course you would use addHeader() with the same parameters instead.

Update: Starting with Jakarta Servlet API, generic getAttribute() and setAttribute() methods have been added to the Cookie class.


问:
S3 event trigger to different SNS topics
I have an event in an S3 bucket that is triggered on every object creation. Now, I need to create another event that will only be triggered for specified subdirectory.

When I attempt to do that, I get an error

```<code>Configuration is ambiguously defined.
Cannot have overlapping suffixes in two rules if the prefixes are overlapping for the same event type.
</code>```

Since the first event is a catch-all, there is no prefix or suffix that I can specify to avoid this situation.

Do I have any options for creation of different events to this bucket?

答:
Looking at this forum discussion, what you are asking is not supported.

Here's an alternative solution that could be used. For your use case, 2 Lambda functions would have to be subscribed to the SNS topic. One of them will work on the specified subdirectory, the other will act as your catch all.

Body:
I have an event in an S3 bucket that is triggered on every object creation. Now, I need to create another event that will only be triggered for specified subdirectory.

When I attempt to do that, I get an error

Configuration is ambiguously defined.
Cannot have overlapping suffixes in two rules if the prefixes are overlapping for the same event type.

Since the first event is a catch-all, there is no prefix or suffix that I can specify to avoid this situation.

Do I have any options for creation of different events to this bucket?


问:
NSPredicate filtering
I have the following json object is stored as self.pElements. I have a search bar to be used to filter items based on the name.

```<code>[
 {"id":"1","name":"Baked Chicken","category":"1","price":"5.49"},
 {"id":"2","name":"Beef Kabob","category":"2","price":"5.49"},
 {"id":"3","name":"Beef Gyro","category":"1","price":"5.49"},
 {"id":"4","name":"Lamb Gyro","category":"4","price":"5.49"}
]
</code>```

I try to filter by name as follows, but it always returns me null. even I type just Beef, nothing has been returned

```<code>pTempElements =[[NSMutableArray alloc] initWithArray:[self.pElements filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name = %@", self.searchBar.text]]];
</code>```

答:
If you want to filter for strings that contain the search string, use contains[cd]:

```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", searchText];
</code>```

For list of the sorts of string comparisons one can do, see Predicate Format String Syntax: String Comparisons in the Predicate Programming Guide.

Title: NSPredicate filtering

Body:
I have the following json object is stored as self.pElements. I have a search bar to be used to filter items based on the name.

[
 {"id":"1","name":"Baked Chicken","category":"1","price":"5.49"},
 {"id":"2","name":"Beef Kabob","category":"2","price":"5.49"},
 {"id":"3","name":"Beef Gyro","category":"1","price":"5.49"},
 {"id":"4","name":"Lamb Gyro","category":"4","price":"5.49"}
]

I try to filter by name as follows, but it always returns me null. even I type just Beef, nothing has been returned

pTempElements =[[NSMutableArray alloc] initWithArray:[self.pElements filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name = %@", self.searchBar.text]]];

Body:
If you want to filter for strings that contain the search string, use contains[cd]:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", searchText];

For list of the sorts of string comparisons one can do, see Predicate Format String Syntax: String Comparisons in the Predicate Programming Guide.


问:
how to call IBM Watson services from javascript
I am implementing a virtual agent using IBM Watson services. My application is developed using Jquery, Angular JS & Java.Currently i am calling the watson services from middle layer that is java. But i want to avoid that and call directly from javascript.When i call from javascript using XML Http request, i am getting CORS error.How to solve this?

Below is my code:

```<code>var username = "uid";
var password = "pwd";
var xhr = new XMLHttpRequest();
xhr.open('GET', 'url');
//xhr.withCredentials = true;
xhr.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type, application/json, Authorization");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader('Access-Control-Allow-Credentials', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
xhr.setRequestHeader('Content-Type', undefined);
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + " " + password));
xhr.send('"query":"hi"');
</code>```

答:
The IBM Watson services don’t yet support getting cross-origin requests from browser-based apps.

See the answer at Can't access IBM Watson API locally due to CORS on a Rails/AJAX App:

We don't support CORS, we are working on it but in your case Visual Recognition is not supported yet.

That implies some of the services support CORS but I guess the one you’ve tried isn’t one of them.

So other than what you say you’re doing now (accessing the services from your server-side Java layer instead), your only option to get at the services from JavaScript code running in a web app is, either set up your own server-side proxy with https://github.com/Rob--W/cors-anywhere or such, or send your requests through an open CORS proxy like https://cors-anywhere.herokuapp.com/ (though it’s unlikely you’ll want to do that in the case where your requests include any kind of authentication token that you don’t want to expose to the operator of a third-party proxy service).

The way such proxies works is, instead of using https://gateway.watsonplatform.net/some/api as the request URL that specify in your client-side JavaScript code, you instead specify the proxy URL, like https://cors-anywhere.herokuapp.com/https://gateway.watsonplatform.net/some/api, and the proxy sends the actual request to the service, gets back the response, and adds the needed Access-Control-Allow-Origin response header and other headers to it and passes it on.

So that response with the CORS headers included is what the browser sees.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has more details about how CORS works, but the main thing to know is that the browser is the CORS enforcement point. So in the case with the Watson services, the browser will actually get the response from the Watson API—you will be able to use devtools in the browser to see the response—but the browser will expose the response to your client-side JavaScript code only if the response includes the Access-Control-Allow-Origin response header to indicate the server that sent the response has opted in to receiving cross-origin requests from client-side JavaScript running in web apps.

So that’s why, regardless, all the xhr.setRequestHeader("Access-Control-Allow- lines in your XHR code snippet above need to just be removed—because Access-Control-Allow-* headers are response headers, not request headers; sending them in a request to a server has no effect on CORS, because as noted above, the browser’s the CORS enforcement point, not the server.

So it’s not the case that the server receives some request from a browser and says, OK I see this request has the right headers, so I’ll allow it. Instead the server allows all requests from browsers, just as it allows all requests from non-browser tools like your Java code or curl or Postman or whatever (as long as they are authenticated of course) and sends a response.

The difference is, when a non-browser-based app receives a response, it doesn’t refuse to let you access the response if it lacks the Access-Control-Allow-Origin header. But the browser does refuse to let your client-side JavaScript web-app code access the response if it lacks that.

Body:
I am implementing a virtual agent using IBM Watson services. My application is developed using Jquery, Angular JS & Java.Currently i am calling the watson services from middle layer that is java. But i want to avoid that and call directly from javascript.When i call from javascript using XML Http request, i am getting CORS error.How to solve this?

Below is my code:

var username = "uid";
var password = "pwd";
var xhr = new XMLHttpRequest();
xhr.open('GET', 'url');
//xhr.withCredentials = true;
xhr.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type, application/json, Authorization");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader('Access-Control-Allow-Credentials', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
xhr.setRequestHeader('Content-Type', undefined);
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + " " + password));
xhr.send('"query":"hi"');


问:
Selectable Variable/goto statement
so i am making a basic dice game for school - i am very new to this. basically what i want is to be able to have upto 3 dice being rolled but would like each to run a different code (to be rolling 1/2/3 dice)
i had something like this but found out there is no "goto" statement

```<code>Dice = input("Please select number of dice you would like to use (1-3)") #20
    if Dice == "1":
        print("You have selected 1 dice")

elif Dice == "2":
    print("You have selected 2 dice")

elif Dice == "3":
    print("You have selected 3 dice")

elif Dice == "":
    print ("\n" "Please Select number of dice you wish to use (Select a number between 1 and 3)")
</code>```

what should i either do or how would i make this go to a specific place in the code to run what i have next.

答:
In this case you will want to use a while loop. They look something like this:

```<code>while (condition):
    #do stuff
</code>```

Assuming that the user will only enter a valid integer then your code could look something like this:

```<code>while True:
    dice = int(input("Enter the number of dice you would like to roll. (between 1 and 3) -> "))
    if (dice >= 1 and dice <= 3):
        #more checks here if you like
        #And make sure you 'break' or this will be an infinite loop
</code>```

Sorry if my Python syntax is a bit off, haven't done it for a while. Hope this helps, if you have any questions please feel free to ask!

Happy coding!

Title: Selectable Variable/goto statement

Body:
so i am making a basic dice game for school - i am very new to this. basically what i want is to be able to have upto 3 dice being rolled but would like each to run a different code (to be rolling 1/2/3 dice)
i had something like this but found out there is no "goto" statement

Dice = input("Please select number of dice you would like to use (1-3)") #20
    if Dice == "1":
        print("You have selected 1 dice")

elif Dice == "2":
    print("You have selected 2 dice")

elif Dice == "3":
    print("You have selected 3 dice")

elif Dice == "":
    print ("\n" "Please Select number of dice you wish to use (Select a number between 1 and 3)")

what should i either do or how would i make this go to a specific place in the code to run what i have next.

Body:
In this case you will want to use a while loop. They look something like this:

while (condition):
    #do stuff

Assuming that the user will only enter a valid integer then your code could look something like this:

while True:
    dice = int(input("Enter the number of dice you would like to roll. (between 1 and 3) -> "))
    if (dice >= 1 and dice <= 3):
        #more checks here if you like
        #And make sure you 'break' or this will be an infinite loop

Sorry if my Python syntax is a bit off, haven't done it for a while. Hope this helps, if you have any questions please feel free to ask!

Happy coding!


问:
Is it possible to Turn page programmatically in UIPageViewController?
Is it possible to turn page programmatically in UIPageViewController?

答:
I could totally be missing something here, but this solution seems a lot simpler than many others proposed.</p>

```<code>extension UIPageViewController {
    func goToNextPage(animated: Bool = true, completion: ((Bool) -> Void)? = nil) {
        if let currentViewController = viewControllers?[0] {
            if let nextPage = dataSource?.pageViewController(self, viewControllerAfter: currentViewController) {
                setViewControllers([nextPage], direction: .forward, animated: animated, completion: completion)
            }
        }
    }
}
</code>```

Body:
I could totally be missing something here, but this solution seems a lot simpler than many others proposed.

extension UIPageViewController {
    func goToNextPage(animated: Bool = true, completion: ((Bool) -> Void)? = nil) {
        if let currentViewController = viewControllers?[0] {
            if let nextPage = dataSource?.pageViewController(self, viewControllerAfter: currentViewController) {
                setViewControllers([nextPage], direction: .forward, animated: animated, completion: completion)
            }
        }
    }
}


问:
How do perform a "customized" running total in SQL Server?
I have temp table that I've populated with a running total. I used SQL Server windowing functions. The data in my temp table is in the following format:

```<code>|Day  | Sku  Nbr | CMQTY  |
| 1   |  f45     |   0    |
| 2   |  f45     |   2    |
| 3   |  f45     |   0    |
| 4   |  f45     |   7    |
| 5   |  f45     |   0    |
| 6   |  f45     |   0    |
| 7   |  f45     |   0    |
| 8   |  f45     |   13   |
| 9   |  f45     |  15    |
| 10  |  f45     |  21    |
</code>```

I would like to manipulate the data so that it displays like this:

```<code>|Day| Sku Nbr | CMQTY |
| 1 |  f45    | 0     |
| 2 |  f45    | 2     |
| 3 |  f45    | 2     |
| 4 |  f45    | 7     |
| 5   |  f45  |   7   |
| 6   |  f45  |   7   |
| 7   |  f45  |   7   |
| 8   |  f45  |   13  |
| 9   |  f45  |  15   |
| 10  |  f45  |  21   |
</code>```

I've tried using a lag function but there are issues when I have multiple days, in a row, with a 0 CMQTY. I've also tried using CASE WHEN logic but am failing.

答:
For fun, another approach. First for some sample data:

```<code>IF OBJECT_ID('tempdb..#t1') IS NOT NULL DROP TABLE #t1;

CREATE TABLE #t1
(
  [day]     int        NOT NULL,
  [Sku Nbr] varchar(5) NOT NULL,
  CMQTY     int        NOT NULL,
  CONSTRAINT pk_t1 PRIMARY KEY CLUSTERED([day] ASC)
);

INSERT #t1 VALUES
(1 , 'f45', 0),
(2 , 'f45', 2),
(3 , 'f45', 0),
(4 , 'f45', 7),
(5 , 'f45', 0),
(6 , 'f45', 0),
(7 , 'f45', 0),
(8 , 'f45', 13),
(9 , 'f45', 15),
(10, 'f45', 21);
</code>```

And the solution:

```<code>DECLARE @RunningTotal int = 0;

UPDATE #t1
SET @RunningTotal = CMQTY = IIF(CMQTY = 0, @RunningTotal, CMQTY)
FROM #t1 WITH (TABLOCKX)
OPTION (MAXDOP 1);
</code>```

Results:

```<code>day  Sku Nbr CMQTY
---- ------- ------
1    f45     0
2    f45     2
3    f45     2
4    f45     7
5    f45     7
6    f45     7
7    f45     7
8    f45     13
9    f45     15
10   f45     21
</code>```

This approach is referred to the local updateable variable or Quirky Update. You can read more about it here: http://www.sqlservercentral.com/articles/T-SQL/68467/

Body:
I have temp table that I've populated with a running total. I used SQL Server windowing functions. The data in my temp table is in the following format:

|Day  | Sku  Nbr | CMQTY  |
| 1   |  f45     |   0    |
| 2   |  f45     |   2    |
| 3   |  f45     |   0    |
| 4   |  f45     |   7    |
| 5   |  f45     |   0    |
| 6   |  f45     |   0    |
| 7   |  f45     |   0    |
| 8   |  f45     |   13   |
| 9   |  f45     |  15    |
| 10  |  f45     |  21    |

I would like to manipulate the data so that it displays like this:

|Day| Sku Nbr | CMQTY |
| 1 |  f45    | 0     |
| 2 |  f45    | 2     |
| 3 |  f45    | 2     |
| 4 |  f45    | 7     |
| 5   |  f45  |   7   |
| 6   |  f45  |   7   |
| 7   |  f45  |   7   |
| 8   |  f45  |   13  |
| 9   |  f45  |  15   |
| 10  |  f45  |  21   |

I've tried using a lag function but there are issues when I have multiple days, in a row, with a 0 CMQTY. I've also tried using CASE WHEN logic but am failing.

Body:
For fun, another approach. First for some sample data:

IF OBJECT_ID('tempdb..#t1') IS NOT NULL DROP TABLE #t1;

CREATE TABLE #t1
(
  [day]     int        NOT NULL,
  [Sku Nbr] varchar(5) NOT NULL,
  CMQTY     int        NOT NULL,
  CONSTRAINT pk_t1 PRIMARY KEY CLUSTERED([day] ASC)
);

INSERT #t1 VALUES
(1 , 'f45', 0),
(2 , 'f45', 2),
(3 , 'f45', 0),
(4 , 'f45', 7),
(5 , 'f45', 0),
(6 , 'f45', 0),
(7 , 'f45', 0),
(8 , 'f45', 13),
(9 , 'f45', 15),
(10, 'f45', 21);

And the solution:

DECLARE @RunningTotal int = 0;

UPDATE #t1
SET @RunningTotal = CMQTY = IIF(CMQTY = 0, @RunningTotal, CMQTY)
FROM #t1 WITH (TABLOCKX)
OPTION (MAXDOP 1);

Results:

day  Sku Nbr CMQTY
---- ------- ------
1    f45     0
2    f45     2
3    f45     2
4    f45     7
5    f45     7
6    f45     7
7    f45     7
8    f45     13
9    f45     15
10   f45     21

This approach is referred to the local updateable variable or Quirky Update. You can read more about it here: http://www.sqlservercentral.com/articles/T-SQL/68467/


问:
Replace slashes with dots in javascript regex
I have a date and I want to replace all the slashes with dots. This is what I have but it's not working:

```<code>var TheDate = "3 / 29 / 2017";
TheDate = TheDate.replace(/'/'/g,'.');
alert(TheDate);
</code>```

What's not right? There's a jsFiddle here to test.

答: Try this TheDate.replace(/\//g, '.')

Body:
I have a date and I want to replace all the slashes with dots. This is what I have but it's not working:

var TheDate = "3 / 29 / 2017";
TheDate = TheDate.replace(/'/'/g,'.');
alert(TheDate);

What's not right? There's a jsFiddle here to test.

Body: Try this TheDate.replace(/\//g, '.')