问:
How can I add a field that count the number of the records retrieved by my query? Why am I obtaining this error message?
I am not so into SQL and I have the following doubt trying to change a query (I am using MySql as DB).

So I have this query:

```<code>SELECT
        MD.id                                                           AS market_id,
        MD.market_name                                                  AS market_name,
        CN.id                                                           AS commodity_details_id,
        CD.commodity_name_en                                            AS commodity_name_en,
        CN.commodity_name                                               AS commodity_name,
        CD.image_link                                                   AS image_link,
        CN.description                                                  AS description,
        MD_CD.id                                                        AS price_serie_id,
        MCPS.avg_price                                                  AS today_avg_price,
        YMCPS.avg_price                                                 AS yesterday_avg_price,

        CASE WHEN MCPS.market_commodity_details_id IS NOT NULL
                THEN
                        MCPS.currency
                ELSE
                        YMCPS.currency
        END AS currency,

        CASE WHEN MCPS.market_commodity_details_id IS NOT NULL
                THEN
                        MCPS.measure_unit
                ELSE
                        YMCPS.measure_unit
                END AS measure_unit

FROM MarketDetails_CommodityDetails AS MD_CD

INNER JOIN MarketDetails AS MD
    ON MD_CD.market_details_id = MD.id

INNER JOIN CommodityDetails as CD
    ON MD_CD.commodity_details_id = CD.id

INNER JOIN CommodityName AS CN
    ON CD.id=CN.commodity_details_id

LEFT JOIN
(
    SELECT
        Market_Commodity_Price_Series.id AS price_series_id,
        market_commodity_details_id
        , avg_price
        , CU.ISO_4217_cod      AS currency
        , MU.unit_name         AS measure_unit
    FROM Market_Commodity_Price_Series
    INNER JOIN MeasureUnit AS MU
    ON Market_Commodity_Price_Series.measure_unit_id = MU.id
    INNER JOIN Currency AS CU
    ON Market_Commodity_Price_Series.currency_id = CU.id
    WHERE price_date = CURDATE()
) AS MCPS
ON MD_CD.id = MCPS.market_commodity_details_id

LEFT JOIN
(
    SELECT
        Market_Commodity_Price_Series.id AS price_series_id,
        market_commodity_details_id
        , avg_price
        , CU.ISO_4217_cod      AS currency
        , MU.unit_name         AS measure_unit
    FROM Market_Commodity_Price_Series
    INNER JOIN MeasureUnit AS MU
    ON Market_Commodity_Price_Series.measure_unit_id = MU.id
    INNER JOIN Currency AS CU
    ON Market_Commodity_Price_Series.currency_id = CU.id
    WHERE price_date = ADDDATE(CURDATE(), -1)
) AS YMCPS
ON MD_CD.id = YMCPS.market_commodity_details_id

WHERE
   MD_CD.commodity_details_id = 4
AND
    MD.localization_id = 2
</code>```

that is returning 2 records like these representing the markets where a specific commodity is sold, something like this:

```<code>market_id            market_name                    commodity_details_id      commodity_name_en            commodity_name        image_link                                                                                description price_serie_id       today_avg_price      yesterday_avg_price  currency measure_unit
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
4                    Tambacounda Market N1          4                         Red onion                    Red onion             https://firebasestorage.googleapis.com/v0/b/blablabla.appspot.com/o/img%2Ficons%2Fagrimarket%2Fcommodity%2Fonion-red.png?alt=media&token=4ec9de4e-6e5a-4198-9bcd-21b692760618              Red onion   24                   20,15                18,94                XOF      kilogram
5                    Tambacounda Market N2          4                         Red onion                    Red onion             https://firebasestorage.googleapis.com/v0/b/blablabla.appspot.com/o/img%2Ficons%2Fagrimarket%2Fcommodity%2Fonion-red.png?alt=media&token=4ec9de4e-6e5a-4198-9bcd-21b692760618              Red onion   28                   13,7                 16,2                 XOF      kilogram
</code>```

Ok I want to add a new field that represents the number of markets in which this commodity is avaiable (basically the number of retrieved records), so I tried to do something like this:

```<code>SELECT
        MD.id                                                           AS market_id,
        MD.market_name                                                  AS market_name,
        count(MD.id)                                                AS market_total_number,
        CN.id                                                           AS commodity_details_id,
        CD.commodity_name_en                                            AS commodity_name_en,
        CN.commodity_name                                               AS commodity_name,
        CD.image_link                                                   AS image_link,
        CN.description                                                  AS description,
        MD_CD.id                                                        AS price_serie_id,
        MCPS.avg_price                                                  AS today_avg_price,
        YMCPS.avg_price                                                 AS yesterday_avg_price,

        CASE WHEN MCPS.market_commodity_details_id IS NOT NULL
                THEN
                        MCPS.currency
                ELSE
                        YMCPS.currency
        END AS currency,

        CASE WHEN MCPS.market_commodity_details_id IS NOT NULL
                THEN
                        MCPS.measure_unit
                ELSE
                        YMCPS.measure_unit
                END AS measure_unit

FROM MarketDetails_CommodityDetails AS MD_CD

INNER JOIN MarketDetails AS MD
    ON MD_CD.market_details_id = MD.id

INNER JOIN CommodityDetails as CD
    ON MD_CD.commodity_details_id = CD.id

INNER JOIN CommodityName AS CN
    ON CD.id=CN.commodity_details_id

LEFT JOIN
(
    SELECT
        Market_Commodity_Price_Series.id AS price_series_id,
        market_commodity_details_id
        , avg_price
        , CU.ISO_4217_cod      AS currency
        , MU.unit_name         AS measure_unit
    FROM Market_Commodity_Price_Series
    INNER JOIN MeasureUnit AS MU
    ON Market_Commodity_Price_Series.measure_unit_id = MU.id
    INNER JOIN Currency AS CU
    ON Market_Commodity_Price_Series.currency_id = CU.id
    WHERE price_date = CURDATE()
) AS MCPS
ON MD_CD.id = MCPS.market_commodity_details_id

LEFT JOIN
(
    SELECT
        Market_Commodity_Price_Series.id AS price_series_id,
        market_commodity_details_id
        , avg_price
        , CU.ISO_4217_cod      AS currency
        , MU.unit_name         AS measure_unit
    FROM Market_Commodity_Price_Series
    INNER JOIN MeasureUnit AS MU
    ON Market_Commodity_Price_Series.measure_unit_id = MU.id
    INNER JOIN Currency AS CU
    ON Market_Commodity_Price_Series.currency_id = CU.id
    WHERE price_date = ADDDATE(CURDATE(), -1)
) AS YMCPS
ON MD_CD.id = YMCPS.market_commodity_details_id

WHERE
   MD_CD.commodity_details_id = 4
AND
    MD.localization_id = 2
</code>```

I simply added this SELECT to the retrievd fields list:

```<code>count(MD.id) AS market_total_number,
</code>```

because my idea is to count the retrieved records, but performing my query now I am obtaining this error message:

```<code>#42000In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'digital_services_DB.MD.id'; this is incompatible with sql_mode=only_full_group_by
</code>```

Why? What is wrong? What am I missing? How can I fix this issue and obtained the desired result?

答:
When using an aggregation function the group by is mandatory.
try this</p>

```<code>SELECT  count(market_id) AS market_total_number,
    market_id,
    market_name,
    market_total_number,
    commodity_details_id,
    commodity_name_en,
    commodity_name,
    image_link,
    description,
    price_serie_id,
    today_avg_price,
    yesterday_avg_price,
    currency ,
    measure_units
FROM (
SELECT
        MD.id                                                           AS market_id,
        MD.market_name                                                  AS market_name,
        count(MD.id)                                                AS market_total_number,
        CN.id                                                           AS commodity_details_id,
        CD.commodity_name_en                                            AS commodity_name_en,
        CN.commodity_name                                               AS commodity_name,
        CD.image_link                                                   AS image_link,
        CN.description                                                  AS description,
        MD_CD.id                                                        AS price_serie_id,
        MCPS.avg_price                                                  AS today_avg_price,
        YMCPS.avg_price                                                 AS yesterday_avg_price,

        CASE WHEN MCPS.market_commodity_details_id IS NOT NULL
                THEN
                        MCPS.currency
                ELSE
                        YMCPS.currency
        END AS currency,

        CASE WHEN MCPS.market_commodity_details_id IS NOT NULL
                THEN
                        MCPS.measure_unit
                ELSE
                        YMCPS.measure_unit
                END AS measure_unit

FROM MarketDetails_CommodityDetails AS MD_CD

INNER JOIN MarketDetails AS MD
    ON MD_CD.market_details_id = MD.id

INNER JOIN CommodityDetails as CD
    ON MD_CD.commodity_details_id = CD.id

INNER JOIN CommodityName AS CN
    ON CD.id=CN.commodity_details_id

LEFT JOIN
(
    SELECT
        Market_Commodity_Price_Series.id AS price_series_id,
        market_commodity_details_id
        , avg_price
        , CU.ISO_4217_cod      AS currency
        , MU.unit_name         AS measure_unit
    FROM Market_Commodity_Price_Series
    INNER JOIN MeasureUnit AS MU
    ON Market_Commodity_Price_Series.measure_unit_id = MU.id
    INNER JOIN Currency AS CU
    ON Market_Commodity_Price_Series.currency_id = CU.id
    WHERE price_date = CURDATE()
) AS MCPS
ON MD_CD.id = MCPS.market_commodity_details_id

LEFT JOIN
(
    SELECT
        Market_Commodity_Price_Series.id AS price_series_id,
        market_commodity_details_id
        , avg_price
        , CU.ISO_4217_cod      AS currency
        , MU.unit_name         AS measure_unit
    FROM Market_Commodity_Price_Series
    INNER JOIN MeasureUnit AS MU
    ON Market_Commodity_Price_Series.measure_unit_id = MU.id
    INNER JOIN Currency AS CU
    ON Market_Commodity_Price_Series.currency_id = CU.id
    WHERE price_date = ADDDATE(CURDATE(), -1)
) AS YMCPS
ON MD_CD.id = YMCPS.market_commodity_details_id

WHERE
   MD_CD.commodity_details_id = 4
AND
    MD.localization_id = 2
) base
group by    market_id,
        market_name,
        market_total_number,
        commodity_details_id,
        commodity_name_en,
        commodity_name,
        image_link,
        description,
        price_serie_id,
        today_avg_price,
        yesterday_avg_price,
        currency ,
        measure_units
</code>```

Body:
I am not so into SQL and I have the following doubt trying to change a query (I am using MySql as DB).

So I have this query:

SELECT
        MD.id                                                           AS market_id,
        MD.market_name                                                  AS market_name,
        CN.id                                                           AS commodity_details_id,
        CD.commodity_name_en                                            AS commodity_name_en,
        CN.commodity_name                                               AS commodity_name,
        CD.image_link                                                   AS image_link,
        CN.description                                                  AS description,
        MD_CD.id                                                        AS price_serie_id,
        MCPS.avg_price                                                  AS today_avg_price,
        YMCPS.avg_price                                                 AS yesterday_avg_price,

        CASE WHEN MCPS.market_commodity_details_id IS NOT NULL
                THEN
                        MCPS.currency
                ELSE
                        YMCPS.currency
        END AS currency,

        CASE WHEN MCPS.market_commodity_details_id IS NOT NULL
                THEN
                        MCPS.measure_unit
                ELSE
                        YMCPS.measure_unit
                END AS measure_unit

FROM MarketDetails_CommodityDetails AS MD_CD

INNER JOIN MarketDetails AS MD
    ON MD_CD.market_details_id = MD.id

INNER JOIN CommodityDetails as CD
    ON MD_CD.commodity_details_id = CD.id

INNER JOIN CommodityName AS CN
    ON CD.id=CN.commodity_details_id

LEFT JOIN
(
    SELECT
        Market_Commodity_Price_Series.id AS price_series_id,
        market_commodity_details_id
        , avg_price
        , CU.ISO_4217_cod      AS currency
        , MU.unit_name         AS measure_unit
    FROM Market_Commodity_Price_Series
    INNER JOIN MeasureUnit AS MU
    ON Market_Commodity_Price_Series.measure_unit_id = MU.id
    INNER JOIN Currency AS CU
    ON Market_Commodity_Price_Series.currency_id = CU.id
    WHERE price_date = CURDATE()
) AS MCPS
ON MD_CD.id = MCPS.market_commodity_details_id

LEFT JOIN
(
    SELECT
        Market_Commodity_Price_Series.id AS price_series_id,
        market_commodity_details_id
        , avg_price
        , CU.ISO_4217_cod      AS currency
        , MU.unit_name         AS measure_unit
    FROM Market_Commodity_Price_Series
    INNER JOIN MeasureUnit AS MU
    ON Market_Commodity_Price_Series.measure_unit_id = MU.id
    INNER JOIN Currency AS CU
    ON Market_Commodity_Price_Series.currency_id = CU.id
    WHERE price_date = ADDDATE(CURDATE(), -1)
) AS YMCPS
ON MD_CD.id = YMCPS.market_commodity_details_id

WHERE
   MD_CD.commodity_details_id = 4
AND
    MD.localization_id = 2

that is returning 2 records like these representing the markets where a specific commodity is sold, something like this:

market_id            market_name                    commodity_details_id      commodity_name_en            commodity_name        image_link                                                                                description price_serie_id       today_avg_price      yesterday_avg_price  currency measure_unit
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
4                    Tambacounda Market N1          4                         Red onion                    Red onion             https://firebasestorage.googleapis.com/v0/b/blablabla.appspot.com/o/img%2Ficons%2Fagrimarket%2Fcommodity%2Fonion-red.png?alt=media&token=4ec9de4e-6e5a-4198-9bcd-21b692760618              Red onion   24                   20,15                18,94                XOF      kilogram
5                    Tambacounda Market N2          4                         Red onion                    Red onion             https://firebasestorage.googleapis.com/v0/b/blablabla.appspot.com/o/img%2Ficons%2Fagrimarket%2Fcommodity%2Fonion-red.png?alt=media&token=4ec9de4e-6e5a-4198-9bcd-21b692760618              Red onion   28                   13,7                 16,2                 XOF      kilogram

Ok I want to add a new field that represents the number of markets in which this commodity is avaiable (basically the number of retrieved records), so I tried to do something like this:

SELECT
        MD.id                                                           AS market_id,
        MD.market_name                                                  AS market_name,
        count(MD.id)                                                AS market_total_number,
        CN.id                                                           AS commodity_details_id,
        CD.commodity_name_en                                            AS commodity_name_en,
        CN.commodity_name                                               AS commodity_name,
        CD.image_link                                                   AS image_link,
        CN.description                                                  AS description,
        MD_CD.id                                                        AS price_serie_id,
        MCPS.avg_price                                                  AS today_avg_price,
        YMCPS.avg_price                                                 AS yesterday_avg_price,

        CASE WHEN MCPS.market_commodity_details_id IS NOT NULL
                THEN
                        MCPS.currency
                ELSE
                        YMCPS.currency
        END AS currency,

        CASE WHEN MCPS.market_commodity_details_id IS NOT NULL
                THEN
                        MCPS.measure_unit
                ELSE
                        YMCPS.measure_unit
                END AS measure_unit

FROM MarketDetails_CommodityDetails AS MD_CD

INNER JOIN MarketDetails AS MD
    ON MD_CD.market_details_id = MD.id

INNER JOIN CommodityDetails as CD
    ON MD_CD.commodity_details_id = CD.id

INNER JOIN CommodityName AS CN
    ON CD.id=CN.commodity_details_id

LEFT JOIN
(
    SELECT
        Market_Commodity_Price_Series.id AS price_series_id,
        market_commodity_details_id
        , avg_price
        , CU.ISO_4217_cod      AS currency
        , MU.unit_name         AS measure_unit
    FROM Market_Commodity_Price_Series
    INNER JOIN MeasureUnit AS MU
    ON Market_Commodity_Price_Series.measure_unit_id = MU.id
    INNER JOIN Currency AS CU
    ON Market_Commodity_Price_Series.currency_id = CU.id
    WHERE price_date = CURDATE()
) AS MCPS
ON MD_CD.id = MCPS.market_commodity_details_id

LEFT JOIN
(
    SELECT
        Market_Commodity_Price_Series.id AS price_series_id,
        market_commodity_details_id
        , avg_price
        , CU.ISO_4217_cod      AS currency
        , MU.unit_name         AS measure_unit
    FROM Market_Commodity_Price_Series
    INNER JOIN MeasureUnit AS MU
    ON Market_Commodity_Price_Series.measure_unit_id = MU.id
    INNER JOIN Currency AS CU
    ON Market_Commodity_Price_Series.currency_id = CU.id
    WHERE price_date = ADDDATE(CURDATE(), -1)
) AS YMCPS
ON MD_CD.id = YMCPS.market_commodity_details_id

WHERE
   MD_CD.commodity_details_id = 4
AND
    MD.localization_id = 2

I simply added this SELECT to the retrievd fields list:

count(MD.id) AS market_total_number,

because my idea is to count the retrieved records, but performing my query now I am obtaining this error message:

#42000In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'digital_services_DB.MD.id'; this is incompatible with sql_mode=only_full_group_by

Why? What is wrong? What am I missing? How can I fix this issue and obtained the desired result?

Body:
When using an aggregation function the group by is mandatory.
try this

SELECT  count(market_id) AS market_total_number,
    market_id,
    market_name,
    market_total_number,
    commodity_details_id,
    commodity_name_en,
    commodity_name,
    image_link,
    description,
    price_serie_id,
    today_avg_price,
    yesterday_avg_price,
    currency ,
    measure_units
FROM (
SELECT
        MD.id                                                           AS market_id,
        MD.market_name                                                  AS market_name,
        count(MD.id)                                                AS market_total_number,
        CN.id                                                           AS commodity_details_id,
        CD.commodity_name_en                                            AS commodity_name_en,
        CN.commodity_name                                               AS commodity_name,
        CD.image_link                                                   AS image_link,
        CN.description                                                  AS description,
        MD_CD.id                                                        AS price_serie_id,
        MCPS.avg_price                                                  AS today_avg_price,
        YMCPS.avg_price                                                 AS yesterday_avg_price,

        CASE WHEN MCPS.market_commodity_details_id IS NOT NULL
                THEN
                        MCPS.currency
                ELSE
                        YMCPS.currency
        END AS currency,

        CASE WHEN MCPS.market_commodity_details_id IS NOT NULL
                THEN
                        MCPS.measure_unit
                ELSE
                        YMCPS.measure_unit
                END AS measure_unit

FROM MarketDetails_CommodityDetails AS MD_CD

INNER JOIN MarketDetails AS MD
    ON MD_CD.market_details_id = MD.id

INNER JOIN CommodityDetails as CD
    ON MD_CD.commodity_details_id = CD.id

INNER JOIN CommodityName AS CN
    ON CD.id=CN.commodity_details_id

LEFT JOIN
(
    SELECT
        Market_Commodity_Price_Series.id AS price_series_id,
        market_commodity_details_id
        , avg_price
        , CU.ISO_4217_cod      AS currency
        , MU.unit_name         AS measure_unit
    FROM Market_Commodity_Price_Series
    INNER JOIN MeasureUnit AS MU
    ON Market_Commodity_Price_Series.measure_unit_id = MU.id
    INNER JOIN Currency AS CU
    ON Market_Commodity_Price_Series.currency_id = CU.id
    WHERE price_date = CURDATE()
) AS MCPS
ON MD_CD.id = MCPS.market_commodity_details_id

LEFT JOIN
(
    SELECT
        Market_Commodity_Price_Series.id AS price_series_id,
        market_commodity_details_id
        , avg_price
        , CU.ISO_4217_cod      AS currency
        , MU.unit_name         AS measure_unit
    FROM Market_Commodity_Price_Series
    INNER JOIN MeasureUnit AS MU
    ON Market_Commodity_Price_Series.measure_unit_id = MU.id
    INNER JOIN Currency AS CU
    ON Market_Commodity_Price_Series.currency_id = CU.id
    WHERE price_date = ADDDATE(CURDATE(), -1)
) AS YMCPS
ON MD_CD.id = YMCPS.market_commodity_details_id

WHERE
   MD_CD.commodity_details_id = 4
AND
    MD.localization_id = 2
) base
group by    market_id,
        market_name,
        market_total_number,
        commodity_details_id,
        commodity_name_en,
        commodity_name,
        image_link,
        description,
        price_serie_id,
        today_avg_price,
        yesterday_avg_price,
        currency ,
        measure_units


来源: stackexchange

问:
MySQL - Get similarity score from where two different rows meet same condition from two columns
What I want to do is generate a similarity percentage amount by comparing a ratings column from one table with the ratings column from another table.

However, this needs to be limited to instances where an id from one table matches an id in another table, is for a specific user and a rating exists in the ratings column from both tables.

For example, table1 has the following columns and data:

```<code>   id   |   rate (out of 10)
=====================
   1    |    8
   2    |    10
   3    |    5
   4    |    4
   5    |    0
   6    |    9
   7    |    8
</code>```

And table2 has the following columns and data:

```<code> movid  |   userid   |   rating (out of 10)
================================
   1    |     3      |    6
   2    |     2      |    10
   3    |     1      |    4
   4    |     3      |    7
   5    |     3      |    6
   6    |     4      |    8
   7    |     3      |    5
</code>```

So lets say I want to use any rows where 'userid' = 3 and compare their 'rating' from table2 to the 'rate' column from table1 where 'rate' > 0 and id/movid from the two tables has the same number.

Using the example above, the results to compare should be limited to:

```<code>   id   |   rate
=====================
   1    |    8
   4    |    4
   7    |    8

 movid  |   userid   |   rating
================================
   1    |     3      |    6
   4    |     3      |    7
   7    |     3      |    5
</code>```

