问:
Calculate percentage in SQL
I'm trying to create table (columns) using another table(s), having trouble in the getting the desired columns. Please guide.

Table Names: Transactions, Customer, Prod_cat_info

```<code>SELECT DISTINCT T.cust_id,
                c.gender,
                C.city_code,
                Datediff(mm, c.dob, Getdate())             AS AGE_IN_MONTHS,
                (SELECT Count(transaction_id)
                 FROM   transactions
                 GROUP  BY tran_date)                      AS
                basket_count_per_day,
                (SELECT Sum(total_amt)
                 FROM   transactions)                      AS Tot_sal_amt,
                (SELECT Sum(qty)
                 FROM   transactions)                      AS tot_sal_qnty,
                (SELECT Count(DISTINCT prod_cat)
                 FROM   dbo.prod_cat_info)                 AS Unq_cat_cnt,
                (SELECT DISTINCT prod_subcat
                 FROM   dbo.prod_cat_info)                 AS Unq_Scat_cnt,
                (SELECT DISTINCT store_type
                 FROM   dbo.transactions)                  AS Unq_chnl_cnt,
                (SELECT Max(tran_date)
                 FROM   dbo.transactions)                  AS
                Last_Transaction_date,
                (SELECT Avg(qty) / Count(tran_date)
                 from transactions)                        AS
                                                           Avg_basket_qty,
                (SELECT Avg(total_amt) / Count(tran_date)
                 from transactions)
                                                         AS Avg_basket_val
INTO   customer_360
FROM   dbo.customer AS c
       INNER JOIN dbo.transactions AS t
               ON t.cust_id = c.customer_id
       INNER JOIN dbo.prod_cat_info AS pci
               ON pci.prod_cat_code = t.prod_cat_code
</code>```

Error Message:

Msg 8120, Level 16, State 1, Line 1

  Column 'dbo.Transactions.cust_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

答:
GROUP BY produces rows that are UNIQUE for the combination of values held in the columns you specify under that clause. Your overall query should look more like this, where the "non-aggregating columns" are listed in the GROUP BY clause

```<code>SELECT
      T.cust_id    --<< this is a "non-aggregating" column
    , c.gender     --<< this is a "non-aggregating" column
    , C.city_code  --<< this is a "non-aggregating" column
    , DATEDIFF(mm, c.dob, GETDATE())    AS AGE_IN_MONTHS --<< this is a "non-aggregating" column

    , SUM(total_amt)                    AS Tot_sal_amt
    , SUM(qty)                          AS tot_sal_qnty
    , COUNT(DISTINCT store_type)        AS Unq_chnl_cnt
    , MAX(tran_date)                    AS Last_Transaction_date
    , AVG(qty) / COUNT(tran_date)       AS Avg_basket_qty
    , AVG(total_amt) / COUNT(tran_date) AS Avg_basket_val

--INTO customer_360
FROM dbo.customer AS c
INNER JOIN dbo.transactions AS t ON t.cust_id = c.customer_id
GROUP BY
      T.cust_id      --<< list each non-aggregating column here
    , c.gender       --<< list each non-aggregating column here
    , C.city_code    --<< list each non-aggregating column here
    , DATEDIFF(mm, c.dob, GETDATE())  --<< list each non-aggregating column here
</code>```

Note please that "select distinct" is utterly, totally, completely redundant if you are using GROUP BY (correctly) in the same select query. Also "select distinct" does less than GROUP BY can do for you (e.g. SUM/MIN/MAX/AVG values).

Further notes:

AVG(qty) / COUNT(tran_date) will produce an integer result, yo may want to do this instead AVG(qty) / (COUNT(tran_date)*1.0)

This join was removed INNER JOIN dbo.prod_cat_info AS pci ON pci.prod_cat_code = t.prod_cat_code as it is MIGHT multiply results. Compare the query above to another where this join is included. If the aggregations are affected then you will need a subquery against this table and join that instead. Due to this the following columns are missing too:

```<code>            (SELECT Count(DISTINCT prod_cat)
             FROM   dbo.prod_cat_info)                 AS Unq_cat_cnt,
            (SELECT DISTINCT prod_subcat
             FROM   dbo.prod_cat_info)                 AS Unq_Scat_cnt,
</code>```

These was also been removed as I wasn't certain what you intended with it:

```<code>            (SELECT Count(transaction_id)
             FROM   transactions
             GROUP  BY tran_date)  AS  basket_count_per_day,
</code>```

A subquery such as this isn't permitted to return multiple values; which this will do. So it would cause an error and you need to decide how to incorporate "daily averages" into a table with one row per customer.

Title: Calculate percentage in SQL

Body:
I'm trying to create table (columns) using another table(s), having trouble in the getting the desired columns. Please guide.

Table Names: Transactions, Customer, Prod_cat_info

SELECT DISTINCT T.cust_id,
                c.gender,
                C.city_code,
                Datediff(mm, c.dob, Getdate())             AS AGE_IN_MONTHS,
                (SELECT Count(transaction_id)
                 FROM   transactions
                 GROUP  BY tran_date)                      AS
                basket_count_per_day,
                (SELECT Sum(total_amt)
                 FROM   transactions)                      AS Tot_sal_amt,
                (SELECT Sum(qty)
                 FROM   transactions)                      AS tot_sal_qnty,
                (SELECT Count(DISTINCT prod_cat)
                 FROM   dbo.prod_cat_info)                 AS Unq_cat_cnt,
                (SELECT DISTINCT prod_subcat
                 FROM   dbo.prod_cat_info)                 AS Unq_Scat_cnt,
                (SELECT DISTINCT store_type
                 FROM   dbo.transactions)                  AS Unq_chnl_cnt,
                (SELECT Max(tran_date)
                 FROM   dbo.transactions)                  AS
                Last_Transaction_date,
                (SELECT Avg(qty) / Count(tran_date)
                 from transactions)                        AS
                                                           Avg_basket_qty,
                (SELECT Avg(total_amt) / Count(tran_date)
                 from transactions)
                                                         AS Avg_basket_val
INTO   customer_360
FROM   dbo.customer AS c
       INNER JOIN dbo.transactions AS t
               ON t.cust_id = c.customer_id
       INNER JOIN dbo.prod_cat_info AS pci
               ON pci.prod_cat_code = t.prod_cat_code

Error Message:

Msg 8120, Level 16, State 1, Line 1

  Column 'dbo.Transactions.cust_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Body:
GROUP BY produces rows that are UNIQUE for the combination of values held in the columns you specify under that clause. Your overall query should look more like this, where the "non-aggregating columns" are listed in the GROUP BY clause

SELECT
      T.cust_id    --<< this is a "non-aggregating" column
    , c.gender     --<< this is a "non-aggregating" column
    , C.city_code  --<< this is a "non-aggregating" column
    , DATEDIFF(mm, c.dob, GETDATE())    AS AGE_IN_MONTHS --<< this is a "non-aggregating" column

    , SUM(total_amt)                    AS Tot_sal_amt
    , SUM(qty)                          AS tot_sal_qnty
    , COUNT(DISTINCT store_type)        AS Unq_chnl_cnt
    , MAX(tran_date)                    AS Last_Transaction_date
    , AVG(qty) / COUNT(tran_date)       AS Avg_basket_qty
    , AVG(total_amt) / COUNT(tran_date) AS Avg_basket_val

--INTO customer_360
FROM dbo.customer AS c
INNER JOIN dbo.transactions AS t ON t.cust_id = c.customer_id
GROUP BY
      T.cust_id      --<< list each non-aggregating column here
    , c.gender       --<< list each non-aggregating column here
    , C.city_code    --<< list each non-aggregating column here
    , DATEDIFF(mm, c.dob, GETDATE())  --<< list each non-aggregating column here

Note please that "select distinct" is utterly, totally, completely redundant if you are using GROUP BY (correctly) in the same select query. Also "select distinct" does less than GROUP BY can do for you (e.g. SUM/MIN/MAX/AVG values).

Further notes:

AVG(qty) / COUNT(tran_date) will produce an integer result, yo may want to do this instead AVG(qty) / (COUNT(tran_date)*1.0)

This join was removed INNER JOIN dbo.prod_cat_info AS pci ON pci.prod_cat_code = t.prod_cat_code as it is MIGHT multiply results. Compare the query above to another where this join is included. If the aggregations are affected then you will need a subquery against this table and join that instead. Due to this the following columns are missing too:

            (SELECT Count(DISTINCT prod_cat)
             FROM   dbo.prod_cat_info)                 AS Unq_cat_cnt,
            (SELECT DISTINCT prod_subcat
             FROM   dbo.prod_cat_info)                 AS Unq_Scat_cnt,

These was also been removed as I wasn't certain what you intended with it:

            (SELECT Count(transaction_id)
             FROM   transactions
             GROUP  BY tran_date)  AS  basket_count_per_day,

A subquery such as this isn't permitted to return multiple values; which this will do. So it would cause an error and you need to decide how to incorporate "daily averages" into a table with one row per customer.


来源: stackexchange

问:
C# Attach properties? to enum
I have an enum:

```<code>enum RANK
{
    kingdom=0,
    phylum=1,
    order=2,
    family=3,
    genus=4,
    species=5
}
</code>```

where each item has a parent (the rank above) and child (the rank below). Out of bounds errors (e.g. trying to find the parent of a kingdom) result in an exception. The questions is whether it is possible to attach an attribute (or anything really) to the enum so that it can be called:

```<code>RANK child = kingdom.Child;
RANK parent = species.Parent;
</code>```

I have code to call this as a function (which is on the border of my understanding)

```<code>public static RANK GetParent(this RANK rank)
    {
        if ((rank - 1) > (RANK)0)
        {
            return rank - 1;
        }
        else
        {
            throw new ArgumentOutOfRangeException("No parent rank");
        }
    }
</code>```

with corresponding GetChild version. Called as:

```<code>RANK child = kingdom.GetChild();
RANK parent = species.GetPArent();
</code>```

This is annoying me, as it's not really a function call but a variable call, and should really be called as such. I'm open to suggestions, however I need enum-type behaviour from the result (fixed list and called in the same way, this is going to be near non-technical people!) So long as it looks like an enum and behaves like an enum, it'll pass as an enum.

答:
Can you wrap your needs into a class.

```<code>public enum Rank
{
    Kingdom,
    Phylum,
    Order,
}

public class Family
{
    public Rank Rank { get; set; }
    public Rank Child => Enum.IsDefined(typeof(Rank), Rank + 1) ? Rank +  1 : throw new ArgumentOutOfRangeException("No child rank");
    public Rank Parent => Enum.IsDefined(typeof(Rank),Rank - 1) ? Rank -  1 : throw new ArgumentOutOfRangeException("No parent rank");

}
</code>```

Usage -

```<code>Family family = new Family();
rank.Rank = Rank.Order;
Rank child = family.Child;
Rank parent = family.Parent; //this will throw an exception
</code>```

ContentLicense: CC BY-SA 3.0

Title: C# Attach properties? to enum

Body:
I have an enum:

enum RANK
{
    kingdom=0,
    phylum=1,
    order=2,
    family=3,
    genus=4,
    species=5
}

where each item has a parent (the rank above) and child (the rank below). Out of bounds errors (e.g. trying to find the parent of a kingdom) result in an exception. The questions is whether it is possible to attach an attribute (or anything really) to the enum so that it can be called:

RANK child = kingdom.Child;
RANK parent = species.Parent;

I have code to call this as a function (which is on the border of my understanding)

public static RANK GetParent(this RANK rank)
    {
        if ((rank - 1) > (RANK)0)
        {
            return rank - 1;
        }
        else
        {
            throw new ArgumentOutOfRangeException("No parent rank");
        }
    }

with corresponding GetChild version. Called as:

RANK child = kingdom.GetChild();
RANK parent = species.GetPArent();

This is annoying me, as it's not really a function call but a variable call, and should really be called as such. I'm open to suggestions, however I need enum-type behaviour from the result (fixed list and called in the same way, this is going to be near non-technical people!) So long as it looks like an enum and behaves like an enum, it'll pass as an enum.

Body:
Can you wrap your needs into a class.

public enum Rank
{
    Kingdom,
    Phylum,
    Order,
}

public class Family
{
    public Rank Rank { get; set; }
    public Rank Child => Enum.IsDefined(typeof(Rank), Rank + 1) ? Rank +  1 : throw new ArgumentOutOfRangeException("No child rank");
    public Rank Parent => Enum.IsDefined(typeof(Rank),Rank - 1) ? Rank -  1 : throw new ArgumentOutOfRangeException("No parent rank");

}

Usage -

Family family = new Family();
rank.Rank = Rank.Order;
Rank child = family.Child;
Rank parent = family.Parent; //this will throw an exception


问:
Persist login/Authentication info on Android?
What is the best way to persist a users info in an android app?  I have a login screen that uses a web service to authenticate the user and return basic user info.

I don't care about saving the username/password, but I do need things like a couple of integer ID fields (patientID and personID) and a first and last name.

I don't want the user to have to login every time they load the app.  Someone suggested I use SQL lite to store the info, is this the best way or is there a more light weight solution?

答:
Use SharedPreferences
refer this link also</p>

ContentLicense: CC BY-SA 2.5


问:
NFC implemetation in iOS7
I am planning to implement NFC in iPhone. I would like to know that iOS7 can use NFC sdk.
When I research about NFC, I found that is the new sdk for iOS 11 and heigher. I just found out some examples for NFC but they are implemented using swift. I also would like to know that I can also use objective c to implement NFC.</p>

答: iOS 11 contains Core NFC framework and it works only for tag reading. Reading NFC NDEF tags is supported on iPhone 7 and iPhone 7 Plus. Of course, you can use Objective-C for your application. And you can't use NFC on iOS 7. Read more in official docs. And here is my basic example of using Core NFC.</p>

Title: NFC implemetation in iOS7


问:
NPM fails when installing image-webpack-loader. I can't proceed with my project.
Webpack was working fine all day and when I added a new image it suddenly failed. I updated node and npm and I still get the following error. How would I go about fixing this or using an alternative? The other image loader modules I attempted to install give the same error.</p>

```<code>74857 verbose stack Error: gifsicle@3.0.4 postinstall: `node lib/install.js`
74857 verbose stack Exit status 1
74857 verbose stack     at EventEmitter.<anonymous> (C:\Users\mykod\AppData\Roaming\npm\node_modules\npm\lib\utils\lifecycle.js:279:16)
74857 verbose stack     at emitTwo (events.js:106:13)
74857 verbose stack     at EventEmitter.emit (events.js:191:7)
74857 verbose stack     at ChildProcess.<anonymous> (C:\Users\mykod\AppData\Roaming\npm\node_modules\npm\lib\utils\spawn.js:40:14)
74857 verbose stack     at emitTwo (events.js:106:13)
74857 verbose stack     at ChildProcess.emit (events.js:191:7)
74857 verbose stack     at maybeClose (internal/child_process.js:877:16)
74857 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
74858 verbose pkgid gifsicle@3.0.4
74859 verbose cwd C:\Users\mykod\Desktop\best-voted
74860 error Windows_NT 10.0.14393
74861 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\mykod\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install"
74862 error node v6.9.4
74863 error npm  v4.3.0
74864 error code ELIFECYCLE
74865 error errno 1
74866 error gifsicle@3.0.4 postinstall: `node lib/install.js`
74866 error Exit status 1
74867 error Failed at the gifsicle@3.0.4 postinstall script 'node lib/install.js'.
74867 error Make sure you have the latest version of node.js and npm installed.
74867 error If you do, this is most likely a problem with the gifsicle package,
74867 error not with npm itself.
74867 error Tell the author that this fails on your system:
74867 error     node lib/install.js
74867 error You can get information on how to open an issue for this project with:
74867 error     npm bugs gifsicle
74867 error Or if that isn't available, you can get their info via:
74867 error     npm owner ls gifsicle
74867 error There is likely additional logging output above.
74868 verbose exit [ 1, true ]
</code>```

答:
Restarting doesn't help for me. There was problems with permissions on my laptop.
I'm working on Ubuntu 16.04.

Here is solution: fixing npm permissions

I'm recommending to watch video first.
At least check NPM's directory first npm config get prefix and if it's /usr, you have to use Option 2.

I've solved this problems with processing step by step of Option 2.

Body:
Webpack was working fine all day and when I added a new image it suddenly failed. I updated node and npm and I still get the following error. How would I go about fixing this or using an alternative? The other image loader modules I attempted to install give the same error.

74857 verbose stack Error: gifsicle@3.0.4 postinstall: `node lib/install.js`
74857 verbose stack Exit status 1
74857 verbose stack     at EventEmitter.<anonymous> (C:\Users\mykod\AppData\Roaming\npm\node_modules\npm\lib\utils\lifecycle.js:279:16)
74857 verbose stack     at emitTwo (events.js:106:13)
74857 verbose stack     at EventEmitter.emit (events.js:191:7)
74857 verbose stack     at ChildProcess.<anonymous> (C:\Users\mykod\AppData\Roaming\npm\node_modules\npm\lib\utils\spawn.js:40:14)
74857 verbose stack     at emitTwo (events.js:106:13)
74857 verbose stack     at ChildProcess.emit (events.js:191:7)
74857 verbose stack     at maybeClose (internal/child_process.js:877:16)
74857 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
74858 verbose pkgid gifsicle@3.0.4
74859 verbose cwd C:\Users\mykod\Desktop\best-voted
74860 error Windows_NT 10.0.14393
74861 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\mykod\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install"
74862 error node v6.9.4
74863 error npm  v4.3.0
74864 error code ELIFECYCLE
74865 error errno 1
74866 error gifsicle@3.0.4 postinstall: `node lib/install.js`
74866 error Exit status 1
74867 error Failed at the gifsicle@3.0.4 postinstall script 'node lib/install.js'.
74867 error Make sure you have the latest version of node.js and npm installed.
74867 error If you do, this is most likely a problem with the gifsicle package,
74867 error not with npm itself.
74867 error Tell the author that this fails on your system:
74867 error     node lib/install.js
74867 error You can get information on how to open an issue for this project with:
74867 error     npm bugs gifsicle
74867 error Or if that isn't available, you can get their info via:
74867 error     npm owner ls gifsicle
74867 error There is likely additional logging output above.
74868 verbose exit [ 1, true ]


问:
Add strings with ajax from server using phpMyAdmin, jquery
Right now, i'm trying to add a couple of
, using ajax. The problem is that i'd like these
 to use data from a database I have on the server. I'd like to know how to do that! Also, is it possible to use jQuery?

Let's say I have a
, where I have a
 and then some
. Those
 are the ones I want to change via ajax.
I use phpMyAdmin, where I have a database called t_menuMaterials, and I want to retrieve strings inside m_nom.
I'd also want to be able to change the menu, on a click of a button, change t_menuMaterials to t_menuTextures.
I have been able to populate my menu, but only at the load of the page like that!

```<code>$requeteMenuMaterials = "SELECT * FROM t_menuMaterials ORDER BY m_id LIMIT 10";
$ressourcesListe = mysql_query($requeteMenuMaterials);

$targetMenu = "SELECT r_categorie FROM t_ressources ORDER BY m_id LIMIT 10";
$ressourcesListe2 = mysql_query($targetMenu);
$menu2 ='';
while($tbl_ressources1 = mysql_fetch_assoc($ressourcesListe)){
    $menu2 .='<li class="secondaryMenu"><a href="#" onClick="test('.$ressourcesListe2.');" ><div>'.$tbl_ressources1['m_nom'].'</div></a></li>';
}
</code>```

Now, I'd like to be able to change the div (like if $requeteMenuMaterials became ="SELECT * FROM t_menuTextures(instead of t_menuMaterials). I have no idea on how to change those
 via ajax using my databases and phpMyAdmin.

答:
jQuery $.get is probably what you need. Basically, have a page that pulls the relevant data from the database, and echo it out to your page. So your page (get-li-data.php, for example) might output:

```<code><li>An item</li>
<li>Another item</li>
</code>```

And use $.get to get that data and insert it into a div, like:

```<code>$.get('/get-li-data.php', function(data) {
  $('#div-where-i-have-a-ul').html(data);
});
</code>```

Body:
Right now, i'm trying to add a couple of
, using ajax. The problem is that i'd like these
 to use data from a database I have on the server. I'd like to know how to do that! Also, is it possible to use jQuery?

Let's say I have a
, where I have a
 and then some
. Those
 are the ones I want to change via ajax.
I use phpMyAdmin, where I have a database called t_menuMaterials, and I want to retrieve strings inside m_nom.
I'd also want to be able to change the menu, on a click of a button, change t_menuMaterials to t_menuTextures.
I have been able to populate my menu, but only at the load of the page like that!

$requeteMenuMaterials = "SELECT * FROM t_menuMaterials ORDER BY m_id LIMIT 10";
$ressourcesListe = mysql_query($requeteMenuMaterials);

$targetMenu = "SELECT r_categorie FROM t_ressources ORDER BY m_id LIMIT 10";
$ressourcesListe2 = mysql_query($targetMenu);
$menu2 ='';
while($tbl_ressources1 = mysql_fetch_assoc($ressourcesListe)){
    $menu2 .='

'.$tbl_ressources1['m_nom'].'

';
}