Even though userid 3 had a rating for movid 5 in table2, it had a 0 rate (no rating) for id 5 in table1, so it will not compare those.

This would compare the ratings for each id/movid and then put it into an overall total. As the rating numbers are based on a score out of 10, I'm guessing the best way to determine the similarity percentage is to take the difference between each id/movid, subtract it from 10 to get the percentage number.

For id/movid 1, 'rate' in table1 is 8 and 'rating' in table2 is 6. The difference between those numbers is 2. We subtract 2 from 10, to get 80% similarity score for id/movid 1.

That would need to happen for each comparison and then total it all together.

So by my calculation, the similarity score for id/movid 1, 4 and 7 all combined would be 73% (rounded without decimals).

This total percentage amount is the end result I am trying to achieve. Can anyone help me out? I'm now bald after all of the hair I've pulled out trying to get this to work.

答:
I suppose what you are looking for is:

```<code>SEELCT table1.id, table1.rate, table2.rating
FROM table1 INNER JOIN table2 ON table1.id=table2.movid
WHERE table1.rate>0 AND table2.userid=3
</code>```

A simple INNER join plus filters in where clause to filter userid=3 and to show rates greater than zero

ContentLicense: CC BY-SA 3.0

Body:
What I want to do is generate a similarity percentage amount by comparing a ratings column from one table with the ratings column from another table.

However, this needs to be limited to instances where an id from one table matches an id in another table, is for a specific user and a rating exists in the ratings column from both tables.

For example, table1 has the following columns and data:

   id   |   rate (out of 10)
=====================
   1    |    8
   2    |    10
   3    |    5
   4    |    4
   5    |    0
   6    |    9
   7    |    8

And table2 has the following columns and data:

 movid  |   userid   |   rating (out of 10)
================================
   1    |     3      |    6
   2    |     2      |    10
   3    |     1      |    4
   4    |     3      |    7
   5    |     3      |    6
   6    |     4      |    8
   7    |     3      |    5

So lets say I want to use any rows where 'userid' = 3 and compare their 'rating' from table2 to the 'rate' column from table1 where 'rate' > 0 and id/movid from the two tables has the same number.

Using the example above, the results to compare should be limited to:

   id   |   rate
=====================
   1    |    8
   4    |    4
   7    |    8

 movid  |   userid   |   rating
================================
   1    |     3      |    6
   4    |     3      |    7
   7    |     3      |    5

Even though userid 3 had a rating for movid 5 in table2, it had a 0 rate (no rating) for id 5 in table1, so it will not compare those.

This would compare the ratings for each id/movid and then put it into an overall total. As the rating numbers are based on a score out of 10, I'm guessing the best way to determine the similarity percentage is to take the difference between each id/movid, subtract it from 10 to get the percentage number.

For id/movid 1, 'rate' in table1 is 8 and 'rating' in table2 is 6. The difference between those numbers is 2. We subtract 2 from 10, to get 80% similarity score for id/movid 1.

That would need to happen for each comparison and then total it all together.

So by my calculation, the similarity score for id/movid 1, 4 and 7 all combined would be 73% (rounded without decimals).

This total percentage amount is the end result I am trying to achieve. Can anyone help me out? I'm now bald after all of the hair I've pulled out trying to get this to work.

Body:
I suppose what you are looking for is:

SEELCT table1.id, table1.rate, table2.rating
FROM table1 INNER JOIN table2 ON table1.id=table2.movid
WHERE table1.rate>0 AND table2.userid=3

A simple INNER join plus filters in where clause to filter userid=3 and to show rates greater than zero


问:
How can I run script automatically after Docker container startup
I'm using Search Guard plugin to secure an elasticsearch cluster composed of multiple nodes.
Here is my Dockerfile:

```<code>#!/bin/sh
FROM docker.elastic.co/elasticsearch/elasticsearch:5.6.3

USER root

# Install search guard
RUN bin/elasticsearch-plugin install --batch com.floragunn:search-guard-5:5.6.3-16 \
    && chmod +x \
        plugins/search-guard-5/tools/hash.sh \
        plugins/search-guard-5/tools/sgadmin.sh \
        bin/init_sg.sh \
    && chown -R elasticsearch:elasticsearch /usr/share/elasticsearch

USER elasticsearch
</code>```

To initialize SearchGuard (create internal users and assign roles). I need to run the script init_sg.sh after the container startup.
Here is the problem: Unless elasticsearch is running, the script will not initialize any security index.

The script's content is :

```<code>sleep 10
plugins/search-guard-5/tools/sgadmin.sh -cd config/ -ts config/truststore.jks -ks config/kirk-keystore.jks -nhnv -icl
</code>```

Now, I just run the script manually after the container startup but since I'm running it on Kubernetes.. Pods may get killed or fail and get recreated automatically for some reason. In this case, the plugin have to be initialized automatically after the container startup!

So how to accomplish this? Any help or hint would be really appreciated.

答: The image itself has an entrypoint ENTRYPOINT ["/run/entrypoint.sh"] specified in the Dockerfile. You can replace it by your own script. So for example create a new script, mount it and first call /run/entrypoint.sh and then wait for start of elasticsearch before running your init_sg.sh.

Body:
I'm using Search Guard plugin to secure an elasticsearch cluster composed of multiple nodes.
Here is my Dockerfile:

#!/bin/sh
FROM docker.elastic.co/elasticsearch/elasticsearch:5.6.3

USER root

# Install search guard
RUN bin/elasticsearch-plugin install --batch com.floragunn:search-guard-5:5.6.3-16 \
    && chmod +x \
        plugins/search-guard-5/tools/hash.sh \
        plugins/search-guard-5/tools/sgadmin.sh \
        bin/init_sg.sh \
    && chown -R elasticsearch:elasticsearch /usr/share/elasticsearch

USER elasticsearch

To initialize SearchGuard (create internal users and assign roles). I need to run the script init_sg.sh after the container startup.
Here is the problem: Unless elasticsearch is running, the script will not initialize any security index.

The script's content is :

sleep 10
plugins/search-guard-5/tools/sgadmin.sh -cd config/ -ts config/truststore.jks -ks config/kirk-keystore.jks -nhnv -icl

Now, I just run the script manually after the container startup but since I'm running it on Kubernetes.. Pods may get killed or fail and get recreated automatically for some reason. In this case, the plugin have to be initialized automatically after the container startup!

So how to accomplish this? Any help or hint would be really appreciated.

ContentLicense: CC BY-SA 4.0


问:
Does NSView have a backgroundColor? If it does, I can't find it
I'm seeing all over the place online where people are referring to NSView's backgroundColor. I need to set a custom backgroundColor to my NSView, but I'm not seeing that property. I can't see it in code, or in IB. I am unable to set the background color of my simple NSView.

What could I be missing?

答:
Strangely enough NSView does not provide this (sigh). I use one consistent class I wrote myself throughout all my macOs projects. Just change the CustomView class in the Identity Inspector tab in IB to ColorView. You will then be able to set the background color in the Attribute Inspector, just like you would for a UIView. Here's the code, hope this helps!</p>

```<code>import Cocoa

class ColorView: NSView
{
    @IBInspectable var backgroundColor:NSColor?

    required init?(coder decoder: NSCoder)
    {
        super.init(coder: decoder)
        wantsLayer = true
    }

    override init(frame frameRect: NSRect)
    {
        super.init(frame: frameRect)
        wantsLayer = true
    }

    override func layout()
    {
        layer?.backgroundColor = backgroundColor?.cgColor
    }
}
</code>```

Body:
Strangely enough NSView does not provide this (sigh). I use one consistent class I wrote myself throughout all my macOs projects. Just change the CustomView class in the Identity Inspector tab in IB to ColorView. You will then be able to set the background color in the Attribute Inspector, just like you would for a UIView. Here's the code, hope this helps!

import Cocoa

class ColorView: NSView
{
    @IBInspectable var backgroundColor:NSColor?

    required init?(coder decoder: NSCoder)
    {
        super.init(coder: decoder)
        wantsLayer = true
    }

    override init(frame frameRect: NSRect)
    {
        super.init(frame: frameRect)
        wantsLayer = true
    }

    override func layout()
    {
        layer?.backgroundColor = backgroundColor?.cgColor
    }
}


问:
set focus on particular element with keyboard keys using javascript or jquery
Suppose I have 10 texboxes in one page & want to get focus of particular texbox by just pressing particular key on keyboard. Is it possible?</p>

答: Yes, Listen to keyboard events, just call $("#item_id").focus() inside your keyevent handler


问:
Cakephp 3.3 - How to remove nested level when join table
I'm using CakePHP 3.3 and try to get data by join table

```<code>$this->find()
->select([
    'TableA.id',
    'TableA.user_id',
    'TableA.note',
    'TableB.log_date'
])
->where([
    'TableA.user_id' => $userId
])
->join([
    'table' => 'table_b',
    'alias' => 'TableB',
    'conditions' => 'TableA.table_b_id = TableB.id',
]);
</code>```

I try to var_dump() result var_dump($result->toArray());die;
My array display like this:

```<code>    "data": [
    {
        "id": 1317,
        "user_id": 331,
        "note": "Take note",
        "TableB": {
            "log_date": "2017-11-16"
        }
      },
      {
        "id": 1318,
        "user_id": 331,
        "note": "Take note",
        "TableB": {
            "log_date": "2017-11-16"
        }
      }
  ],
</code>```

My result has nested in TableB. How I can remove nested and display like this:

```<code>    "data": [
      {
        "id": 1317,
        "user_id": 331,
        "note": "Take note",
        "log_date": "2017-11-16"
      },
      {
        "id": 1318,
        "user_id": 331,
        "note": "Take note",
        "log_date": "2017-11-16"
      }
   ],
</code>```

Could I get all data in same level in array? Thanks for reading!

答:
You can make alias for joined fields by using associative keys in select()

```<code>$result = $this
    ->Articles
    ->find()
    ->select([
        'Articles.id',
        'user_id' => 'users.id'
    ])
    ->join([
        'table' => 'users',
        'conditions' => 'users.id = Articles.user_id'
    ])
    ->toArray();
</code>```

The sample of result:

```<code>[{"id":26,"user_id":2},{"id":27,"user_id":2}]
</code>```

Body:
I'm using CakePHP 3.3 and try to get data by join table

$this->find()
->select([
    'TableA.id',
    'TableA.user_id',
    'TableA.note',
    'TableB.log_date'
])
->where([
    'TableA.user_id' => $userId
])
->join([
    'table' => 'table_b',
    'alias' => 'TableB',
    'conditions' => 'TableA.table_b_id = TableB.id',
]);

I try to var_dump() result var_dump($result->toArray());die;
My array display like this:

    "data": [
    {
        "id": 1317,
        "user_id": 331,
        "note": "Take note",
        "TableB": {
            "log_date": "2017-11-16"
        }
      },
      {
        "id": 1318,
        "user_id": 331,
        "note": "Take note",
        "TableB": {
            "log_date": "2017-11-16"
        }
      }
  ],