Now, I'd like to be able to change the div (like if $requeteMenuMaterials became ="SELECT * FROM t_menuTextures(instead of t_menuMaterials). I have no idea on how to change those
 via ajax using my databases and phpMyAdmin.

Body:
jQuery $.get is probably what you need. Basically, have a page that pulls the relevant data from the database, and echo it out to your page. So your page (get-li-data.php, for example) might output:

<li>An item</li>
<li>Another item</li>

And use $.get to get that data and insert it into a div, like:

$.get('/get-li-data.php', function(data) {
  $('#div-where-i-have-a-ul').html(data);
});


问:
Error 0xc000007b when launching mongod.exe / mongo.exe
Installed mongodb on Windows.

Mongodb: 3.4.3 - Windows Server 2008 R2 64-bit, with SSL support x64

OS: Windows 7 64-bit

When I run mongod.exe or mongo.exe this error occurs

The application was unable to start correctly (0xc000007b). Click OK to close the application

What can I do to get rid of this error?
Thanks to everyone who helped.

答: I got rid of this error by updating Visual C++ Redistributable. But note that before this i also updated my Net Framework, DirectX and drivers for video-card.


答:
No, there's no such thing as an extension property. But you could create your own class:

```<code>public sealed class Rank
{
    private static readonly List<Rank> ranks = new List<Rank>();

    // Important: these must be initialized in order.
    // (That can be avoided, but only at the cost of more code.)
    public static Rank Kingdom { get; } = new Rank(0);
    public static Rank Phylum { get; } = new Rank(1);
    public static Rank Order { get; } = new Rank(2);
    public static Rank Family { get; } = new Rank(3);
    public static Rank Genus { get; } = new Rank(4);
    public static Rank Species { get; } = new Rank(5);

    private readonly int value;

    // TODO: Change to throw InvalidOperationException (or return null)
    // for boundaries
    public Rank Child => ranks[value + 1];
    public Rank Parent => ranks[value - 1];

    private Rank(int value)
    {
        this.value = value;
        ranks.Add(this);
    }
}
</code>```

Then you use:

```<code>Rank kingdom = Rank.Kingdom;
Rank phylum = kingdom.Child;
// etc
</code>```

The downside is that you don't get other enum behavior such as switching.

Title: C# Attach properties? to enum

Body:
No, there's no such thing as an extension property. But you could create your own class:

public sealed class Rank
{
    private static readonly List<Rank> ranks = new List<Rank>();

    // Important: these must be initialized in order.
    // (That can be avoided, but only at the cost of more code.)
    public static Rank Kingdom { get; } = new Rank(0);
    public static Rank Phylum { get; } = new Rank(1);
    public static Rank Order { get; } = new Rank(2);
    public static Rank Family { get; } = new Rank(3);
    public static Rank Genus { get; } = new Rank(4);
    public static Rank Species { get; } = new Rank(5);

    private readonly int value;

    // TODO: Change to throw InvalidOperationException (or return null)
    // for boundaries
    public Rank Child => ranks[value + 1];
    public Rank Parent => ranks[value - 1];

    private Rank(int value)
    {
        this.value = value;
        ranks.Add(this);
    }
}

Then you use:

Rank kingdom = Rank.Kingdom;
Rank phylum = kingdom.Child;
// etc

The downside is that you don't get other enum behavior such as switching.


问:
click() not working with xpath selector
I am new to UI testing and using Nightwatch. I'm unsuccessfully trying to click an element selected with xpath. It seems like a simple case, the element is asserted as visible, but it's not being clicked.

css:

```<code><a class="blabla" href="/xx/000/aaa">
  <div class="action-button__inner">Open This</div>
</a>
</code>```

selector:

```<code>openThis: {
      selector: '//div[text()="Open This"]',
      locateStrategy: 'xpath'
    }
</code>```

command:

```<code>.waitForElementVisible('@openThis', 2000)
.click('@openThis');
</code>```

output:

```<code>  ✔ Element <//div[text()="Open This"]> was visible after 74 milliseconds.
</code>```

BUT, it's not clicking on it, so the following assertions fail. All help would be appreciated! Thanks a lot guys!

答: instead of using waitForElementVisible property try using  waitForElementClickable</p>

Title: click() not working with xpath selector

Body:
I am new to UI testing and using Nightwatch. I'm unsuccessfully trying to click an element selected with xpath. It seems like a simple case, the element is asserted as visible, but it's not being clicked.

css:

Open This

selector:

openThis: {
      selector: '//div[text()="Open This"]',
      locateStrategy: 'xpath'
    }

command:

.waitForElementVisible('@openThis', 2000)
.click('@openThis');

output:

  ✔ Element <//div[text()="Open This"]> was visible after 74 milliseconds.

BUT, it's not clicking on it, so the following assertions fail. All help would be appreciated! Thanks a lot guys!


问:
How does Pusher handle delivering messages to backgrounded iOS applications
Pusher seems like a good fit for what I want to do, but the only thing that I can't figure out is how Pusher handles delivering a message to an iOS device that the application is not currently running on/backgrounded. I was really hoping that Pusher would fallback to push notifications through APNS and GCM (for Android), but I can't find any mention of that. How does Pusher handle delivery to backgrounded/not running applications.</p>

答:
Although this question is old, but it pops up on the google, so lets update the answer.

at the time of the question, the accepted answer (jcugat's) , I assume, was correct.
but now, it is not.

both services, Pusher and PubNub now support fall backing to Google's GCM/FCM on android and Apple's APN on ios for sending push notifications.


问:
Should I change dependency version of admob unity to match firebase?
I was using admob, gcm & google analytics.
Now I'm moving to firebase. But neither analytics nor admob works with firebase. For analytics moving to firebase analytics. But admob is needed.

Problem is because, firebase uses play services version 11.0.0 specifically.
But admob & google analytics uses version "LATEST".

Now jar resolvers pulling 11.0.0 for firebase and for other two taking 11.0.2.  And therefore duplicate classes are there and build fails.

I can solve it by changing the "LATEST" to 11.0.0 in admob's dependency resolver class.

But is it safe & recommended to do? As I'm changing the 3rd party plugin.

答:
It is recommended that you use Admob with Firebase since Admob is officialy a part of Firebase so there should be no worries in doing this.

The best way to use AdMob is with Firebase, but for those publishers
  who aren't ready to make the switch just yet, the Google Mobile Ads
  SDK can be used as a standalone
  SDK.


问:
Remove file from git repo, but not from server
At some point in the past, a symlink media file has been added to a git repo I'm working on.  I want to remove it from the repo, delete the file locally, but not on the server the repo is deployed to (I would also not want to have to re-make the symlink).  git update-index --assume-unchanged does not appear to be persistent, and git rm --cached would kill the files on deploy.

Is there a way of doing this?

答:
The short answer is : no, there is no way to both :

delete a file from the repo

have a raw git pull not delete the file on disk on a clone

If your deployment process starts with git pull on your production machine, you will have to take some extra action to re-create the symlink on this machine.

I don't know how deployhq works : I imagine you have a way to code "and please execute this script/list of actions after deploying the code", this list of actions should include "add the symlink".


问:
React Native Modal in ListView
I am attempting to implement modals into a Listview, where each list component is clickable and brings up a modal with relevant information. I am presently unable to get this working. My code is as follows:

renderRow function:

```<code> var modalState = false;
  open = () => {
      modalState = true;
    }
    close = () => {
      modalState = false;
    }
  return (
    <View>
    <View style={{flexDirection: 'row', padding: 3}}>
    <Card
    >
    <CardItem>
    <TouchableHighlight
    style={{padding: 15}}
    underlayColor = 'transparent'
    onPress = {() => {
      modalState = true;
      alert(modalState);
    }}
    >
    <Text style = {{color:'grey'}}>{devices.name}</Text>
    </TouchableHighlight>
    <TouchableHighlight
    style={{padding: 15}}
    underlayColor = 'transparent'
    onPress = {() => {
      modalState = true;
      alert(modalState);
    }}>
    <View>
    <Text>                    </Text>
    </View>
    </TouchableHighlight>
    </CardItem>
    </Card>
    </View>
    <Modal isVisible={modalState}>
    <Card>
    <CardItem>
    <View style = {styles.modal}>
        <Text>{devices.name}</Text>
        <Button
          title = "close"
          onPress = {() => {
            modalState = false;
          }}
          />
    </View>
    </CardItem>
    </Card>
    </Modal>
    </View>
  );
</code>```

答:
you should move the modalState variable to class state.
What happens in your code is that modalState is changing properly but it is not forcing the component to re-render hence modal is not receiving the new props, this.setState should solve this.</p>

```<code>class listWithModal extends React.Compoent {

    constructor(props) {
        super(props)
        this.state = {
            modalState = false
        }
    }
    render() {
        const {modalState} = this.state
        const open = () => {
            this.setState({ modalState: true })
        }
        const close = () => {
            this.setState({ modalState: true })
        }
        return (
            <View>
                <View style={{ flexDirection: 'row', padding: 3 }}>
                    <Card
                    >
                        <CardItem>
                            <TouchableHighlight
                                style={{ padding: 15 }}
                                underlayColor='transparent'
                                onPress={() => open()}
                            >
                                <Text style={{ color: 'grey' }}>{devices.name}</Text>
                            </TouchableHighlight>
                            <TouchableHighlight
                                style={{ padding: 15 }}
                                underlayColor='transparent'
                                onPress={() =>open()}>
                                <View>
                                    <Text>                    </Text>
                                </View>
                            </TouchableHighlight>
                        </CardItem>
                    </Card>
                </View>
                <Modal isVisible={modalState}>
                    <Card>
                        <CardItem>
                            <View style={styles.modal}>
                                <Text>{devices.name}</Text>
                                <Button
                                    title="close"
                                    onPress={() => close()}
                                />
                            </View>
                        </CardItem>
                    </Card>
                </Modal>
            </View>
        );
    }
}
</code>```

Title: React Native Modal in ListView

Body:
I am attempting to implement modals into a Listview, where each list component is clickable and brings up a modal with relevant information. I am presently unable to get this working. My code is as follows:

renderRow function:

 var modalState = false;
  open = () => {
      modalState = true;
    }
    close = () => {
      modalState = false;
    }
  return (
    <View>
    <View style={{flexDirection: 'row', padding: 3}}>
    <Card
    >
    <CardItem>
    <TouchableHighlight
    style={{padding: 15}}
    underlayColor = 'transparent'
    onPress = {() => {
      modalState = true;
      alert(modalState);
    }}
    >
    <Text style = {{color:'grey'}}>{devices.name}</Text>
    </TouchableHighlight>
    <TouchableHighlight
    style={{padding: 15}}
    underlayColor = 'transparent'
    onPress = {() => {
      modalState = true;
      alert(modalState);
    }}>
    <View>
    <Text>                    </Text>
    </View>
    </TouchableHighlight>
    </CardItem>
    </Card>
    </View>
    <Modal isVisible={modalState}>
    <Card>
    <CardItem>
    <View style = {styles.modal}>
        <Text>{devices.name}</Text>
        <Button
          title = "close"
          onPress = {() => {
            modalState = false;
          }}
          />
    </View>
    </CardItem>
    </Card>
    </Modal>
    </View>
  );

Body:
you should move the modalState variable to class state.
What happens in your code is that modalState is changing properly but it is not forcing the component to re-render hence modal is not receiving the new props, this.setState should solve this.

class listWithModal extends React.Compoent {

    constructor(props) {
        super(props)
        this.state = {
            modalState = false
        }
    }
    render() {
        const {modalState} = this.state
        const open = () => {
            this.setState({ modalState: true })
        }
        const close = () => {
            this.setState({ modalState: true })
        }
        return (
            <View>
                <View style={{ flexDirection: 'row', padding: 3 }}>
                    <Card
                    >
                        <CardItem>
                            <TouchableHighlight
                                style={{ padding: 15 }}
                                underlayColor='transparent'
                                onPress={() => open()}
                            >
                                <Text style={{ color: 'grey' }}>{devices.name}</Text>
                            </TouchableHighlight>
                            <TouchableHighlight
                                style={{ padding: 15 }}
                                underlayColor='transparent'
                                onPress={() =>open()}>
                                <View>
                                    <Text>                    </Text>
                                </View>
                            </TouchableHighlight>
                        </CardItem>
                    </Card>
                </View>
                <Modal isVisible={modalState}>
                    <Card>
                        <CardItem>
                            <View style={styles.modal}>
                                <Text>{devices.name}</Text>
                                <Button
                                    title="close"
                                    onPress={() => close()}
                                />
                            </View>
                        </CardItem>
                    </Card>
                </Modal>
            </View>
        );
    }
}


问:
CRT 9.0 vsprintf_s Parameter Validation on a long format string
From here:

The versions of these functions with
  _s and _p suffixes are the more secure versions. These versions validate the
  format strings and will generate an
  exception if the format string is not
  well formed (for example, if invalid
  formatting characters are used).

I just discovered the format string is considered not well formed if it is larger than the output buffer size.  Does anyone know of documentation that confirms this for all *_s print functions?

Thanks

答: Looks like the default behavior is to throw the CRT error if output buffer size is exceeded, regardless of source.  I expected the output to be silently truncated if the output buffer size is exceeded.  Thus, there is no point in attempting to fill in the format string if it is too long already.</p>


问:
delete record from two different table using one query Mysql
i want to delete record from two table which is relate by f key.
this is sample code the way i use in my original code. but this is not working.

DELETE from tb_extensions ext
inner JOIN tb_employee em
on em.emp_id = ext.emp_id
where tb_employee.emp_id = 'new1'

答:
Try this

DELETE ext,em from tb_extensions ext inner JOIN tb_employee em on em.emp_id = ext.emp_id where tb_employee.emp_id = 'new1';


问:
MySQL - Partitioning vs multiple table suggestion for a use case
We are having around 30,000 customers and each customer is having multiple products. We are currently storing all the products in a single table partitioned by KEY(customerid). I would like to get your suggestions if separate tables for each customer would be more beneficial over the partitioning OR we continue to use partitioning with current (HASH) or different type.

Number of products per customers varies, a few customers having > 1M products while some customers having as small as a few hundred products. This may result in not so perfect partitions.

If a customer account is to be deleted, so will be all products of that customer. In case of separate tables, this would be quite useful.

All customers are disjointed. So there is no query to access cross-customer products.

Number of customers are quite large (around 30k), I am not sure if that's a good idea to have so many tables.

Is any other partitioning scheme is better than what we currently using.

Thank you for your inputs.

答:
Generally I would go with the single table solution that you already have, it's the simple, straight-forward way to go.

You don't mention your motivation for wanting to change your setup.

How many entries do you have in your products table?

Are you experiencing performance issues with your current setup? If not I might be inclined to call this a case of "premature optimization".

If you ARE experiencing performance issues I would start by analyzing those first (profiling) to determine whether they are caused by your single products table design being a bottleneck.

Practical advice I can offer: Make sure you are using InnoDB storage engine and not MyISAM since that will allow for row level locks.

The downside to your proposal of having one table for each customer is maintenance and complexity. If you ever want to change your schema of the product tables it will be a lot more complicated and error prone task than before. You might have to make a script to batch the changes of all those tables, and what if the script crashes halfway? Then half of you customers have a changed table schema and the other half doesn't. As I mentioned if you do not currently have a performance problem you would be adding this complexity and maintenance without gaining anything.

You state that "All customers are disjointed. So there is no query to access cross-customer products." however it might not stay that way forever. Imagine in 2 months you need to extract a list of all customers who own specific product of type x, that would be a simple SQL query in your current setup, in the multi-table setup you would have to make a script or small program that could iterate over all customers and for each customer make a product query. So what was 1 query before is now 30.000 queries.

What you propose is a simple form of sharding. If you decide to go that way you may want to look into sharding since there are other ways to approach than the somewhat aggressive approach of giving every customer a dedicated table. E.g. use a hash of each customer id as sharding key, so every customer is either part of group A or group B. Products owned by A-customers are in ProductTableA, products owned by B-customers are in ProductTableB. (in a real implementation you may want to hash to a value between 0-255 and then keep a reference list saying that 0-127 are table-A, 128-255 are table-B, that way if you ever decide to scale up and add one more table, you don't have to recalculate all your hashes you just update your reference list).


问:
File upload using ajax and JavaScript function
Need a big favor! I'm trying to send uploaded file using JavaScript & Ajax, however not getting any success.

I want that when I upload the file, it will call the function myFunction(), and send the file to the PHP path(ajax.php) I've set.

Below is the code I've so far.

```<code><script>
   function myFunction() {
      var x = document.getElementById("up");
      $.ajax({
         type: 'GET',
         url: 'ajax.php',
         data: {},
         beforeSend: function() {},
         success: function(data) {
            alert(data);
         }
      });
   }
</script>
<input type="file" name="images" id="up" onchange="myFunction()" />
</code>```

答:
Uploading files with Jquery and Ajax is a little tricky, but it is something that is already fairly well documented. A quick google search returns a fairly good example of this https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax

The most important part is obtaining the formdata. Javascript can grab the file elements and build a FormData object from it. From the example above

```<code>$('input[type=file]').on('change', prepareUpload);
function prepareUpload(event)
{
  files = event.target.files;
}
</code>```

You can then build the form object and use that as the data component of your ajax request.

```<code>var data = new FormData();
$.each(files, function(key, value)
{
    data.append(key, value);
});
</code>```

Body:
Need a big favor! I'm trying to send uploaded file using JavaScript & Ajax, however not getting any success.

I want that when I upload the file, it will call the function myFunction(), and send the file to the PHP path(ajax.php) I've set.

Below is the code I've so far.

<input type="file" name="images" id="up" onchange="myFunction()" />

Body:
Uploading files with Jquery and Ajax is a little tricky, but it is something that is already fairly well documented. A quick google search returns a fairly good example of this https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax

The most important part is obtaining the formdata. Javascript can grab the file elements and build a FormData object from it. From the example above

$('input[type=file]').on('change', prepareUpload);
function prepareUpload(event)
{
  files = event.target.files;
}

You can then build the form object and use that as the data component of your ajax request.

var data = new FormData();
$.each(files, function(key, value)
{
    data.append(key, value);
});


问:
How to make SCNNode is always toward to ARFrame.camera
```<code>- (void)session:(ARSession *)session didUpdateFrame:(ARFrame *)frame {
    SCNNode *shipNode = self.sceneView.scene.rootNode.childNodes[0];
    if (shipNode) {
        shipNode.eulerAngles = SCNVector3FromFloat3(frame.camera.eulerAngles);
    }
}
</code>```

I want to change ship's orientation with camera's moving, but the above code seems useless.

答: Use an SCNBillboardConstraint to keep one node pointed toward another node.  </p>

Body:
- (void)session:(ARSession *)session didUpdateFrame:(ARFrame *)frame {
    SCNNode *shipNode = self.sceneView.scene.rootNode.childNodes[0];
    if (shipNode) {
        shipNode.eulerAngles = SCNVector3FromFloat3(frame.camera.eulerAngles);
    }
}

I want to change ship's orientation with camera's moving, but the above code seems useless.


问:
JPA: ORDER BY before GROUP BY in JPARepository
This is the mysql query that I've:

```<code>SELECT * FROM (SELECT vev.* FROM vital_entry ve
INNER JOIN vital_entry_values vev ON ve.vital_entry_id=vev.vital_entry_id
WHERE ve.account_id=146
ORDER BY date_entered DESC) t1
GROUP BY vital_id ;
</code>```

How do I do this in JPA?? I tried:

```<code>@Query("SELECT t1 FROM (SELECT ve FROM VitalEntry ve " +
            "INNER JOIN ve.vitalEntryValues vev " +
            "WHERE ve.accountId=:accountId " +
            "ORDER BY ve.dateEntered DESC) t1")
List<VitalEntry> getRecentVitalValues(@Param("accountId") int accountId);
</code>```

But IntelIj shows error expected identifer, got '('

答:
This gave me the expected result</p>

```<code>@Query("SELECT new com.v2.model.VitalValue(vev.vitalId, vev.value, max(ve.dateEntered), ve.vitalEntryType, vev.type) FROM VitalEntry ve " +
            "INNER JOIN ve.vitalEntryValues vev " +
            "WHERE ve.accountId=:accountId " +
            "GROUP BY vev.vitalId " +
            "ORDER BY max(ve.dateEntered) DESC")
List<VitalValue> getRecentVitalValues(@Param("accountId") int accountId);
</code>```

Body:
This is the mysql query that I've:

SELECT * FROM (SELECT vev.* FROM vital_entry ve
INNER JOIN vital_entry_values vev ON ve.vital_entry_id=vev.vital_entry_id
WHERE ve.account_id=146
ORDER BY date_entered DESC) t1
GROUP BY vital_id ;

How do I do this in JPA?? I tried:

@Query("SELECT t1 FROM (SELECT ve FROM VitalEntry ve " +
            "INNER JOIN ve.vitalEntryValues vev " +
            "WHERE ve.accountId=:accountId " +
            "ORDER BY ve.dateEntered DESC) t1")
List<VitalEntry> getRecentVitalValues(@Param("accountId") int accountId);

But IntelIj shows error expected identifer, got '('

Body:
This gave me the expected result

@Query("SELECT new com.v2.model.VitalValue(vev.vitalId, vev.value, max(ve.dateEntered), ve.vitalEntryType, vev.type) FROM VitalEntry ve " +
            "INNER JOIN ve.vitalEntryValues vev " +
            "WHERE ve.accountId=:accountId " +
            "GROUP BY vev.vitalId " +
            "ORDER BY max(ve.dateEntered) DESC")
List<VitalValue> getRecentVitalValues(@Param("accountId") int accountId);


问:
Upgrade from Delphi 7 to Delphi 2009
I have a Delphi 7 project in which there are some record types containing strings loaded and stored to files.

After recompiling with Delphi 2009, when the program loads the records from file, strings get messed up because the compiler expects Unicode while the file has Ansi strings.

The type is similar to this:

type

    Tpoint = record

    name: string[255];

    x, y: integer;

end;

After substituting "string" with "ansistring" the project doesn't even compile saying
"E2029 ';' expected but '[' found".
Suggestions?

答:
shortstring (which string[255] is) is still interpreted the same way as before: an array of AnsiChar with the first byte as its length. ansistring can not be defined as an array, therefore the error message.

How do you read the file to fill the records? And how do you fill them? Maybe the error occurs there.

Title: Upgrade from Delphi 7 to Delphi 2009

OwnerDisplayName: malach


问:
Display value from "input range" in another element gives "undefined"
This has been asked before, but I have found no solid, working, plain JS solution, all solutions out there are using frameworks or just do not work.

I simply want to get the value of a input "range" values and have them displayed in a span element.

I get undefined with no error in the console.

Here is the JS code:

```<code>document.getElementById("height").addEventListener("input",
sliderChange(this.value));

function sliderChange(val) {
document.getElementById('yourHeight').innerHTML = val;
}
</code>```

Further, I want to store the user input and use for another function to calculate the final results(this function is not there yet).

Here is the link:

https://codepen.io/damianocel/pen/ZyRogX

答:
You need to pass a function to addEventListener:

```<code>document.getElementById("height").addEventListener("input", function() { sliderChange(this.value) });
</code>```

Body:
This has been asked before, but I have found no solid, working, plain JS solution, all solutions out there are using frameworks or just do not work.

I simply want to get the value of a input "range" values and have them displayed in a span element.

I get undefined with no error in the console.

Here is the JS code:

document.getElementById("height").addEventListener("input",
sliderChange(this.value));

function sliderChange(val) {
document.getElementById('yourHeight').innerHTML = val;
}

Further, I want to store the user input and use for another function to calculate the final results(this function is not there yet).

Here is the link:

https://codepen.io/damianocel/pen/ZyRogX

Body:
You need to pass a function to addEventListener:

document.getElementById("height").addEventListener("input", function() { sliderChange(this.value) });


问:
Unable to Identify the Element in Selenium
```<code><div style="overflow:hidden;height:20px;" valign="middle">
<div id="IconImg_iconMenu_icon__dhtmlLib_274" class="imo"
 style="width:16px;height:16px;background-
image:url('images/main/galleries/icon16x16gallery1b.png');background-
position:0px -208px;margin-top:2px;cursor:pointer"></div>
</code>```

Can anyone help me to locate the above element in Selenium. Tried with different element identification methods nothing has helped.

答:
There are few possible answers.
You can find with xpath and cssSelector.

Xpath:
driver.findElement(By.xpath("//div[starts-with(@id, 'IconImg_iconMenu_icon'"));

CssSelector:
driver.findElement(By.cssSelector("div[id^='IconImg_iconMenu_icon']"));

In CssSelector ^= means starts-with.


问:
PHP Fatal error: Uncaught Error: Cannot use object of type mysqli as array
I don't understand why this line:

```<code>$this->db = mysqli($db['host'],$db['user'],$db['pass'],$db['name']);
</code>```

Give me that error:

[05-Jul-2017 11:55:26 Europe/Berlin] PHP Fatal error: Uncaught Error:
  Cannot use object of type mysqli as array in
  /var/www/***/public_html/core/classes.php:7

Stack trace: #0 /var/www/***/public_html/core/classes.php(19):
  Database->connectDatabase()

1 /var/www/***/public_html/index.php(5): Core->__construct()

2 {main} thrown in /var/www/***/public_html/core/classes.php on line 7

I'm running Ubuntu Apache PHP7, phpinfo() does mention the mysqli ext.

答:
Did you tried with keyword new before mysqli

```<code>$this->db = new mysqli($db['host'],$db['user'],$db['pass'],$db['name']);
</code>```

Also check, is any of given parameters to mysqli function is array (it may cause the error).
$db['host'],$db['pass'],$db['user'],$db['name'] should be strings

Body:
I don't understand why this line:

$this->db = mysqli($db['host'],$db['user'],$db['pass'],$db['name']);

Give me that error:

[05-Jul-2017 11:55:26 Europe/Berlin] PHP Fatal error: Uncaught Error:
  Cannot use object of type mysqli as array in
  /var/www/***/public_html/core/classes.php:7

Stack trace: #0 /var/www/***/public_html/core/classes.php(19):
  Database->connectDatabase()

1 /var/www/***/public_html/index.php(5): Core->__construct()

2 {main} thrown in /var/www/***/public_html/core/classes.php on line 7

I'm running Ubuntu Apache PHP7, phpinfo() does mention the mysqli ext.

Body:
Did you tried with keyword new before mysqli

$this->db = new mysqli($db['host'],$db['user'],$db['pass'],$db['name']);

Also check, is any of given parameters to mysqli function is array (it may cause the error).
$db['host'],$db['pass'],$db['user'],$db['name'] should be strings


问:
How I set maxLength attribute in <input type='number'> in HTML5?
I want maxLength Validation in  in HTML5.

I tried like this

```<code><input type="number" name="trainer_mobile_no[]" maxlength="10" class="form-control" required="required"/>
</code>```

答:
You cannot set max length but max value for number input type something like this:</p>

```<code> <input type="number" min="0" max="100">
</code>```

Body:
I want maxLength Validation in  in HTML5.

I tried like this

<input type="number" name="trainer_mobile_no[]" maxlength="10" class="form-control" required="required"/>

Body:
You cannot set max length but max value for number input type something like this:

 <input type="number" min="0" max="100">


问:
Migrating from Mysql to Postgresql Yii2 query
Before, we were using mysql for our database but when we migrated to postgresql we encountered this problem.

SQLSTATE[42803]: Grouping error: 7 ERROR: column "table.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT COUNT(*) FROM (SELECT * FROM (SELECT * FROM "kv_firmw...
^
The SQL being executed was: SELECT COUNT(*) FROM (SELECT * FROM (SELECT * FROM "kv_firmware_release" ORDER BY "id" DESC) "table" GROUP BY "filename") "c"

I have this code in Yii2 search model.

```<code>    $subquery = new Query;
    $subquery->select(['*']);
    $subquery->from('kv_firmware_release')->orderBy('id DESC');

    $query = new Query;
    $query->select(['*']);
    $query->from(['table' => $subquery])->groupBy('filename');

    $query->limit(5);
</code>```

This is my first time to use Psql. It works fine before, but now it is giving me the error. How can I fix this in Yii2?

答:
in PostgreSQL when use group by you must write all fields using in select or unique or primary key

For example

```<code>SELECT id, name, email FROM contact GROUP BY id, name, email
</code>```

OR

```<code>SELECT id, name, email FROM contact GROUP BY id
</code>```

wil work when column id  is primary or unique key

Body:
Before, we were using mysql for our database but when we migrated to postgresql we encountered this problem.

SQLSTATE[42803]: Grouping error: 7 ERROR: column "table.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT COUNT(*) FROM (SELECT * FROM (SELECT * FROM "kv_firmw...
^
The SQL being executed was: SELECT COUNT(*) FROM (SELECT * FROM (SELECT * FROM "kv_firmware_release" ORDER BY "id" DESC) "table" GROUP BY "filename") "c"

I have this code in Yii2 search model.

    $subquery = new Query;
    $subquery->select(['*']);
    $subquery->from('kv_firmware_release')->orderBy('id DESC');

    $query = new Query;
    $query->select(['*']);
    $query->from(['table' => $subquery])->groupBy('filename');

    $query->limit(5);

This is my first time to use Psql. It works fine before, but now it is giving me the error. How can I fix this in Yii2?

Body:
in PostgreSQL when use group by you must write all fields using in select or unique or primary key

For example

SELECT id, name, email FROM contact GROUP BY id, name, email

OR

SELECT id, name, email FROM contact GROUP BY id

wil work when column id  is primary or unique key


问:
Effective way to compute cosine similarity for sparse tensors in python?
I have a list of unit tensors(length = 1). This list contains ~20 000 such tensors. Tensors have ~3 000  dimensions but are very sparse. Only x (0 < x < 1) dimensions are not 0. And I need to compute cosine similarity between all these tensors. What is the most effective way to do this? (This is not an NLP task, but my solution looks similar to word2Vect approach, that's why I have added NLP tag. My tensor has more dimensions than word2vec and it is more sparse)

答:
SciKit-Learn's cosine_similarity is your friend:

from scipy import sparse
from sklearn.metrics.pairwise import cosine_similarity

# example test:
T = sparse.rand(4, 3, 0.9)
cosine_similarity(T)

# full run (tensor as described in question):
T = sparse.rand(20000, 3000)
%time cosine_similarity(T)
```

<p>Takes about 4.4 seconds on my machine.</p>

```# staying sparse:
%time cosine_similarity(T, dense_output=False)
```

Takes less than 2 seconds on my machine (i.e., around a factor 2 speedup).

ContentLicense: CC BY-SA 4.0

Body:
SciKit-Learn's cosine_similarity is your friend:

from scipy import sparse
from sklearn.metrics.pairwise import cosine_similarity

# example test:
T = sparse.rand(4, 3, 0.9)
cosine_similarity(T)

# full run (tensor as described in question):
T = sparse.rand(20000, 3000)
%time cosine_similarity(T)

Takes about 4.4 seconds on my machine.

# staying sparse:
%time cosine_similarity(T, dense_output=False)

Takes less than 2 seconds on my machine (i.e., around a factor 2 speedup).


问:
Reload only one section header in UITableView
I'm using a custom cell as a section header in my UITableView. In that cell there are three buttons. If any of the buttons are clicked in that section's cell, it should reload that custom section cell only, not any rows. Is this possible?

I was using the following code to reload that cell:

```<code>tableViewHome.reloadSections([1], with: UITableViewRowAnimation.none)
</code>```

It's hiding my section cell and distorting my entire table.

UPDATE

I'm using UITableView and following code I'm using:

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let cellHeader = tableViewHome.dequeueReusableCell(withIdentifier: "header") as! HeaderTableViewCell

        cellHeader.filter1btn.addTarget(self, action: #selector(filterBtnAction(_:)), for: .touchUpInside)
        cellHeader.filter2Btn.addTarget(self, action: #selector(filterBtnAction(_:)), for: .touchUpInside)
        cellHeader.filter3btn.addTarget(self, action: #selector(filterBtnAction(_:)), for: .touchUpInside)

        return cellHeader
    }

    @IBAction func filterBtnAction(_ sender: UIButton) {

        print(sender.tag)

        tableViewHome.reloadSections([1], with: UITableViewRowAnimation.none)

    }
</code>```

答:
What I did and working very correctly, Please follow the given answer:

SWIFT 3.1

Step 1:

Firstly I took a view xib, designed that according to my requirement and did register in my required class.

Secondly, did sub class class HeaderView: UITableViewHeaderFooterView of UITableViewHeaderFooterView

Like following image:

In my required class(here homeclass) I did register my xib file for my tableview.

```<code>override func viewDidLoad() {
        super.viewDidLoad()
        tableViewHome.register(UINib(nibName: "HeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: "HeaderView")
}
</code>```

Step 2:

Then in my required class i did following:

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let cellHeader = tableViewHome.dequeueReusableHeaderFooterView(withIdentifier: "HeaderView") as! HeaderView
        cellHeader.filterAction(cellHeader.filter1Btn)

        return cellHeader
    }
</code>```

And it started working as per my requirement, later i added custom delegate for more actions in my class, but by subviewing, its now working.

Body:
I'm using a custom cell as a section header in my UITableView. In that cell there are three buttons. If any of the buttons are clicked in that section's cell, it should reload that custom section cell only, not any rows. Is this possible?

I was using the following code to reload that cell:

tableViewHome.reloadSections([1], with: UITableViewRowAnimation.none)

It's hiding my section cell and distorting my entire table.

UPDATE

I'm using UITableView and following code I'm using:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let cellHeader = tableViewHome.dequeueReusableCell(withIdentifier: "header") as! HeaderTableViewCell

        cellHeader.filter1btn.addTarget(self, action: #selector(filterBtnAction(_:)), for: .touchUpInside)
        cellHeader.filter2Btn.addTarget(self, action: #selector(filterBtnAction(_:)), for: .touchUpInside)
        cellHeader.filter3btn.addTarget(self, action: #selector(filterBtnAction(_:)), for: .touchUpInside)

        return cellHeader
    }

    @IBAction func filterBtnAction(_ sender: UIButton) {

        print(sender.tag)

        tableViewHome.reloadSections([1], with: UITableViewRowAnimation.none)

    }

Body:
What I did and working very correctly, Please follow the given answer:

SWIFT 3.1

Step 1:

Firstly I took a view xib, designed that according to my requirement and did register in my required class.

Secondly, did sub class class HeaderView: UITableViewHeaderFooterView of UITableViewHeaderFooterView

Like following image:

In my required class(here homeclass) I did register my xib file for my tableview.

override func viewDidLoad() {
        super.viewDidLoad()
        tableViewHome.register(UINib(nibName: "HeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: "HeaderView")
}

Step 2:

Then in my required class i did following:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let cellHeader = tableViewHome.dequeueReusableHeaderFooterView(withIdentifier: "HeaderView") as! HeaderView
        cellHeader.filterAction(cellHeader.filter1Btn)

        return cellHeader
    }

And it started working as per my requirement, later i added custom delegate for more actions in my class, but by subviewing, its now working.


问:
Multiple number from EditText with assigned number Android
I'm trying to get number which user inputs and multiple it with some assigned value. I can't see where I've made mistake, my app keeps crashing. I can't even run it.

MainActivity.java

```<code>public abstract class MainActivity extends AppCompatActivity implements OnItemSelectedListener {

    Button calculateBtn;
    EditText userEcts;
    TextView summary;
    int price = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userEcts = (EditText) findViewById(R.id.ects_input);
        summary = (TextView) findViewById(R.id.text_summary);

        calculateBtn = (Button) findViewById(R.id.calculate);
        calculateBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //When the button is clicked, call the calculate method.
                calculate();
            }
        });
    }

    public void calculate() {
        //gets entered text from the EditText,and convert to integers.
        Double ects = Double.parseDouble(userEcts.getText().toString());
        //do the calculation
        Double calculatedPrice = ects * price;
        //set the value to the TextView, to display on screen.
        summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
    }
}
</code>```

答:
I personally would suggest you to put a check like this on the calculate method before parsing the a string as double as an empty string can cause a crash too while parsing it:

```<code>  public void calculate() {
        //Put this empty check to prevent crash while parsing empty string.
      if (!TextUtils.isEmpty(userEcts.getText.toString())){
          Double ects = Double.parseDouble(userEcts.getText().toString());
          //do the calculation
          Double calculatedPrice = ects * price;
          //set the value to the TextView, to display on screen.
          summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
      }

    }