My result has nested in TableB. How I can remove nested and display like this:

    "data": [
      {
        "id": 1317,
        "user_id": 331,
        "note": "Take note",
        "log_date": "2017-11-16"
      },
      {
        "id": 1318,
        "user_id": 331,
        "note": "Take note",
        "log_date": "2017-11-16"
      }
   ],

Could I get all data in same level in array? Thanks for reading!

Body:
You can make alias for joined fields by using associative keys in select()

$result = $this
    ->Articles
    ->find()
    ->select([
        'Articles.id',
        'user_id' => 'users.id'
    ])
    ->join([
        'table' => 'users',
        'conditions' => 'users.id = Articles.user_id'
    ])
    ->toArray();

The sample of result:

[{"id":26,"user_id":2},{"id":27,"user_id":2}]


问:
stuck in pandas if loop all() any()?
I try to write some basic functions and found me know completely stuck in a quite simple problem regarding the use of if elif else on python pandas dataframe. Here is an example:
dummy data:

```<code>d = {'x': [1, 2, 0, -2, -2], 'y': [3, 4, 5, 4, -4]}
df = pd.DataFrame(data=d)
</code>```

my function:

```<code>def cart2sph(data):  #ceval indicates using numerical expressions
    newDF = pd.DataFrame()
    x = data['x'].astype(float)
    y = data['y'].astype(float)
    if (x == 0).all():
      newDF['angle'] = sign(y)* pi / 2
    else:
      newDF['angle'] = arctan(y/x)
    if (x < 0 and y >= 0).all():
      newDF['angle'] += pi
    elif (x < 0 and y < 0).all():
      newDF['angle'] -= pi
    return newDF
</code>```

I always get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in cart2sph
  File "C:\Users\tpotrusil\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\generic.py", line 955, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

...and can´t see the problem!?!

Very thankful for any help!

答:
Try to replace
(x < 0 and y >= 0).all()
by
(x < 0).all() and (y >= 0).all()

Title: stuck in pandas if loop all() any()?

Body:
I try to write some basic functions and found me know completely stuck in a quite simple problem regarding the use of if elif else on python pandas dataframe. Here is an example:
dummy data:

d = {'x': [1, 2, 0, -2, -2], 'y': [3, 4, 5, 4, -4]}
df = pd.DataFrame(data=d)

my function:

def cart2sph(data):  #ceval indicates using numerical expressions
    newDF = pd.DataFrame()
    x = data['x'].astype(float)
    y = data['y'].astype(float)
    if (x == 0).all():
      newDF['angle'] = sign(y)* pi / 2
    else:
      newDF['angle'] = arctan(y/x)
    if (x < 0 and y >= 0).all():
      newDF['angle'] += pi
    elif (x < 0 and y < 0).all():
      newDF['angle'] -= pi
    return newDF

I always get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in cart2sph
  File "C:\Users\tpotrusil\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\generic.py", line 955, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

...and can´t see the problem!?!

Very thankful for any help!


答:
you can also overwrite the loader styles in "src/theme/variables.scss" e.g.</p>

```<code>    ion-loading {
        ion-backdrop {
            background-color: white !important;
        }
        .loading-wrapper {
            justify-content: center !important;
            opacity: 0.8 !important;
            background-color: white !important;
            width: 100% !important;
            height: 100% !important;
            max-width: 100% !important;
            max-height: 100% !important;
        }

        .spinner-crescent circle {
            stroke: green !important;
        }

        .spinner-ios line,
        .spinner-ios-small line {
            stroke: green !important;
        }
    }
</code>```

Title: Ionic 2 custom svg spinner in loader

Body:
I am trying to add my SVG to the loading create function but when I go to view it all I see is an empty tag where it should be.

let loading = this.loadingCtrl.create({spinner: ' ',
            content: this.appConfig.customSpinner })

Above is my create code and that variable is hte code below for the SVG.

<svg id="Layer_3" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2419 1188.4">
   <defs>
    <mask id="mask">
       <path fill="#000" d="M570.2 87.3L163.8 322c-15.6 9-25.2 25.6-25.2 43.6v469.3c0 18 9.6 34.6 25.2 43.6l406.4 234.7c15.6 9 34.7 9 50.3 0l406.4-234.7c15.6-9 25.2-25.6 25.2-43.6V365.6c0-18-9.6-34.6-25.2-43.6L620.5 87.3c-15.5-8.9-34.7-8.9-50.3 0z"/>

  <path fill="#000" d="M787.4 474.6V343.5H394.2v505.6h131V661.8h262.2v-131H525.2v-56.2z"/>
  <path fill="#000" d="M581.4 718h206v131.1h-206z"/>

    <circle fill="#fff" cx="0" cy="1450" r="551.3"/>
    </mask>
  </defs>

 <path id="background" mask="url(#mask)" fill="#F16E18" d="M570.2 87.3L163.8 322c-15.6 9-25.2 25.6-25.2 43.6v469.3c0 18 9.6 34.6 25.2 43.6l406.4 234.7c15.6 9 34.7 9 50.3 0l406.4-234.7c15.6-9 25.2-25.6 25.2-43.6V365.6c0-18-9.6-34.6-25.2-43.6L620.5 87.3c-15.5-8.9-34.7-8.9-50.3 0z"/>

  <path class="letter" mask="url(#mask)" fill="#fff" d="M787.4 474.6V343.5H394.2v505.6h131V661.8h262.2v-131H525.2v-56.2z"/>
  <path class="letter" mask="url(#mask)" fill="#fff" d="M581.4 718h206v131.1h-206z"/>

  <path  id="hexagon-2" stroke="transparent" class="st2" d="M570.1 82.5L163.7 317.2c-15.6 9-25.2 25.6-25.2 43.6v469.3c0 18 9.6 34.6 25.2 43.6l406.4 234.7c15.6 9 34.7 9 50.3 0l406.4-234.7c15.6-9 25.2-25.6 25.2-43.6V360.8c0-18-9.6-34.6-25.2-43.6L620.4 82.5c-15.5-8.9-34.7-8.9-50.3 0z"/>

    <path  id="hexagon-1" stroke="transparent" class="st2" d="M570.1 82.5L163.7 317.2c-15.6 9-25.2 25.6-25.2 43.6v469.3c0 18 9.6 34.6 25.2 43.6l406.4 234.7c15.6 9 34.7 9 50.3 0l406.4-234.7c15.6-9 25.2-25.6 25.2-43.6V360.8c0-18-9.6-34.6-25.2-43.6L620.4 82.5c-15.5-8.9-34.7-8.9-50.3 0z"/>

</svg>

How can I get it to render? I have also replicated it to the ionic forum on this link

I have tried to add a pipe that will make it safe in run time but that also fails.

I made the content this:

And this is my pipe:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'safe'})
export class SafeHtml {
  constructor(private sanitizer:DomSanitizer){}

  transform(html:any):any {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

I have also tried with using a file:

let loading = this.loadingCtrl.create({spinner: 'hide', content:"<object data='assets/spinner.svg' type='image/svg+xml'></object>"})

This still causes the same issue.

NB**

After changing my code I realised that you cannot assign the return value from the sanitizer inside the variable but rather a declared variable in the class. One I did this I no longer got the TS type error and the svg XML loaded.

Body:
you can also overwrite the loader styles in "src/theme/variables.scss" e.g.

    ion-loading {
        ion-backdrop {
            background-color: white !important;
        }
        .loading-wrapper {
            justify-content: center !important;
            opacity: 0.8 !important;
            background-color: white !important;
            width: 100% !important;
            height: 100% !important;
            max-width: 100% !important;
            max-height: 100% !important;
        }

        .spinner-crescent circle {
            stroke: green !important;
        }

        .spinner-ios line,
        .spinner-ios-small line {
            stroke: green !important;
        }
    }


问:
when using CNN ,to_categorical()wrong
use CNN for handwritten digit.

答:
Without any code it's not easy to help but in Keras > 2.0 the parameters for to_categorial are y and num_classes but it seems that you are trying to pass nb_classes instead.

For more details please check the api documentation.
https://keras.io/utils/#to_categorical

Title: when using CNN ,to_categorical()wrong

Body: use CNN for handwritten digit.


问:
how to add uipickerview with uibutton programmaticaly in iphone
Im new to iPhone development.Now im doing application in that i want to add pickerview with button without using IB.Here i added pickerview and button programmaticaly in iphone.But When i run this application in pickerview I added some names that was not showing.It was showing only empty pickerview and when i click button the pickerview displayed in top of the view not in down.I searched in all sites but there is no data for this pickerview with button.I added pickerview view in uiaction sheet and i declared pickerview.

Can any one plz give code for this uipickerview with uibutton programmaticaly in iphone.

Thank you in advance.

答:
Have you add in main view..?
Like [self.view addSubview:???];</p>

ContentLicense: CC BY-SA 2.5


问:
Reference instance variables or method call within a class
When using instance variables within a class, is there any advantage to directly referencing the instance variable versus using a getter? Which is more commonly seen?

Example using method calls:

```<code>public double howMuchFreeSpace() {
    return getCapacity() - getVolume();
</code>```

Example referencing instance variables:

```<code>public double howMuchFreeSpace() {
    return this.capacity - this.volume;
</code>```

答: It's usually matter of preference inside a class. Direct referencing is more readable IMHO. So I suggest using direct referencing unless you need to execute some code when getting the value - that may be a reason to use getter.</p>

Body:
When using instance variables within a class, is there any advantage to directly referencing the instance variable versus using a getter? Which is more commonly seen?

Example using method calls:

public double howMuchFreeSpace() {
    return getCapacity() - getVolume();

Example referencing instance variables:

public double howMuchFreeSpace() {
    return this.capacity - this.volume;


问:
Assign JavaScript var from Smarty in Prestashop 1.6
I'm trying to define a JS variable which gets it's value from a smarty variable..

This is what I've done in my PHP controller:

```<code>public function hookDisplayBackOfficeHeader()
{
  $this->context->controller->addJS($this->_path.'js/bo_setup.js', 'all');
}
</code>```

I'm declaring the variable on a separate function:

```<code>    private function _loadTestInfo()
    {
      $this->context->smarty->assign(array(
         'test_username' => 'myuser',
            ));
    }
</code>```

and calling it from the getContent() function:

```<code>{
  $output = '';
 ....
$this->output .= $this->display(__FILE__, '/views/templates/admin/back_office.tpl');
$this->_loadTestInfo();
$this->output .= $this->renderForm();
return $this->output;
}
</code>```

my bo_setup.js function looks like this:

```<code>var test_username = "{$test_username}";
document.getElementById('username').value = test_username;
</code>```

However, running the page gives the 'username' variable the value of "{$test_username}" instead of the "myuser" value.

any clues?

答:
For accessing variables in JavaScript you can assign them in your controllers with:

```<code>Media::addJsDef(array('mymodule' => array('test_username' => 'Your name')));
$this->context->controller->addJS($this->_path.'myscript.js')
</code>```

Then you can use them in your JavaScript or through console:

```<code>let var1 = mymodule.test_username;
</code>```

Body:
I'm trying to define a JS variable which gets it's value from a smarty variable..

This is what I've done in my PHP controller:

public function hookDisplayBackOfficeHeader()
{
  $this->context->controller->addJS($this->_path.'js/bo_setup.js', 'all');
}

I'm declaring the variable on a separate function:

    private function _loadTestInfo()
    {
      $this->context->smarty->assign(array(
         'test_username' => 'myuser',
            ));
    }

and calling it from the getContent() function:

{
  $output = '';
 ....
$this->output .= $this->display(__FILE__, '/views/templates/admin/back_office.tpl');
$this->_loadTestInfo();
$this->output .= $this->renderForm();
return $this->output;
}

my bo_setup.js function looks like this:

var test_username = "{$test_username}";
document.getElementById('username').value = test_username;

However, running the page gives the 'username' variable the value of "{$test_username}" instead of the "myuser" value.

any clues?

Body:
For accessing variables in JavaScript you can assign them in your controllers with:

Media::addJsDef(array('mymodule' => array('test_username' => 'Your name')));
$this->context->controller->addJS($this->_path.'myscript.js')

Then you can use them in your JavaScript or through console:

let var1 = mymodule.test_username;


问:
VBA powerpoint Strikethrough of a single word
I have a powerpoint file with several sheets. On this sheets are text fields with texts. Some of the words are strikethrough. I would like to make a list of all the slides where a word exists which is strike through.
I tried to use the function:
If  objShape.TextFrame2.TextRange.Font.Strikethrough = True Then

Problem is that is only get true when the first word is strike through. So
Hallo jaja the function works.
Hallo jaja  function does not work
Does anybody have a solution for this?

答:
Try .TextRange2 instead of .TextRange with Font.Strikethrough :

Example:

```<code>Sub ST()
    With ActiveWindow.Selection
        .TextRange2.Font.Strikethrough = msoTrue
        .TextRange2.Font.Fill.ForeColor.RGB = vbRed
    End With
End Sub
</code>```

Below is an (incomplete) list of differences in handling of the two property types:

```<code>| TextRange Property    | TextRange Return Type | TextRange2 Property                        | TextRange2 Return Type |
|-----------------------|-----------------------|--------------------------------------------|------------------------|
| ActionSettings        | ActionSettings        | －                                         | －                     |
| Application           | Application           | Application                                | Application            |
| BoundHeight           | Single                | BoundHeight                                | Single                 |
| BoundLeft             | Single                | BoundLeft                                  | Single                 |
| BoundTop              | Single                | BoundTop                                   | Single                 |
| BoundWidth            | Single                | BoundWidth                                 | Single                 |
| （Characters method）   | （TextRange）           | Characters                                 | TextRange2             |
| Count                 | Long                  | Count                                      | Long                   |
| －                    | －                    | Creator                                    | Long                   |
| Font                  | Font                  | Font                                       | Font2                  |
| IndentLevel           | Long                  | （Paragraph Format2 .IndentLevel propety）   | （Long)                |
| LanguageID            | Mso LanguageID        | LanguageID                                 | Mso LanguageID         |
| Length                | Long                  | Length                                     | Long                   |
| （Lines method）        | （TextRange）           | Lines                                      | TextRange2             |
| －                    | －                    | MathZones                                  | TextRange2             |
| Paragraph Format      | Paragraph Format      | Paragraph Format                           | Paragraph Format2      |
| （Paragraphs method）   | （TextRange）           | Paragraphs                                 | TextRange2             |
| Parent                | Object                | Parent                                     | Object                 |
| （Runs method）         | （TextRange）           | Runs                                       | TextRange2             |
| （Sentences method）    | （TextRange）           | Sentences                                  | TextRange2             |
| Start                 | Long                  | Start                                      | Long                   |
| Text                  | String                | Text                                       | String                 |
| （Words method）        | （TextRange）           | Words                                      | TextRange2             |
|                       |                       |                                            |                        |
</code>```

More information:

PowerPoint VBA: TextRange and TextRange2 Properties and Methods List

Powerpoint text/link strikethrough or black out

Body:
Try .TextRange2 instead of .TextRange with Font.Strikethrough :

Example:

Sub ST()
    With ActiveWindow.Selection
        .TextRange2.Font.Strikethrough = msoTrue
        .TextRange2.Font.Fill.ForeColor.RGB = vbRed
    End With
End Sub

Below is an (incomplete) list of differences in handling of the two property types:

| TextRange Property    | TextRange Return Type | TextRange2 Property                        | TextRange2 Return Type |
|-----------------------|-----------------------|--------------------------------------------|------------------------|
| ActionSettings        | ActionSettings        | －                                         | －                     |
| Application           | Application           | Application                                | Application            |
| BoundHeight           | Single                | BoundHeight                                | Single                 |
| BoundLeft             | Single                | BoundLeft                                  | Single                 |
| BoundTop              | Single                | BoundTop                                   | Single                 |
| BoundWidth            | Single                | BoundWidth                                 | Single                 |
| （Characters method）   | （TextRange）           | Characters                                 | TextRange2             |
| Count                 | Long                  | Count                                      | Long                   |
| －                    | －                    | Creator                                    | Long                   |
| Font                  | Font                  | Font                                       | Font2                  |
| IndentLevel           | Long                  | （Paragraph Format2 .IndentLevel propety）   | （Long)                |
| LanguageID            | Mso LanguageID        | LanguageID                                 | Mso LanguageID         |
| Length                | Long                  | Length                                     | Long                   |
| （Lines method）        | （TextRange）           | Lines                                      | TextRange2             |
| －                    | －                    | MathZones                                  | TextRange2             |
| Paragraph Format      | Paragraph Format      | Paragraph Format                           | Paragraph Format2      |
| （Paragraphs method）   | （TextRange）           | Paragraphs                                 | TextRange2             |
| Parent                | Object                | Parent                                     | Object                 |
| （Runs method）         | （TextRange）           | Runs                                       | TextRange2             |
| （Sentences method）    | （TextRange）           | Sentences                                  | TextRange2             |
| Start                 | Long                  | Start                                      | Long                   |
| Text                  | String                | Text                                       | String                 |
| （Words method）        | （TextRange）           | Words                                      | TextRange2             |
|                       |                       |                                            |                        |

More information:

PowerPoint VBA: TextRange and TextRange2 Properties and Methods List

Powerpoint text/link strikethrough or black out


答:
When you want to create a select with aggregation functions like count and also retrieve any field, you have to use group by.

You can read more about it in:
https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html

So if you add this at the end of your query it will work.

```<code>GROUP BY
MD.id
,MD.market_name
,CN.id
,CD.commodity_name_en
,CN.commodity_name
,CD.image_link
,CN.description
,MD_CD.id
,MCPS.avg_price
,YMCPS.avg_price
</code>```

Title: How can I add a field that count the number of the records retrieved by my query? Why am I obtaining this error message?

Body:
When you want to create a select with aggregation functions like count and also retrieve any field, you have to use group by.

You can read more about it in:
https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html

So if you add this at the end of your query it will work.

GROUP BY
MD.id
,MD.market_name
,CN.id
,CD.commodity_name_en
,CN.commodity_name
,CD.image_link
,CN.description
,MD_CD.id
,MCPS.avg_price
,YMCPS.avg_price


问:
Datatable Angular 4
[ANGULAR 4 - ts]
I'm using the metronic theme and its datatable comes from a remote location this way:

```<code>var DatatableJsonRemoteDemo = function () {
//== Private functions

// basic demo
var demo = function () {

    var datatable = $('.m_datatable').mDatatable({
        // datasource definition
        data: {
            type: 'remote',
            source: 'http://localhost/ci/api/Users',
            pageSize: 10,
            saveState: {
                cookie: true,
                webstorage: true
            }
        },
</code>```

But my API uses a heaader where I have to pass a KEY, how can I do that to fit this request to a key? And where can I by a console.log to see my return? PS: step via post Thanks

答:
I'm using Metronic with Angular v5.0.5.
In order to create a Datatable from a remote location you need to,

import the Service that gets the key you need

import { KeyService } from '../path.to.services/key.service';

Then call it in the component constructor

constructor (private _keyService:KeyService) {}

In the ngOnInit() hook, create your array of options, (I will focus only on the data part)

```<code>let options = {
      data: {
        type: 'remote',
        source: {
            read: {
              url: 'http://your_API_URL.com',
              method: 'POST',
              headers: { 'Key': this._keyService.getKey()},
            }
        },
        pageSize: 10,
        saveState: {
          cookie: true,
          webstorage: true
        }
      }
</code>```

and create your datatable with

let yourdatatable = (<any>$('#TheIdDataTable')).mDatatable(options);

Notes :

If you want to use the GET method you need to have at least the 5.0.4 version of Metronic because before the POST method was hardcoded in the theme. See this

To use a console.log just put it anywhere you want in the constructor or ngOnInit hook.

If you just want to see the return of you API request just go in the network section of your navigator console, filter the request by XHR and fetch and find the one corresponding to your datatable (something like users?datatable%5Bquery%5D=)

in order to display your results you may need to map them with a function, I invite you to read the Metronic Documentation and look for the data.source.read.map part.

Good luck !

Title: Datatable Angular 4

Body:
[ANGULAR 4 - ts]
I'm using the metronic theme and its datatable comes from a remote location this way:

var DatatableJsonRemoteDemo = function () {
//== Private functions

// basic demo
var demo = function () {

    var datatable = $('.m_datatable').mDatatable({
        // datasource definition
        data: {
            type: 'remote',
            source: 'http://localhost/ci/api/Users',
            pageSize: 10,
            saveState: {
                cookie: true,
                webstorage: true
            }
        },

But my API uses a heaader where I have to pass a KEY, how can I do that to fit this request to a key? And where can I by a console.log to see my return? PS: step via post Thanks

Body:
I'm using Metronic with Angular v5.0.5.
In order to create a Datatable from a remote location you need to,

import the Service that gets the key you need

import { KeyService } from '../path.to.services/key.service';

Then call it in the component constructor

constructor (private _keyService:KeyService) {}

In the ngOnInit() hook, create your array of options, (I will focus only on the data part)

let options = {
      data: {
        type: 'remote',
        source: {
            read: {
              url: 'http://your_API_URL.com',
              method: 'POST',
              headers: { 'Key': this._keyService.getKey()},
            }
        },
        pageSize: 10,
        saveState: {
          cookie: true,
          webstorage: true
        }
      }

and create your datatable with

let yourdatatable = (<any>$('#TheIdDataTable')).mDatatable(options);

Notes :

If you want to use the GET method you need to have at least the 5.0.4 version of Metronic because before the POST method was hardcoded in the theme. See this

To use a console.log just put it anywhere you want in the constructor or ngOnInit hook.

If you just want to see the return of you API request just go in the network section of your navigator console, filter the request by XHR and fetch and find the one corresponding to your datatable (something like users?datatable%5Bquery%5D=)

in order to display your results you may need to map them with a function, I invite you to read the Metronic Documentation and look for the data.source.read.map part.

Good luck !


问:
Why doesn't git fetch update local branch?
I have the following scenario:

I have my remote branch equal to my local branch. Then I made some changes in the remote branch and some different changes in my local branch.

My idea is to run git fetch, to sync my local branch, then check the differences, and then push everything, but it simply doesn't work! (git fetch seems to not get the changes made in the remote branch before)
I know running git pull "fixes" this, or git push -f but I want to review the changes before commit.

Why doesn't git fetch work as expected? Or how can I otherwise review the differences before commit?

答:
git fetch downloads commits from the remote branch, but doesn't update your workspace. You won't see the commits until they are merged into your local branch.

git pull is a combination of git fetch and git merge - this is why git pull appears to "fix" this behaviour.


问:
Unpause d3.timer
I'm really new in d3, so maybe this question is too silly, but...
I want to create a globe, that rotate by itself and by user.
When user rotate the globe, it paused its own rotation, and after that resume it.

I tried to use mouse events, but it didn't work out.
So, I have smth like this:

```<code>timer = d3.timer(function() {
var dt = Date.now() - time;
projection.rotate([rotate[0] + velocity[0] * dt, 0]);
feature.attr("d", path);
});

//Drag
var drag = d3.drag().subject(function() {
    var r = projection.rotate();
    return {
  x: λ.invert(r[0]),
  y: φ.invert(r[1])
};

 }).on("drag", function() {
stopGlobe();
projection.rotate([λ(d3.event.x), φ(d3.event.y)]);
feature.attr("d", path);
});

svg.call(drag);
</code>```

Also, I heard about .off, but don't understand, how I can it use there.
And I have this globe on codepen ->
https://codepen.io/bramsis/pen/QOPXej

Can you help me with this?

答:
First make a function start globe;

```<code>function startGlobe() {
      var r = projection.rotate()[0];//old state
      var k = projection.rotate()[1];//old state
      time = Date.now();
      timer.restart(function() {
        var dt = Date.now() - time;
        projection.rotate([r + velocity[0] * dt, k]);
        feature.attr("d", path);
      });
    }
</code>```

On drag end call startGlobe function declared above.

```<code>.on("end", function () {
        startGlobe();
      });
</code>```

working code here

Title: Unpause d3.timer

Body:
I'm really new in d3, so maybe this question is too silly, but...
I want to create a globe, that rotate by itself and by user.
When user rotate the globe, it paused its own rotation, and after that resume it.

I tried to use mouse events, but it didn't work out.
So, I have smth like this:

timer = d3.timer(function() {
var dt = Date.now() - time;
projection.rotate([rotate[0] + velocity[0] * dt, 0]);
feature.attr("d", path);
});

//Drag
var drag = d3.drag().subject(function() {
    var r = projection.rotate();
    return {
  x: λ.invert(r[0]),
  y: φ.invert(r[1])
};

 }).on("drag", function() {
stopGlobe();
projection.rotate([λ(d3.event.x), φ(d3.event.y)]);
feature.attr("d", path);
});

svg.call(drag);

Also, I heard about .off, but don't understand, how I can it use there.
And I have this globe on codepen ->
https://codepen.io/bramsis/pen/QOPXej

Can you help me with this?

Body:
First make a function start globe;

function startGlobe() {
      var r = projection.rotate()[0];//old state
      var k = projection.rotate()[1];//old state
      time = Date.now();
      timer.restart(function() {
        var dt = Date.now() - time;
        projection.rotate([r + velocity[0] * dt, k]);
        feature.attr("d", path);
      });
    }

On drag end call startGlobe function declared above.

.on("end", function () {
        startGlobe();
      });

working code here


问:
SVG CSS keyframe animation with transform issue (<text> and <rect>)
I'm Working on a (simple) loading image made in SVG with some CSS animations.
It works fine on Chrome and Firefox, but I can't seem to make it work on Safari.

Is this a Safari (11.0.1) thing, or is there something I'm missing? A simple SVG rectangle animates fine, but text does nothing...

If someone could help it would be much appreciated.

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 21.0.2, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 1400 300" style="enable-background:new 0 0 100 100;" xml:space="preserve">
    <style>
        .oeps {
            font-family: 'SketchRockwell', 'Sketch Block', sans-serif;
            font-size: 120px;
        }
        .balk {
            -webkit-animation: vallen 1s ease-in-out infinite;
            animation: vallen 1s ease-in-out infinite;
        }
        .tekst1 {
                -webkit-animation: vallen 1s ease-in-out infinite;
                animation: vallen 1s ease-in-out infinite;
            }
        @keyframes vallen {
            0% { transform: translate(0px, 0px)}
            50% { transform: translate(20px, 0px)}
            100% { transform: translate(0px, 200px)}
        }
    </style>
    <rect x="0" y="0" width="1400" height="340" fill="rgb(227,6,19)"/>
    <g class="oeps" style="transform: translate(700px, 60px);">
        <text class="tekst1" x="-200" y="120" fill="white">O</text>
        <rect class="balk" x="-200" y="80" width="75" height="4" fill="#ffffff" stroke="#494949"/>
    </g>
</svg>
</code>```

答:
I see you are using the prefixed version of the animation CSS property: -webkit-animation.  When you do that, you also need to use the prefixed version of @keyframes:

```<code>@-webkit-keyframes vallen {
   ..etc..
}
</code>```

Now I'm not sure whether the Safari version you are using supports the unprefixed version of these properties or not, but try it. Perhaps that's your problem.

Body:
I'm Working on a (simple) loading image made in SVG with some CSS animations.
It works fine on Chrome and Firefox, but I can't seem to make it work on Safari.

Is this a Safari (11.0.1) thing, or is there something I'm missing? A simple SVG rectangle animates fine, but text does nothing...

If someone could help it would be much appreciated.

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 1400 300" style="enable-background:new 0 0 100 100;" xml:space="preserve">

    <rect x="0" y="0" width="1400" height="340" fill="rgb(227,6,19)"/>
    <g class="oeps" style="transform: translate(700px, 60px);">
        <text class="tekst1" x="-200" y="120" fill="white">O</text>
        <rect class="balk" x="-200" y="80" width="75" height="4" fill="#ffffff" stroke="#494949"/>
    </g>
</svg>

Body:
I see you are using the prefixed version of the animation CSS property: -webkit-animation.  When you do that, you also need to use the prefixed version of @keyframes:

@-webkit-keyframes vallen {
   ..etc..
}

Now I'm not sure whether the Safari version you are using supports the unprefixed version of these properties or not, but try it. Perhaps that's your problem.


问:
how to identify the questions in the email body
I am new to the deep learning, I am solving the problem below:

I want to identify the questions present in the email body and give the text/answers suggestions for the questions present in the email.

I felt this is a question and auto answer problem, will seq2seq model will work for this type of problems?

if seq2seq will work how will I feed the data, please suggest any useful link.

答:
I see you tagged machine-learning, but i dont think it is the right tool for the job. Try regex:

```<code>import re

questions = re.findall(r"[^.?!]*?\?", text)
</code>```

Example:

```<code>text = """
Dear Mr. Jameson,

I hope you are well, and that all is running smoothly at ABC Company. I miss everyone in the marketing division!

I am writing to ask if you would feel comfortable providing a positive letter of reference for me? If you are able to attest to my qualifications for employment, and the skills I attained while I was employed at ABC Company, I would sincerely appreciate it.

I am in the process of seeking a new position as a marketing manager.

Do you have any questions, or do you want a meeting in person?

I have attached an updated resume. Don’t hesitate ask for any other materials you think would be helpful.

I can be reached at jdickinson@gmail.com or (111) 111-1234. Random question?

Thank you for your consideration, and I look forward to hearing from you.

Regards,

Jane Dickinson
"""

import re

questions = re.findall(r"[^.?!]*?\?", text)

for q in questions:
    q = q.replace("\n", "")
    print(q)
</code>```

Returns:

```<code>I am writing to ask if you would feel comfortable providing a positive letter of reference for me?
Do you have any questions, or do you want a meeting in person?
 Random question?
</code>```

Google has a nice crashcourse on Regular Expressions:
https://developers.google.com/edu/python/regular-expressions

Body:
I see you tagged machine-learning, but i dont think it is the right tool for the job. Try regex:

import re

questions = re.findall(r"[^.?!]*?\?", text)

Example:

text = """
Dear Mr. Jameson,

I hope you are well, and that all is running smoothly at ABC Company. I miss everyone in the marketing division!

I am writing to ask if you would feel comfortable providing a positive letter of reference for me? If you are able to attest to my qualifications for employment, and the skills I attained while I was employed at ABC Company, I would sincerely appreciate it.

I am in the process of seeking a new position as a marketing manager.

Do you have any questions, or do you want a meeting in person?

I have attached an updated resume. Don’t hesitate ask for any other materials you think would be helpful.

I can be reached at jdickinson@gmail.com or (111) 111-1234. Random question?

Thank you for your consideration, and I look forward to hearing from you.

Regards,

Jane Dickinson
"""

import re

questions = re.findall(r"[^.?!]*?\?", text)

for q in questions:
    q = q.replace("\n", "")
    print(q)

Returns:

I am writing to ask if you would feel comfortable providing a positive letter of reference for me?
Do you have any questions, or do you want a meeting in person?
 Random question?

Google has a nice crashcourse on Regular Expressions:
https://developers.google.com/edu/python/regular-expressions


问:
Query to remove all non-digit but only keep last period/dot
Struggle to design a regular expression to filter field value from varchar2 to number, so that it can remove all non-digit and only left the last period in the string, so that

```<code>"about 1,000.00" return 1000.00 or 1000
"3,000,000.000" return 300000.000 or 3000000
"3.000.000.000" return return 3000000.000 or 3000000
"a^*3^%*(C4.5d*9" return 34.59
</code>```

Any method just change the string into accurate convertible string that can be converted by to_number()

I use

```<code>SELECT REGEXP_REPLACE(field_value, '[^0-9\.]+', '') from dual;
</code>```

but can't resolve the 3rd case....

答:
Shortest way is as follows:

```<code>select regexp_substr('a^*3^%*(C4.5d*9s','\d+\.\d+') from dual;
</code>```

or

```<code>select regexp_replace('a^*3^%*(C4.5d*9s', '[^0.0-9]', '') from dual;
</code>```

Body:
Struggle to design a regular expression to filter field value from varchar2 to number, so that it can remove all non-digit and only left the last period in the string, so that

"about 1,000.00" return 1000.00 or 1000
"3,000,000.000" return 300000.000 or 3000000
"3.000.000.000" return return 3000000.000 or 3000000
"a^*3^%*(C4.5d*9" return 34.59

Any method just change the string into accurate convertible string that can be converted by to_number()

I use

SELECT REGEXP_REPLACE(field_value, '[^0-9\.]+', '') from dual;

but can't resolve the 3rd case....

Body:
Shortest way is as follows:

select regexp_substr('a^*3^%*(C4.5d*9s','\d+\.\d+') from dual;

or

select regexp_replace('a^*3^%*(C4.5d*9s', '[^0.0-9]', '') from dual;


问:
How to bypass socket?
I have installed a streaming server "Lighttpd" (light-tpd) which runs on port 81.

I have a C program that listens to http requests on port 80 using a server socket created by socket api.

I want that as soon as I get a request on the port 80 from a client I forward that to the streaming server and the remaining conversation takes place b/w the Streaming Server and client & they bypass my C program completely.

The problem is client would be expecting msgs from socket at port 80 (i.e from the socket of my C program) since it had sent request to port 80 only rather than from the Streaming server which gives service on port 81.
can anyone help me out on this issue of bypassing the socket on port 80 for replying to the client.

Solution I think: my program can be a middle man...It will forward the request to port 81 of streaming server and when it get replies from there it forwards them to the client...but bypassing would be efficient and I don't know how to do that. Please help me out.

Thanks in advance

答: Why put your C program in front? Lighttpd is designed to act as a frontend proxy (among other uses), so you can put lighttpd in front and use its mod_proxy_core to pass requests to your C program. You can use X-Rewrite and/or X-Sendfile to pass requests back to Lighttpd after doing some processing inside your application.</p>

Title: How to bypass socket?


问:
Angular Post array results in all NULL in database
I am trying to post data to my table (T-SQL/Azure) but all it writes is NULL and just one line, not even the complete array. I have tried numerous variations of the $param, serialize, $httpParamSerializer etc. none of them write the contents inside the table. Even tho the console.log tells me all is ok.

```<code>var data = $scope.test;
console.log(data);
var jsonData = angular.toJson(data);
console.log(jsonData)
var objectToSerialize = { 'object': jsonData };
console.log(objectToSerialize);

$http({
     url: 'http://url/api/UserOrderProductList',
     method: "POST",
     data: $.param(objectToSerialize),
     //data: $.param(data),
     //data: $.param(jsonData),
     //data: $httpParamSerializerJQLike(objectToSerialize),

     headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
     //headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }

      }).success(function (data) {
            alert("done");
      });
</code>```

this is what i am writing:

```<code>    var data = {
        "quantity": 0,
        "title": "string",
        "imageFront": "string"
        }
</code>```

with the same matching table.

in the debugger is get the 201 created and the form-data of the complete array

Form Data from Headers:

```<code>object:[{"count":1,"title":"Lara croft",imageFront":"20170807234015"},
{"count":1,"title":"Dragon Age","imageFront":"20170807231312"},
{"count":2,"title":"Madden","imageFront":"20170807235148"}]
</code>```

This is what is says in the Preview/Response:

```<code>{"id":16,"count":null,"imageFront":null,"title":null}
</code>```

This is the backend section, how the request is recieved:

```<code>  // POST: api/UserOrders
  [ResponseType(typeof(UserOrderProductList))]
  public async Task<IHttpActionResult> PostUserOrderProductList(UserOrderProductList UserOrderProductList)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.UserOrderProductLists.Add(UserOrderProductList);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = UserOrderProductList.id }, UserOrderProductList);
    }
</code>```

what is going on and why does it all write NULL?
When i am writing with swagger is all turns out fine.

答:
Try setting Content-Type to application/json and passing JSON data to your Web API:

```<code>var data = $scope.test;
var jsonData = angular.toJson(data);

$http({
    url: 'http://url/api/UserOrderProductList',
    method: "POST",
    data: jsonData,
    headers: { 'Content-Type': 'application/json' }

}).success(function (data) {
    alert("done");
});
</code>```

And the parameter of the Web API should be a List rather than an Object:

```<code>// POST: api/UserOrders
[ResponseType(typeof(UserOrderProductList))]
public async Task<IHttpActionResult> PostUserOrderProductList(List<UserOrderProductList> userOrderProductLists)
{
    //...
}
</code>```

A similar question is answered here: Web Api 2 receive json array.

Body:
I am trying to post data to my table (T-SQL/Azure) but all it writes is NULL and just one line, not even the complete array. I have tried numerous variations of the $param, serialize, $httpParamSerializer etc. none of them write the contents inside the table. Even tho the console.log tells me all is ok.

var data = $scope.test;
console.log(data);
var jsonData = angular.toJson(data);
console.log(jsonData)
var objectToSerialize = { 'object': jsonData };
console.log(objectToSerialize);

$http({
     url: 'http://url/api/UserOrderProductList',
     method: "POST",
     data: $.param(objectToSerialize),
     //data: $.param(data),
     //data: $.param(jsonData),
     //data: $httpParamSerializerJQLike(objectToSerialize),

     headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
     //headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }

      }).success(function (data) {
            alert("done");
      });

this is what i am writing:

    var data = {
        "quantity": 0,
        "title": "string",
        "imageFront": "string"
        }

with the same matching table.

in the debugger is get the 201 created and the form-data of the complete array

Form Data from Headers:

object:[{"count":1,"title":"Lara croft",imageFront":"20170807234015"},
{"count":1,"title":"Dragon Age","imageFront":"20170807231312"},
{"count":2,"title":"Madden","imageFront":"20170807235148"}]

This is what is says in the Preview/Response:

{"id":16,"count":null,"imageFront":null,"title":null}

This is the backend section, how the request is recieved:

  // POST: api/UserOrders
  [ResponseType(typeof(UserOrderProductList))]
  public async Task<IHttpActionResult> PostUserOrderProductList(UserOrderProductList UserOrderProductList)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.UserOrderProductLists.Add(UserOrderProductList);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = UserOrderProductList.id }, UserOrderProductList);
    }

what is going on and why does it all write NULL?
When i am writing with swagger is all turns out fine.

Body:
Try setting Content-Type to application/json and passing JSON data to your Web API:

var data = $scope.test;
var jsonData = angular.toJson(data);

$http({
    url: 'http://url/api/UserOrderProductList',
    method: "POST",
    data: jsonData,
    headers: { 'Content-Type': 'application/json' }

}).success(function (data) {
    alert("done");
});

And the parameter of the Web API should be a List rather than an Object:

// POST: api/UserOrders
[ResponseType(typeof(UserOrderProductList))]
public async Task<IHttpActionResult> PostUserOrderProductList(List<UserOrderProductList> userOrderProductLists)
{
    //...
}

A similar question is answered here: Web Api 2 receive json array.


问:
Jquery autocomplete from json data
i have country related data stored as json. i want to show country name from that json array. i use jquery autocomplete. this is my code which i tried but not working. give me some hint that where is the mistake.

```<code><input type="text" class="form-control" id="plugins" name="plugins" />

var myData =[
    {"name": "Afghanistan"},
    {"name": "Åland Islands"},
    {"name": "Albania"},
    {"name": "Algeria"},
    {"name": "American Samoa"},
    {"name": "Bahamas"},
    {"name": "Bahrain"},
    {"name": "Bangladesh"},
    {"name": "Barbados"},
    {"name": "Belarus"},
    {"name": "Belgium"},
    {"name": "Belize"},
    {"name": "Benin"},
    {"name": "Cambodia"},
    {"name": "Cameroon"},
    {"name": "Canada"},
    {"name": "Cape Verde"},
    {"name": "Cayman Islands"},
    {"name": "Viet Nam"},
    {"name": "Virgin Islands, British"},
    {"name": "Virgin Islands, U.S."},
    {"name": "Wallis and Futuna"},
    {"name": "Western Sahara"},
    {"name": "Yemen"},
    {"name": "Zambia"},
    {"name": "Zimbabwe"}
]

$(function() {
  $("#plugins").autocomplete({
    source: function(req, resp) {
      var results = [];
      $.each(myData, function(k, v) {
        // Make a pass for names
        if (v.name.indexOf(req.term) != -1) {
          results.push(v);
          return;
        }
      });
      resp(results);
    }
  });
});
</code>```

here is jsfiddle version https://jsfiddle.net/urtkxo46/2/

this is working version of jsfiddle https://jsfiddle.net/durga598/urtkxo46/5/

答:
According to the docs: [http://api.jqueryui.com/autocomplete/]

The result of the response function needs to be an array of strings, or an array of objects with label and value properties.  You're returning an array of objects with a "name" property.

results.push(v) should be results.push(v.name) and then it'll be an array of strings so should work.

Title: Jquery autocomplete from json data

Body:
i have country related data stored as json. i want to show country name from that json array. i use jquery autocomplete. this is my code which i tried but not working. give me some hint that where is the mistake.

<input type="text" class="form-control" id="plugins" name="plugins" />

var myData =[
    {"name": "Afghanistan"},
    {"name": "Åland Islands"},
    {"name": "Albania"},
    {"name": "Algeria"},
    {"name": "American Samoa"},
    {"name": "Bahamas"},
    {"name": "Bahrain"},
    {"name": "Bangladesh"},
    {"name": "Barbados"},
    {"name": "Belarus"},
    {"name": "Belgium"},
    {"name": "Belize"},
    {"name": "Benin"},
    {"name": "Cambodia"},
    {"name": "Cameroon"},
    {"name": "Canada"},
    {"name": "Cape Verde"},
    {"name": "Cayman Islands"},
    {"name": "Viet Nam"},
    {"name": "Virgin Islands, British"},
    {"name": "Virgin Islands, U.S."},
    {"name": "Wallis and Futuna"},
    {"name": "Western Sahara"},
    {"name": "Yemen"},
    {"name": "Zambia"},
    {"name": "Zimbabwe"}
]

$(function() {
  $("#plugins").autocomplete({
    source: function(req, resp) {
      var results = [];
      $.each(myData, function(k, v) {
        // Make a pass for names
        if (v.name.indexOf(req.term) != -1) {
          results.push(v);
          return;
        }
      });
      resp(results);
    }
  });
});

here is jsfiddle version https://jsfiddle.net/urtkxo46/2/

this is working version of jsfiddle https://jsfiddle.net/durga598/urtkxo46/5/


问:
Maven - setup project from Nexus
On the maven Nexus all artifacts (including sources) are published, but can I also get the project from the Nexus so I can recompile the source code in my IDE? I need this to make a single change in the code but I can't find the source code anywhere on the internet, only the artifacts (including xyz-sources.jar) on the Nexus.</p>

答: The projects are not stored in Nexus. If you are lucky, the pom contains the meta information of the git or svn path. Then you can checkout from there. Alternatively, you can use the pom and the unpacked sources to construct a compilable project (I may miss additional files and resources, though).</p>

Title: Maven - setup project from Nexus


问:
What is the relation between `Fabric`, `Composer`, `Cello` and other Hyperledger applications?
When I was tasting the fabric, I found many other blockchain projects, like Composer, Cello, Explorer. They are all belong to Hyperledger. I'm very confused that there are so many projects. Should I learn all of them? It seems each project plays a role in the blockchain. BUT:

What's the relation between them?

I draw a picture to explain my question. The picture is not correct, I just want to make my question clear.

If I figure it out, when we want to use the blockchain in our project, I can just study few of them, and use them appropriately.

答:
Fabric provides a framework to set up a blockchain network. It is data/application agnostic.

Composer provides a set of tools to define a business network on top of Fabric. This provides a higher level of abstraction than Fabric where the data are essentially just bits. With Composer you can define assets, transactions, etc.

Cello helps with provisioning of the network.

Explorer simply provides a web based interface to explore what's on a blockchain.


问:
Can I use font-awesome without downloading?
For some simple html pages I want to use Fontaweseome without downloading it at all.

I was thinking to have my CSS to point to the /fontFace like this:

(i.e.: directly to the github URL)

```<code>@font-face {
  font-family: 'FontAwesome';
  src: url('http://fortawesome.github.io/Font-Awesome/assets/font-awesome/font/fontawesome-webfont.eot?v=3.2.1');
  src: url('http://fortawesome.github.io/Font-Awesome/assets/font-awesome/font/fontawesome-webfont.eot?#iefix&v=3.2.1') format('embedded-opentype'), url('http://fortawesome.github.io/Font-Awesome/assets/font-awesome/font/fontawesome-webfont.woff?v=3.2.1') format('woff'), url('http://fortawesome.github.io/Font-Awesome/assets/font-awesome/font/fontawesome-webfont.ttf?v=3.2.1') format('truetype'), url('http://fortawesome.github.io/Font-Awesome/assets/font-awesome/font/fontawesome-webfont.svg#fontawesomeregular?v=3.2.1') format('svg');
  font-weight: normal;
  font-style: normal;
}
</code>```

which I did ... but it does not seem to work.

No errors yet something like this:

```<code> <i class="icon-bar"></i>
</code>```

where

```<code>  <style>
  i { font-family: 'FontAwesome', sans-serif; }
  </style>
</code>```

is not rendered as expected

答:
You can use Font Awesome CDN embed code! Get it here:

http://fontawesome.io/get-started/

Maybe this option was not available in the time of asking this question.

Body:
For some simple html pages I want to use Fontaweseome without downloading it at all.

I was thinking to have my CSS to point to the /fontFace like this:

(i.e.: directly to the github URL)

@font-face {
  font-family: 'FontAwesome';
  src: url('http://fortawesome.github.io/Font-Awesome/assets/font-awesome/font/fontawesome-webfont.eot?v=3.2.1');
  src: url('http://fortawesome.github.io/Font-Awesome/assets/font-awesome/font/fontawesome-webfont.eot?#iefix&v=3.2.1') format('embedded-opentype'), url('http://fortawesome.github.io/Font-Awesome/assets/font-awesome/font/fontawesome-webfont.woff?v=3.2.1') format('woff'), url('http://fortawesome.github.io/Font-Awesome/assets/font-awesome/font/fontawesome-webfont.ttf?v=3.2.1') format('truetype'), url('http://fortawesome.github.io/Font-Awesome/assets/font-awesome/font/fontawesome-webfont.svg#fontawesomeregular?v=3.2.1') format('svg');
  font-weight: normal;
  font-style: normal;
}

which I did ... but it does not seem to work.

No errors yet something like this:

where

is not rendered as expected


问:
ArrayList - Is it better to clear a List or Reinitialize it?
Which is the best practice between

ArrayList.clear();

new ArrayList<Object>();

I have a list which gets data, I use them and then I have to recycle it.
Which is the best way?

答:
I think if u just clear it its 1 less object for GC to handle, so its better.

I dont see any actual advantage on creating a new array list object if not changing the type.


问:
Improve Frame rate on too many UI Images - Unity UI
In my single page, there were so many textures those I require to render before I was just facing problem in just screen opening but this I was able to resolve this suggestion:

OnBecomeVisible for Canvas UI Objects

Here is the actual code that I used for this purpose:

```<code>public void OnValueChangeRefreshCards (Vector2 valueChange)
{
    elapsedYDist += valueChange.y;

    if (elapsedYDist > 3f) {
        elapsedYDist = 0f;
        for (int i = 0; i < GameConstants.TOTAL_ROSE_COUNT; i++) {
            Card card = roseList [i].GetComponent<Card> ();

            if (RendererExtensions.IsVisibleFrom (card.MyRectTransform, Camera.main))
                card.roseImage.enabled = true;
            else
                card.roseImage.enabled = false;
        }
    }
}
</code>```

But now I started too much framerate lose related issue so even scrolling of page become really difficult for me.
Please check the attached video for more clearance about the issue, I was facing.
NameThatRose - Low Frame Rate

Please give me some suggestions for next improvements.

EDIT: Here are my profiler output.

Detailed Deep Profiler

Overview Deep Profiler

答:
You can try few things to find out whats causing the low fps.

Use profiler to deep profile to find out which UI call is taking more time. Like what I did here.
As Image inherits from UIMaskableGraphics, it calls MaskableGraphics.OnEnable() every frame for every image in your list. This takes up time which you can see here:

I believe your OnValueChanged method is called every frame this would only multiply the enable/disable iterations and its processing time. You can limit the call by some time, processing 4 times a second for example.

```<code>float timeSinceLastUpdate = 0;

void Update()
{
    timeSinceLastUpdate += Time.deltaTime;
}

public void OnValueChangeRefreshCards (Vector2 valueChange)
{
    if(timeSinceLastUpdate < 0.25f)
    {
        return;
    }
    timeSinceLastUpdate = 0;

    // do your stuff here...
}
</code>```

You have 250+ images to process every frame which is a big deal for older Android devices, again as MaskableGraphics.OnEnable() call can be the culprit. You can avoid changing the state if it is required:

```<code>if (RendererExtensions.IsVisibleFrom (card.MyRectTransform, Camera.main))
{
    if(!card.roseImage.enalbed)
        card.roseImage.enabled = true;
}
else
{
    if(card.roseImage.enalbed)
        card.roseImage.enabled = false;
}
</code>```

Furthermore, following are some helpful links to optimize UI in Unity:

Some of the best optimization tips for Unity UI

Tantzy Games

Gemserk

Other UI Optimization Techniques and Tips

A guide to optimizing Unity UI

UPDATE:

The following blog provides more information about UI rendering:

Making the UI Backend Faster

Hope this helps :)

Body:
In my single page, there were so many textures those I require to render before I was just facing problem in just screen opening but this I was able to resolve this suggestion:

OnBecomeVisible for Canvas UI Objects

Here is the actual code that I used for this purpose:

public void OnValueChangeRefreshCards (Vector2 valueChange)
{
    elapsedYDist += valueChange.y;

    if (elapsedYDist > 3f) {
        elapsedYDist = 0f;
        for (int i = 0; i < GameConstants.TOTAL_ROSE_COUNT; i++) {
            Card card = roseList [i].GetComponent<Card> ();

            if (RendererExtensions.IsVisibleFrom (card.MyRectTransform, Camera.main))
                card.roseImage.enabled = true;
            else
                card.roseImage.enabled = false;
        }
    }
}

But now I started too much framerate lose related issue so even scrolling of page become really difficult for me.
Please check the attached video for more clearance about the issue, I was facing.
NameThatRose - Low Frame Rate

Please give me some suggestions for next improvements.

EDIT: Here are my profiler output.

Detailed Deep Profiler

Overview Deep Profiler

Body:
You can try few things to find out whats causing the low fps.

Use profiler to deep profile to find out which UI call is taking more time. Like what I did here.
As Image inherits from UIMaskableGraphics, it calls MaskableGraphics.OnEnable() every frame for every image in your list. This takes up time which you can see here:

I believe your OnValueChanged method is called every frame this would only multiply the enable/disable iterations and its processing time. You can limit the call by some time, processing 4 times a second for example.

float timeSinceLastUpdate = 0;

void Update()
{
    timeSinceLastUpdate += Time.deltaTime;
}

public void OnValueChangeRefreshCards (Vector2 valueChange)
{
    if(timeSinceLastUpdate < 0.25f)
    {
        return;
    }
    timeSinceLastUpdate = 0;

    // do your stuff here...
}

You have 250+ images to process every frame which is a big deal for older Android devices, again as MaskableGraphics.OnEnable() call can be the culprit. You can avoid changing the state if it is required:

if (RendererExtensions.IsVisibleFrom (card.MyRectTransform, Camera.main))
{
    if(!card.roseImage.enalbed)
        card.roseImage.enabled = true;
}
else
{
    if(card.roseImage.enalbed)
        card.roseImage.enabled = false;
}

Furthermore, following are some helpful links to optimize UI in Unity:

Some of the best optimization tips for Unity UI

Tantzy Games

Gemserk

Other UI Optimization Techniques and Tips

A guide to optimizing Unity UI

UPDATE:

The following blog provides more information about UI rendering:

Making the UI Backend Faster

Hope this helps :)


问:
NSFetchedResultsController - KVO, UITableView and a "Tree"
I'm using a NSFetchedResultsController to implement KVO for my UITableView (which is obvious). What I can't figure out is, how to use multiple Entities - sort of a tree structure - to be present(ed) simultaneously.

Here is my setup:

Entity1

DisplayName

RelationToEntity2

Entity2

DisplayName

Now I can fetch the data of either to be presented - so far so good. What I want is to have a one-sectioned TableView (like a flattened view) with the following structure:

Entity1 (Entry 1)

Entity2 (Entry 1)

Entity2 (Entry 2)

…

Entity1 (Entry 2)

…

Though it might look like a thing to be done via sections, it's not. Both Entities should be a UITableViewCells. Can someone please point me the right direction to flatten the without loosing the actual hierarchy.

答:
It sounds like you need to maintain your own 'flattened' datasource. Perhaps the following will work:

When NSFetchedResultController tells you a new Entity1 has been inserted, you insert Entity1 and its associated Entity2s into say, _flattenedArray so it looks like this:

[<Entity1>, <related Entity2>, <related Entity2>...]

Where you insert them is up to you - it pretty much comes down to:

construct a subarray containing the new Entity1 and associated Entity2 objects

decide where in _flattenedArray to insert the new subarray.

call reloadData or some other means to inform the tableView of the new data

When an Entity1 object is removed, remove it and all subsequent Entity2 objects until you encounter the end of _flattenedArray or run into another Entity1 object. This assumes Entity2 is never a "top level" object. If it is you will need to only remove those Entity2 objects in the relation.

When an Entity1 object gains or loses an Entity2 object, you can first delete the Entity1 object from _flattenedArray then reinserting it. If this is too efficient, do a merge instead.


问:
App developed in Xcode for native iOS
We have our native iOS app developed in Xcode and now software developer is saying that we should upgrade our code to Xcode 9 as we may face issue with the new release on the App Store if we continue using Xcode for development. I would like to know if this is a fact, since I am not from iOS development and I don't know if this is a fact.

Any help in this regarding or a pointer to documentation would be appreciated.

答:
Apple releases a new version of Xcode every year, while it also removes the functionality in iTunes Connect to upload builds from older Xcode versions. So, to be brief, your developer is right!

Source: App Store - Submissions

Title: App developed in Xcode for native iOS