</code>```

Hope this helps.

Body:
I'm trying to get number which user inputs and multiple it with some assigned value. I can't see where I've made mistake, my app keeps crashing. I can't even run it.

MainActivity.java

public abstract class MainActivity extends AppCompatActivity implements OnItemSelectedListener {

    Button calculateBtn;
    EditText userEcts;
    TextView summary;
    int price = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userEcts = (EditText) findViewById(R.id.ects_input);
        summary = (TextView) findViewById(R.id.text_summary);

        calculateBtn = (Button) findViewById(R.id.calculate);
        calculateBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //When the button is clicked, call the calculate method.
                calculate();
            }
        });
    }

    public void calculate() {
        //gets entered text from the EditText,and convert to integers.
        Double ects = Double.parseDouble(userEcts.getText().toString());
        //do the calculation
        Double calculatedPrice = ects * price;
        //set the value to the TextView, to display on screen.
        summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
    }
}

Body:
I personally would suggest you to put a check like this on the calculate method before parsing the a string as double as an empty string can cause a crash too while parsing it:

  public void calculate() {
        //Put this empty check to prevent crash while parsing empty string.
      if (!TextUtils.isEmpty(userEcts.getText.toString())){
          Double ects = Double.parseDouble(userEcts.getText().toString());
          //do the calculation
          Double calculatedPrice = ects * price;
          //set the value to the TextView, to display on screen.
          summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
      }

    }

Hope this helps.


问:
Publish Node.JS server on the internet
I have a Node.JS server that works fine on localhost. Now I want it accessible from the internet, hosted by my machine. My public IP address (the one that Google tells me I have) does not seem to be "accessible":

```<code>https.createServer({
    key: privateKey,
    cert: certificate
}, server).listen(80, '86.151.23.17');
</code>```

fails with the following Node.JS error:

```<code>Error: listen EADDRNOTAVAIL
    at errnoException (net.js:770:11)
    at Server._listen2 (net.js:893:19)
    at listen (net.js:937:10)
    at Server.listen (net.js:994:9)
    at dns.js:71:18
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)
</code>```

How can I publish my Node.JS server to my public IP address?

[Note: I do not have another webserver running. Also, I have tried various different ports as suggested here.]

答:
Your app should listen on other ip address, example

```<code>app.listen(3000,'0.0.0.0');
</code>```

or just

```<code>app.listen(3000);
</code>```

Then you must open port forwarding in your modem. Like this http://www.dlink.com/uk/en/support/faq/routers/wireless-routers/dkt-series/how-do-i-open-up-ports-to-my-computer-port-forwarding-on-this-router

Finally you can see your app at ip address in here https://whatismyipaddress.com/

Title: Publish Node.JS server on the internet

Body:
I have a Node.JS server that works fine on localhost. Now I want it accessible from the internet, hosted by my machine. My public IP address (the one that Google tells me I have) does not seem to be "accessible":

https.createServer({
    key: privateKey,
    cert: certificate
}, server).listen(80, '86.151.23.17');

fails with the following Node.JS error:

Error: listen EADDRNOTAVAIL
    at errnoException (net.js:770:11)
    at Server._listen2 (net.js:893:19)
    at listen (net.js:937:10)
    at Server.listen (net.js:994:9)
    at dns.js:71:18
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

How can I publish my Node.JS server to my public IP address?

[Note: I do not have another webserver running. Also, I have tried various different ports as suggested here.]

Body:
Your app should listen on other ip address, example

app.listen(3000,'0.0.0.0');

or just

app.listen(3000);

Then you must open port forwarding in your modem. Like this http://www.dlink.com/uk/en/support/faq/routers/wireless-routers/dkt-series/how-do-i-open-up-ports-to-my-computer-port-forwarding-on-this-router

Finally you can see your app at ip address in here https://whatismyipaddress.com/


问:
How to apply css to ext component
I am creating a component.

Here is my code.

```<code>{
    xtype : 'component',
    width : 320,
    listeners :{
        afterrender : function(me,eOpts) {
             var divID = this.el.dom.id;
        }
    }
}
</code>```

I wanted to customize a my component as a css. there for I am accssing its id.

My question is How to apply css to ext component. By adding the new id and then css with respect to that id or by using the smae id.

答:
No need to access its id. You can define your own id for the component.

Ext.application({
  name: 'Fiddle',
  launch: function() {
    Ext.create('Ext.Component', {
      html: 'Hello world!',
      id: 'myComponentId',
      renderTo: Ext.getBody()
    });
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myComponentId {
  width: 300px;
  height: 200px;
  padding: 20px;
  color: #FFFFFF;
  background: #000000;
}</code>```

<link rel="stylesheet" href="https://cdn.sencha.com/ext/gpl/4.1.1/resources/css/ext-all.css">
```

Title: How to apply css to ext component

Body:
I am creating a component.

Here is my code.

{
    xtype : 'component',
    width : 320,
    listeners :{
        afterrender : function(me,eOpts) {
             var divID = this.el.dom.id;
        }
    }
}

I wanted to customize a my component as a css. there for I am accssing its id.

My question is How to apply css to ext component. By adding the new id and then css with respect to that id or by using the smae id.

Body:
No need to access its id. You can define your own id for the component.

Ext.application({
  name: 'Fiddle',
  launch: function() {
    Ext.create('Ext.Component', {
      html: 'Hello world!',
      id: 'myComponentId',
      renderTo: Ext.getBody()
    });
  }
});

#myComponentId {
  width: 300px;
  height: 200px;
  padding: 20px;
  color: #FFFFFF;
  background: #000000;
}

<link rel="stylesheet" href="https://cdn.sencha.com/ext/gpl/4.1.1/resources/css/ext-all.css">
<script type="text/javascript" src="https://cdn.sencha.com/ext/gpl/4.1.1/ext-all-debug.js"></script>


问:
How to update key value in talend with tmysqloutput component
My scenario is like, I have the tMysqlOutput component is like as follows

tMysqlOutput ---> Basic settings ---> Action on table is Default  and Action on Data is Update

tMysqlOutput ---> Advanced settings -----> Use field options

I want to update indicator (indicator is key column also), but i am unable to update the indicator

Thanks in Advance

答:
Can you please confirm, Have you committed the transaction after updating the table.

Please use tMysqlCommit after output comoponent or select "Auto Commit" in tmysqlConnection comoponent.

tmysqlConnection --> Advanced settings.


问:
How to simulate C++ friend in C# and VB.NET?
Because sometimes, I really need a friend.

I can think of the following tricks:

Read only wrapper - like ReadOnlyCollection. The friend keeps the pointer to the modifiable object, while everyone else can access only the wrapper.

Write delegate - the friend gives the constructor of the object a reference to a delegate as one of the parameters, the constructor fills it with an address to a private method that can be used to modify the object.

Reflection - obviously a bad idea. Included for completeness.

Multiple assemblies - put your friends together in a separate assembly and set your modifier methods internal.

Expose the modifiable object, but add comments to modifier methods "This is an infrastructure method - don't call it!"

Nested classes.

Add System.ComponentModel.EditorBrowsable(System.ComponentModel.
EditorBrowsableState.Never) attribute to the member you want only the friend to access to hide it from IntelliSense.

Implicit interface implementation - see comments.

Is this list exhaustive? Can anyone sort these in order of decreasing performance? Order of decreasing neatness? Any suggestions when to use which?

答:
In c# Nested classes (like private classes) are similar to friend in c++:

```<code>public class Root
{
   private int a; // accessible for friendroot

   public int b;

   public class FriendOfRoot
   {
      public int d;
   }

}
</code>```

Edit: If the simulation of friend with nested classes provided here is useful for you, in performance it's fast enough like regular classes (In compile all things will be determined and there is no casting issues and no overhead).

Body:
In c# Nested classes (like private classes) are similar to friend in c++:

public class Root
{
   private int a; // accessible for friendroot

   public int b;

   public class FriendOfRoot
   {
      public int d;
   }

}

Edit: If the simulation of friend with nested classes provided here is useful for you, in performance it's fast enough like regular classes (In compile all things will be determined and there is no casting issues and no overhead).


问:
Python: parsing a string of concatenated ascending integers
The objective is to parse the output of an ill-behaving program which concatenates a list of numbers, e.g., 3, 4, 5, into a string "345", without any non-number separating the numbers. I also know that the list is sorted in ascending order.

I came up with the following solution which reconstructs the list from a string:

```<code>a = '3456781015203040'
numlist = []

numlist.append(int(a[0]))

i = 1
while True:
    j = 1
    while True:
        if int(a[i:i+j]) <= numlist[-1]:
            j = j + 1
        else:
            numlist.append(int(a[i:i+j]))
            i = i + j
            break
    if i >= len(a):
        break
</code>```

This works, but I have a feeling that the solution reflects too much the fact that I have been trained in Pascal, decades ago.  Is there a better or more pythonic way to do it?

I am aware that the problem is ill-posed, i.e., I could start with '34' as the initial element and get a different solution (or possibly end up with remaining trailing numeral characters which don't form the next element of the list).

答:
This finds solutions for all possible initial number lengths:

```<code>a = '3456781015203040'

def numbers(a,n):
    current_num, i = 0, 0
    while True:
        while i+n <= len(a) and int(a[i:i+n]) <= current_num:
            n += 1
        if i+n <= len(a):
            current_num = int(a[i:i+n])
            yield current_num
            i += n
        else:
            return

for n in range(1,len(a)):
    l = list(numbers(a,n))
    # print only solutions that use up all digits of a
    if ''.join(map(str,l)) == a:
         print(l)
</code>```

```<code>[3, 4, 5, 6, 7, 8, 10, 15, 20, 30, 40]
[34, 56, 78, 101, 520, 3040]
[34567, 81015, 203040]
</code>```

Body:
The objective is to parse the output of an ill-behaving program which concatenates a list of numbers, e.g., 3, 4, 5, into a string "345", without any non-number separating the numbers. I also know that the list is sorted in ascending order.

I came up with the following solution which reconstructs the list from a string:

a = '3456781015203040'
numlist = []

numlist.append(int(a[0]))

i = 1
while True:
    j = 1
    while True:
        if int(a[i:i+j]) <= numlist[-1]:
            j = j + 1
        else:
            numlist.append(int(a[i:i+j]))
            i = i + j
            break
    if i >= len(a):
        break

This works, but I have a feeling that the solution reflects too much the fact that I have been trained in Pascal, decades ago.  Is there a better or more pythonic way to do it?

I am aware that the problem is ill-posed, i.e., I could start with '34' as the initial element and get a different solution (or possibly end up with remaining trailing numeral characters which don't form the next element of the list).

Body:
This finds solutions for all possible initial number lengths:

a = '3456781015203040'

def numbers(a,n):
    current_num, i = 0, 0
    while True:
        while i+n <= len(a) and int(a[i:i+n]) <= current_num:
            n += 1
        if i+n <= len(a):
            current_num = int(a[i:i+n])
            yield current_num
            i += n
        else:
            return

for n in range(1,len(a)):
    l = list(numbers(a,n))
    # print only solutions that use up all digits of a
    if ''.join(map(str,l)) == a:
         print(l)

[3, 4, 5, 6, 7, 8, 10, 15, 20, 30, 40]
[34, 56, 78, 101, 520, 3040]
[34567, 81015, 203040]


问:
Read or write file on system dbus without dependencie
I need to read (write later) a file with dbus method like:

```<code>busctl call org.freedesktop.systemd1 \
    /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager LoadUnit s fstrim.service
</code>```

I get object path

```<code>o "/org/freedesktop/systemd1/unit/fstrim_2eservice"
</code>```

Now, I would like to display its contents.

Is there a solution?

答:
This is basically the same as this serverfault question.

You want to query the FragmentPath property of the org.freedesktop.systemd1.Unit interface on that object path.

```<code>$ busctl get-property org.freedesktop.systemd1 /org/freedesktop/systemd1/unit/NetworkManager_2eservice org.freedesktop.systemd1.Unit FragmentPath
s "/usr/lib/systemd/system/NetworkManager.service"
</code>```

That gives you the filename to load and display.

Body:
I need to read (write later) a file with dbus method like:

busctl call org.freedesktop.systemd1 \
    /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager LoadUnit s fstrim.service

I get object path

o "/org/freedesktop/systemd1/unit/fstrim_2eservice"

Now, I would like to display its contents.

Is there a solution?

Body:
This is basically the same as this serverfault question.

You want to query the FragmentPath property of the org.freedesktop.systemd1.Unit interface on that object path.

$ busctl get-property org.freedesktop.systemd1 /org/freedesktop/systemd1/unit/NetworkManager_2eservice org.freedesktop.systemd1.Unit FragmentPath
s "/usr/lib/systemd/system/NetworkManager.service"

That gives you the filename to load and display.


问:
Javascript Regex - get div IDs from string html
Consider the following code:

```<code>const content = "<div id='x'><h2>Lorem Ipsum</h2> <p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p></div>"

let ids = content.match(/id='(.*?)'/g).map((val) => {
    return val.replace(/id='/g,'');
})
</code>```

And when I do console.log(ids) - I get the output like this 'x\'' but I need only 'x'. I'm wondering how to achive that result, I've tried by randomly changing regex symbols, because I don't know regex at all - and nothing seems to be working.

No jquery please. Thank you in advance

答:
when you use dot "." it means everything but you are searching everithing but ' character</p>

```<code>const content = "<div id='x'><h2>Lorem Ipsum</h2> <p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p></div>"

let ids = content.match(/id='([^' .*?])'/g).map((val) => {
    return val.replace(/id='([^' .*?])'/g,'$1');
})

console.log(ids)
</code>```

Body:
Consider the following code:

const content = "

Lorem Ipsum

is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

"

let ids = content.match(/id='(.*?)'/g).map((val) => {
    return val.replace(/id='/g,'');
})

And when I do console.log(ids) - I get the output like this 'x\'' but I need only 'x'. I'm wondering how to achive that result, I've tried by randomly changing regex symbols, because I don't know regex at all - and nothing seems to be working.

No jquery please. Thank you in advance

Body:
when you use dot "." it means everything but you are searching everithing but ' character

const content = "<div id='x'><h2>Lorem Ipsum</h2> <p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p></div>"

let ids = content.match(/id='([^' .*?])'/g).map((val) => {
    return val.replace(/id='([^' .*?])'/g,'$1');
})

console.log(ids)


问:
checking database for necessary updates using dateDiff
hey stackoverflowers. im having a few problems with the code i have written to check my database on refresh if all record dates on the database are between the specified $min and $max values. if not then the record will be updated. this is what i have done so far.

```<code>// check database for necessary updates

    $update = mysql_query("SELECT * FROM rent");

    while($row = mysql_fetch_array( $update )) {

    $datetime_lower   = DateTime::createFromFormat('d/m/Y', $min);
    $datetime_upper   = DateTime::createFromFormat('d/m/Y', $max);
    $datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', $row_update['pDate']);

    $diff_lower = $datetime_lower->diff($datetime_compare);
    $diff_upper = $datetime_upper->diff($datetime_compare);

    if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {
        // date is between min and max, do nothing
    } else {
        // date is not between min and max, update cell colour
$result = mysql_query("UPDATE rent SET colour='F0F0F0' WHERE $datetime_lower < $pDate && $datetime_upper > $pDate") or die(mysql_error());
    }
    }
</code>```

the logic behind it seems rather rational but whenever i try to run the code i get the error message:

```<code>Warning: DateTime::diff() expects parameter 1 to be DateTime, boolean given in C:\xampp\htdocs\keypad\main.php on line 41

Warning: DateTime::diff() expects parameter 1 to be DateTime, boolean given in C:\xampp\htdocs\keypad\main.php on line 42
</code>```

any idea whats going on?

答:
fetching into $row but using $row_update

UPDATE rent SET colour='F0F0F0' will update ALL records if one tupel is not between $min and $max

Why not UPDATE rent SET colour='F0F0F0' WHERE pDate NOT BETWEEN $min AND $max MySQL Between

Body:
hey stackoverflowers. im having a few problems with the code i have written to check my database on refresh if all record dates on the database are between the specified $min and $max values. if not then the record will be updated. this is what i have done so far.

// check database for necessary updates

    $update = mysql_query("SELECT * FROM rent");

    while($row = mysql_fetch_array( $update )) {

    $datetime_lower   = DateTime::createFromFormat('d/m/Y', $min);
    $datetime_upper   = DateTime::createFromFormat('d/m/Y', $max);
    $datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', $row_update['pDate']);

    $diff_lower = $datetime_lower->diff($datetime_compare);
    $diff_upper = $datetime_upper->diff($datetime_compare);

    if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {
        // date is between min and max, do nothing
    } else {
        // date is not between min and max, update cell colour
$result = mysql_query("UPDATE rent SET colour='F0F0F0' WHERE $datetime_lower < $pDate && $datetime_upper > $pDate") or die(mysql_error());
    }
    }

the logic behind it seems rather rational but whenever i try to run the code i get the error message:

Warning: DateTime::diff() expects parameter 1 to be DateTime, boolean given in C:\xampp\htdocs\keypad\main.php on line 41

Warning: DateTime::diff() expects parameter 1 to be DateTime, boolean given in C:\xampp\htdocs\keypad\main.php on line 42

any idea whats going on?


问:
c# a namespace cannot directly contain members such as fields or methods
Can anyone tell what is wrong here ?
I just create one folder call Models and add new class BaseEntity, and I get error.
Till now I didn't get this error when I add new class...

答:
An identifier cannot start with a number; 3DBool in this case is invalid.

Reference, older but still correct: it must start with either a letter or the underscore character (including or excluding the @ character to disambiguate it with keywords).


问:
Recycler view in first result is different with scrolled design?
everything in my recycler View work fine except this problem that when fragment start, first list that show in recycler View has problem with design and after scrolling it has been correct and repair that ! whats is the reason ?
this is my recycler view adapter :

```<code>        View rootView = inflater.inflate(R.layout.fragment_order_list, container,
            false);

    recyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);

    mAdapter = new MoviesAdapter(movieList);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(mAdapter);

    prepareMovieData();
</code>```

and this it my XML rows for recycler:

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="155dp"
android:layout_marginBottom="10dp"
android:background="@color/WhiteColor"
tools:context="ir.himmel.visitors.himmel.LoginActivity"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="73dp">

<TextView
    android:id="@+id/txt_finalPrice"
    android:layout_width="313dp"
    android:layout_height="26dp"
    android:layout_marginRight="14dp"
    android:layout_marginTop="10dp"
    android:textColor="@color/year"
    app:layout_constraintRight_toLeftOf="@+id/imageView6"
    app:layout_constraintTop_toBottomOf="@+id/txt_TimeOrder"
    tools:text="رقم کل سفارش: ۱۲۰۰۰۰ تومان" />

<TextView
    android:id="@+id/txt_status"
    android:layout_width="76dp"
    android:layout_height="16dp"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="14dp"
    android:textColor="@color/year"
    android:textSize="10sp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/imageView3"
    tools:text="رقم کل سفارش: ۱۲۰۰۰۰ تومان" />

<ImageView
    android:id="@+id/imageView8"
    android:layout_width="23dp"
    android:layout_height="25dp"
    app:srcCompat="@drawable/itemsicon"
    android:layout_marginRight="31dp"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/imageView6" />

<TextView
    android:id="@+id/title"

    android:layout_width="420dp"
    android:layout_height="30dp"
    android:layout_marginRight="31dp"
    android:layout_marginTop="7dp"
    android:textColor="@color/title"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<ImageView
    android:id="@+id/imageView4"
    android:layout_width="23dp"
    android:layout_height="26dp"
    android:layout_marginRight="31dp"
    android:layout_marginTop="43dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/calendaricon" />

<ImageView
    android:id="@+id/imageView6"
    android:layout_width="23dp"
    android:layout_height="25dp"
    android:layout_marginRight="31dp"
    android:layout_marginTop="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/imageView4"
    app:srcCompat="@drawable/pricesicon" />

<TextView
    android:id="@+id/year"
    android:layout_width="313dp"
    android:layout_height="26dp"
    android:textColor="@color/year"
    android:layout_marginTop="10dp"
    app:layout_constraintTop_toBottomOf="@+id/txt_finalPrice"
    app:layout_constraintRight_toLeftOf="@+id/imageView8"
    android:layout_marginRight="15dp" />

<ImageView
    android:id="@+id/imageView3"
    android:layout_width="43dp"
    android:layout_height="36dp"
    android:layout_marginLeft="33dp"
    android:layout_marginTop="73dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/tickicon" />

<TextView
    android:id="@+id/editText2"
    android:layout_width="2dp"
    android:layout_height="90dp"
    android:layout_marginBottom="0dp"
    android:layout_marginLeft="30dp"
    android:layout_marginTop="8dp"
    android:background="@color/GeneralBackGround"
    android:ems="10"
    android:inputType="textPersonName"
    app:layout_constraintBottom_toBottomOf="@+id/imageView3"
    app:layout_constraintLeft_toRightOf="@+id/imageView3"
    app:layout_constraintTop_toTopOf="@+id/imageView3" />

<TextView
    android:id="@+id/txt_TimeOrder"

    android:layout_width="312dp"
    android:layout_height="24dp"
    android:layout_marginRight="14dp"
    android:layout_marginTop="8dp"
    app:layout_constraintRight_toLeftOf="@+id/imageView4"
    app:layout_constraintTop_toBottomOf="@+id/title" />
</code>```

this is result ! why does this behavior ?
as you show in first list result we have problem in design and after scrolling it repair by recycler View !

答:
I also had such a problem once , solved it by adding these methods in the recyclerView adapter. What this does is that it reloads the rows even before it is visible ..</p>

```<code>    @Override
    public void onViewAttachedToWindow(ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        int wPosition = holder.getAdapterPosition();   // if you need the position of current item else ignore..
        /* copy paste whatever you have in your onBindViewHolder method here */
     }

    @Override
    public void onViewRecycled(ViewHolder holder) {
         super.onViewRecycled(holder);
    /* copy paste whatever you have in your onBindViewHolder method here */

     }
</code>```

Body:
everything in my recycler View work fine except this problem that when fragment start, first list that show in recycler View has problem with design and after scrolling it has been correct and repair that ! whats is the reason ?
this is my recycler view adapter :

        View rootView = inflater.inflate(R.layout.fragment_order_list, container,
            false);

    recyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);

    mAdapter = new MoviesAdapter(movieList);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(mAdapter);

    prepareMovieData();

and this it my XML rows for recycler:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="155dp"
android:layout_marginBottom="10dp"
android:background="@color/WhiteColor"
tools:context="ir.himmel.visitors.himmel.LoginActivity"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="73dp">

<TextView
    android:id="@+id/txt_finalPrice"
    android:layout_width="313dp"
    android:layout_height="26dp"
    android:layout_marginRight="14dp"
    android:layout_marginTop="10dp"
    android:textColor="@color/year"
    app:layout_constraintRight_toLeftOf="@+id/imageView6"
    app:layout_constraintTop_toBottomOf="@+id/txt_TimeOrder"
    tools:text="رقم کل سفارش: ۱۲۰۰۰۰ تومان" />

<TextView
    android:id="@+id/txt_status"
    android:layout_width="76dp"
    android:layout_height="16dp"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="14dp"
    android:textColor="@color/year"
    android:textSize="10sp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/imageView3"
    tools:text="رقم کل سفارش: ۱۲۰۰۰۰ تومان" />

<ImageView
    android:id="@+id/imageView8"
    android:layout_width="23dp"
    android:layout_height="25dp"
    app:srcCompat="@drawable/itemsicon"
    android:layout_marginRight="31dp"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/imageView6" />

<TextView
    android:id="@+id/title"

    android:layout_width="420dp"
    android:layout_height="30dp"
    android:layout_marginRight="31dp"
    android:layout_marginTop="7dp"
    android:textColor="@color/title"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<ImageView
    android:id="@+id/imageView4"
    android:layout_width="23dp"
    android:layout_height="26dp"
    android:layout_marginRight="31dp"
    android:layout_marginTop="43dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/calendaricon" />

<ImageView
    android:id="@+id/imageView6"
    android:layout_width="23dp"
    android:layout_height="25dp"
    android:layout_marginRight="31dp"
    android:layout_marginTop="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/imageView4"
    app:srcCompat="@drawable/pricesicon" />

<TextView
    android:id="@+id/year"
    android:layout_width="313dp"
    android:layout_height="26dp"
    android:textColor="@color/year"
    android:layout_marginTop="10dp"
    app:layout_constraintTop_toBottomOf="@+id/txt_finalPrice"
    app:layout_constraintRight_toLeftOf="@+id/imageView8"
    android:layout_marginRight="15dp" />

<ImageView
    android:id="@+id/imageView3"
    android:layout_width="43dp"
    android:layout_height="36dp"
    android:layout_marginLeft="33dp"
    android:layout_marginTop="73dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/tickicon" />

<TextView
    android:id="@+id/editText2"
    android:layout_width="2dp"
    android:layout_height="90dp"
    android:layout_marginBottom="0dp"
    android:layout_marginLeft="30dp"
    android:layout_marginTop="8dp"
    android:background="@color/GeneralBackGround"
    android:ems="10"
    android:inputType="textPersonName"
    app:layout_constraintBottom_toBottomOf="@+id/imageView3"
    app:layout_constraintLeft_toRightOf="@+id/imageView3"
    app:layout_constraintTop_toTopOf="@+id/imageView3" />

<TextView
    android:id="@+id/txt_TimeOrder"

    android:layout_width="312dp"
    android:layout_height="24dp"
    android:layout_marginRight="14dp"
    android:layout_marginTop="8dp"
    app:layout_constraintRight_toLeftOf="@+id/imageView4"
    app:layout_constraintTop_toBottomOf="@+id/title" />

this is result ! why does this behavior ?
as you show in first list result we have problem in design and after scrolling it repair by recycler View !

Body:
I also had such a problem once , solved it by adding these methods in the recyclerView adapter. What this does is that it reloads the rows even before it is visible ..

    @Override
    public void onViewAttachedToWindow(ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        int wPosition = holder.getAdapterPosition();   // if you need the position of current item else ignore..
        /* copy paste whatever you have in your onBindViewHolder method here */
     }

    @Override
    public void onViewRecycled(ViewHolder holder) {
         super.onViewRecycled(holder);
    /* copy paste whatever you have in your onBindViewHolder method here */

     }


答:
you can add a max attribute that will specify the highest possible number that you may insert

```<code><input type="number" max="999" />
</code>```

if you add both a max and a min value you can specify the range of allowed values:

```<code><input type="number" min="1" max="999" />
</code>```

Title: How I set maxLength attribute in <input type='number'> in HTML5?

Body:
I want maxLength Validation in  in HTML5.

I tried like this

<input type="number" name="trainer_mobile_no[]" maxlength="10" class="form-control" required="required"/>

Body:
you can add a max attribute that will specify the highest possible number that you may insert

<input type="number" max="999" />

if you add both a max and a min value you can specify the range of allowed values:

<input type="number" min="1" max="999" />