问:
Need help to improve MYSQL SubQuery Performance
I just learning MYSQL, I have MySql subquery like this:

```<code>EXPLAIN EXTENDED SELECT brand_name, stars, hh_stock, hh_stock_value, sales_monthly_1, sales_monthly_2, sales_monthly_3, sold_monthly_1, sold_monthly_2,
  sold_monthly_3, price_uvp, price_ecp, price_default, price_margin AS margin, vc_percent as vc, cogs, products_length, products_id, material_expenses,
  MAX(price) AS products_price, SUM(total_sales) AS total_sales,
  IFNULL(MAX(active_age), DATEDIFF(NOW(), products_date_added)) AS products_age, DATEDIFF(NOW(), products_date_added) AS jng_products_age,
  AVG(sales_weekly) AS sales_weekly, AVG(sales_monthly) AS sales_monthly, SUM(total_sold) AS total_sold, SUM(total_returned) AS total_returned,
  ((SUM(total_returned)/SUM(total_sold)) * 100) AS returned_rate
FROM
  (
    SELECT p.products_id, jc.price, jc.price_end_customer AS price_ecp, jc.total_sales, jc.active_age, jc.sales_weekly,
      jc.sales_monthly, jc.total_sold, jc.total_returned, jc.price_uvp, p.price_margin, p.vc_percent, p.material_expenses,
      p.products_date_added, p.stars , pb.brand_name, p.family_id, p.products_price_default AS price_default, pl.sales_monthly_1,
      pl.sales_monthly_2, pl.sales_monthly_3, pl.sold_monthly_1, pl.sold_monthly_2, pl.sold_monthly_3, pst.stock AS hh_stock,
      (pst.stock * p.average_stock_value) AS hh_stock_value, pnc.products_length,
      IF(ploc.cogs IS NULL OR ploc.cogs=0,
         (CASE p.complexity
          WHEN 'F' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2),2)
          WHEN 'E' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2),2)
          WHEN 'N' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2),2)
          WHEN 'M' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2),2)
          WHEN 'I' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2),2)
          WHEN 'H' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2),2)
          ELSE ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+5+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+5+0.25+2.2),2) END), ploc.cogs) AS cogs
    FROM products p
      LEFT  JOIN jng_sp_catalog jc ON  jc.products_id=p.products_id
      LEFT JOIN products_description pd ON pd.products_id = p.products_id AND pd.language_id = 2
      LEFT JOIN products_description2 pd2 ON pd2.products_id = p.products_id
      LEFT JOIN products_brand pb ON pb.products_brand_id = p.products_brand_id
      LEFT JOIN products_log pl ON pl.products_id = p.products_id
      LEFT JOIN products_log_static pls ON pls.products_id=p.products_id
      LEFT JOIN products_local ploc ON ploc.products_id = p.products_id
      LEFT JOIN products_non_configurator pnc ON pnc.products_id = p.products_id
      INNER JOIN
      (
        SELECT shp.products_id, CONCAT(',', GROUP_CONCAT(shp.styles_id), ',') AS styles_id
        FROM styles_has_products shp GROUP BY shp.products_id HAVING styles_id NOT LIKE '%,1967,%') subquery_styles ON subquery_styles.products_id = p.products_id
      LEFT JOIN products_stock_temp pst ON pst.products_id=p.products_id WHERE p.active_status='1'  AND p.categories_top_id  =  '1') dt  GROUP BY products_id ORDER BY  products_id;
</code>```

The result of explain is like this:

```<code>+----+-------------+------------+------------+--------+---------------------+-------------+---------+------------------------------------+--------+----------+----------------------------------------------+
| id | select_type | table      | partitions | type   | possible_keys       | key         | key_len | ref                                | rows   | filtered | Extra                                        |
+----+-------------+------------+------------+--------+---------------------+-------------+---------+------------------------------------+--------+----------+----------------------------------------------+
|  1 | PRIMARY     | p          | NULL       | ALL    | PRIMARY             | NULL        | NULL    | NULL                               |  40458 |     1.00 | Using where; Using temporary; Using filesort |
|  1 | PRIMARY     | pb         | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_brand_id |      1 |   100.00 | NULL                                         |
|  1 | PRIMARY     | ploc       | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | NULL                                         |
|  1 | PRIMARY     | pl         | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using where                                  |
|  1 | PRIMARY     | pls        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using index                                  |
|  1 | PRIMARY     | pst        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | NULL                                         |
|  1 | PRIMARY     | pd2        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using index                                  |
|  1 | PRIMARY     | pnc        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using where                                  |
|  1 | PRIMARY     | pd         | NULL       | eq_ref | PRIMARY             | PRIMARY     | 8       | manobo_central.p.products_id,const |      1 |   100.00 | Using index                                  |
|  1 | PRIMARY     | jc         | NULL       | ref    | products_id         | products_id | 4       | manobo_central.p.products_id       |      4 |   100.00 | Using where                                  |
|  1 | PRIMARY     | <derived3> | NULL       | ref    | <auto_key0>         | <auto_key0> | 4       | manobo_central.p.products_id       |     10 |   100.00 | Using where                                  |
|  3 | DERIVED     | shp        | NULL       | index  | PRIMARY,products_id | PRIMARY     | 8       | NULL                               | 208226 |   100.00 | Using index; Using filesort                  |
+----+-------------+------------+------------+--------+---------------------+-------------+---------+------------------------------------+--------+----------+----------------------------------------------+
</code>```

I have options in mind.

I will drop subquery and use VIEWS to output the data just like using query. Because i have subquery in FROM, so i will use VIEWS from VIEWS. But some said it will affected in performances. How you guys think about this?

I will still using subquery, but will try and search how to optimize the query. For this one, i wanted to ask you guys, for the first result row in EXPLAIN TABLE, It shows table production p which the type 'all', how to avoid 'all' ? I've managed to use type 'eq_ref' for others table, but still have no clue why the product table is 'all'?

Again,
Do you think i need to switch to VIEW? Or just try to optimise again the subquery.

Many Thanks!

EDIT: table products index

```<code>create index family_id on products (family_id);
create index idx_products_date_added on products (products_date_added);
create index material_expenses on products (material_expenses);
create index products_brand_id on products (products_brand_id);
create index products_ean on products (products_ean);
create index products_status on products (products_status);
create index tb_status on products (tb_status);
</code>```

EDIT: table style_has_products

```<code>CREATE TABLE `styles_has_products` (
  `styles_id` int(10) unsigned NOT NULL DEFAULT '0',
  `products_id` int(10) unsigned NOT NULL DEFAULT '0',
  `date_added` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`styles_id`,`products_id`),
  KEY `products_id` (`products_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
</code>```

答:
first and foremost never write such a complex query for real time use. i'll suggest do batch process and maintain data warehouse. and use real time query on data warehouse.

still there are many things you should not do to SQL query on real time use to get performance. like never use more join operation, never put more if else conditions , never apply group by especially if table is huge, look for proper index , partition structure in table.

Body:
I just learning MYSQL, I have MySql subquery like this:

EXPLAIN EXTENDED SELECT brand_name, stars, hh_stock, hh_stock_value, sales_monthly_1, sales_monthly_2, sales_monthly_3, sold_monthly_1, sold_monthly_2,
  sold_monthly_3, price_uvp, price_ecp, price_default, price_margin AS margin, vc_percent as vc, cogs, products_length, products_id, material_expenses,
  MAX(price) AS products_price, SUM(total_sales) AS total_sales,
  IFNULL(MAX(active_age), DATEDIFF(NOW(), products_date_added)) AS products_age, DATEDIFF(NOW(), products_date_added) AS jng_products_age,
  AVG(sales_weekly) AS sales_weekly, AVG(sales_monthly) AS sales_monthly, SUM(total_sold) AS total_sold, SUM(total_returned) AS total_returned,
  ((SUM(total_returned)/SUM(total_sold)) * 100) AS returned_rate
FROM
  (
    SELECT p.products_id, jc.price, jc.price_end_customer AS price_ecp, jc.total_sales, jc.active_age, jc.sales_weekly,
      jc.sales_monthly, jc.total_sold, jc.total_returned, jc.price_uvp, p.price_margin, p.vc_percent, p.material_expenses,
      p.products_date_added, p.stars , pb.brand_name, p.family_id, p.products_price_default AS price_default, pl.sales_monthly_1,
      pl.sales_monthly_2, pl.sales_monthly_3, pl.sold_monthly_1, pl.sold_monthly_2, pl.sold_monthly_3, pst.stock AS hh_stock,
      (pst.stock * p.average_stock_value) AS hh_stock_value, pnc.products_length,
      IF(ploc.cogs IS NULL OR ploc.cogs=0,
         (CASE p.complexity
          WHEN 'F' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2),2)
          WHEN 'E' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2),2)
          WHEN 'N' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2),2)
          WHEN 'M' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2),2)
          WHEN 'I' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2),2)
          WHEN 'H' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2),2)
          ELSE ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+5+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+5+0.25+2.2),2) END), ploc.cogs) AS cogs
    FROM products p
      LEFT  JOIN jng_sp_catalog jc ON  jc.products_id=p.products_id
      LEFT JOIN products_description pd ON pd.products_id = p.products_id AND pd.language_id = 2
      LEFT JOIN products_description2 pd2 ON pd2.products_id = p.products_id
      LEFT JOIN products_brand pb ON pb.products_brand_id = p.products_brand_id
      LEFT JOIN products_log pl ON pl.products_id = p.products_id
      LEFT JOIN products_log_static pls ON pls.products_id=p.products_id
      LEFT JOIN products_local ploc ON ploc.products_id = p.products_id
      LEFT JOIN products_non_configurator pnc ON pnc.products_id = p.products_id
      INNER JOIN
      (
        SELECT shp.products_id, CONCAT(',', GROUP_CONCAT(shp.styles_id), ',') AS styles_id
        FROM styles_has_products shp GROUP BY shp.products_id HAVING styles_id NOT LIKE '%,1967,%') subquery_styles ON subquery_styles.products_id = p.products_id
      LEFT JOIN products_stock_temp pst ON pst.products_id=p.products_id WHERE p.active_status='1'  AND p.categories_top_id  =  '1') dt  GROUP BY products_id ORDER BY  products_id;

The result of explain is like this:

+----+-------------+------------+------------+--------+---------------------+-------------+---------+------------------------------------+--------+----------+----------------------------------------------+
| id | select_type | table      | partitions | type   | possible_keys       | key         | key_len | ref                                | rows   | filtered | Extra                                        |
+----+-------------+------------+------------+--------+---------------------+-------------+---------+------------------------------------+--------+----------+----------------------------------------------+
|  1 | PRIMARY     | p          | NULL       | ALL    | PRIMARY             | NULL        | NULL    | NULL                               |  40458 |     1.00 | Using where; Using temporary; Using filesort |
|  1 | PRIMARY     | pb         | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_brand_id |      1 |   100.00 | NULL                                         |
|  1 | PRIMARY     | ploc       | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | NULL                                         |
|  1 | PRIMARY     | pl         | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using where                                  |
|  1 | PRIMARY     | pls        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using index                                  |
|  1 | PRIMARY     | pst        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | NULL                                         |
|  1 | PRIMARY     | pd2        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using index                                  |
|  1 | PRIMARY     | pnc        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using where                                  |
|  1 | PRIMARY     | pd         | NULL       | eq_ref | PRIMARY             | PRIMARY     | 8       | manobo_central.p.products_id,const |      1 |   100.00 | Using index                                  |
|  1 | PRIMARY     | jc         | NULL       | ref    | products_id         | products_id | 4       | manobo_central.p.products_id       |      4 |   100.00 | Using where                                  |
|  1 | PRIMARY     | <derived3> | NULL       | ref    | <auto_key0>         | <auto_key0> | 4       | manobo_central.p.products_id       |     10 |   100.00 | Using where                                  |
|  3 | DERIVED     | shp        | NULL       | index  | PRIMARY,products_id | PRIMARY     | 8       | NULL                               | 208226 |   100.00 | Using index; Using filesort                  |
+----+-------------+------------+------------+--------+---------------------+-------------+---------+------------------------------------+--------+----------+----------------------------------------------+

I have options in mind.

I will drop subquery and use VIEWS to output the data just like using query. Because i have subquery in FROM, so i will use VIEWS from VIEWS. But some said it will affected in performances. How you guys think about this?

I will still using subquery, but will try and search how to optimize the query. For this one, i wanted to ask you guys, for the first result row in EXPLAIN TABLE, It shows table production p which the type 'all', how to avoid 'all' ? I've managed to use type 'eq_ref' for others table, but still have no clue why the product table is 'all'?

Again,
Do you think i need to switch to VIEW? Or just try to optimise again the subquery.

Many Thanks!

EDIT: table products index

create index family_id on products (family_id);
create index idx_products_date_added on products (products_date_added);
create index material_expenses on products (material_expenses);
create index products_brand_id on products (products_brand_id);
create index products_ean on products (products_ean);
create index products_status on products (products_status);
create index tb_status on products (tb_status);

EDIT: table style_has_products

CREATE TABLE `styles_has_products` (
  `styles_id` int(10) unsigned NOT NULL DEFAULT '0',
  `products_id` int(10) unsigned NOT NULL DEFAULT '0',
  `date_added` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`styles_id`,`products_id`),
  KEY `products_id` (`products_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1


来源: stackexchange

问:
How to stop a ksh?
I have a ksh script which I have started but now I want to stop it.  The ksh, abc.ksh, takes hours to run and I want it to stop.
I found the pid of the ksh using ps -ef and then did

```<code>kill -9 pid
</code>```

When I did a ps -ef again the ksh is no longer here but I can see the log file where the ksh is writting still executing.  The ksh I have executed call a java.
Any idea how do I stop this java code from continuing to execute?

答: Probably the ksh script you are referring to, starts another process (which is the one that actually produce the log. You have to find the pid of that process and kill that one.</p>

ContentLicense: CC BY-SA 3.0

Title: How to stop a ksh?

Body:
I have a ksh script which I have started but now I want to stop it.  The ksh, abc.ksh, takes hours to run and I want it to stop.
I found the pid of the ksh using ps -ef and then did

kill -9 pid

When I did a ps -ef again the ksh is no longer here but I can see the log file where the ksh is writting still executing.  The ksh I have executed call a java.
Any idea how do I stop this java code from continuing to execute?


问:
Pygame Making A Sprite Face The Mouse
Im New To Pygame But Kinda OK On Python, Im Creating A Zombie Shooting Game With an overhead view.

I managed to make the character move when pressing the arrow keys. But now i need to get the player to FACE the mouse/cursor without clicking the screen all the time.

Any Help?

答:
```<code>if event.type == MOUSEBUTTONDOWN:
    mouseX, mouseY = pygame.mouse.get_pos()
    vetMouse=pygame.math.Vector2(mouseX,mouseY)
    gradiRot=vetMouse.angle_to(vetShip)
</code>```

Title: Pygame Making A Sprite Face The Mouse


问:
jQuery show same value grabbed from different data attributes
I put 2 same data attributes in multiple elements (data-product-name & data-product-code), the intention is to populate the value from the data attribute in some input field.

```<code><strong class="displayed_product_name" data-product-name="All content" data-product-code="abc">All content</strong>
</code>```

I grab the data attributes values and make them as an array.

```<code>var arrProductCode = [];
$(this).closest('.each_content_item').find('[data-product-code]').each(function () {
    arrProductCode.push($(this).text());
});

var arrProductName = [];
$(this).closest('.each_content_item').find('[data-product-name]').each(function () {
    arrProductName.push($(this).text());
});
</code>```

To populate them in element and an input field

```<code>$(arrProductName).each(function () {
    $('.pop_edit_country').find('.pop_edit_product_list ul').append("<li>" + this + "</li>");
});
$(arrProductCode).each(function () {
    $('.hidden_edit_country_product_list').val($('.hidden_edit_country_product_list').val() + arrProductCode + ',');
});
</code>```

The value of data-product-name grabbed correctly, but why the value of data-product-code is the same as data-product-name? I couldn't solve it, is it because 1 element cannot contain 2 data attributes?

答:
This is because in the both case you call text function instead of calling data function.

text function get the text context of your element while data function gets the content of data attribute you passed to it.

Here is the corrected code:

```<code>var arrProductCode = [];
$(this).closest('.each_content_item').find('[data-product-code]').each(function () {
    arrProductCode.push($(this).data('product-code'));
});

var arrProductName = [];
$(this).closest('.each_content_item').find('[data-product-name]').each(function () {
    arrProductName.push($(this).data('product-name'));
});
</code>```

Body:
I put 2 same data attributes in multiple elements (data-product-name & data-product-code), the intention is to populate the value from the data attribute in some input field.

All content

I grab the data attributes values and make them as an array.

var arrProductCode = [];
$(this).closest('.each_content_item').find('[data-product-code]').each(function () {
    arrProductCode.push($(this).text());
});

var arrProductName = [];
$(this).closest('.each_content_item').find('[data-product-name]').each(function () {
    arrProductName.push($(this).text());
});

To populate them in element and an input field

$(arrProductName).each(function () {
    $('.pop_edit_country').find('.pop_edit_product_list ul').append("
" + this + "
");
});
$(arrProductCode).each(function () {
    $('.hidden_edit_country_product_list').val($('.hidden_edit_country_product_list').val() + arrProductCode + ',');
});

The value of data-product-name grabbed correctly, but why the value of data-product-code is the same as data-product-name? I couldn't solve it, is it because 1 element cannot contain 2 data attributes?

Body:
This is because in the both case you call text function instead of calling data function.

text function get the text context of your element while data function gets the content of data attribute you passed to it.

Here is the corrected code:

var arrProductCode = [];
$(this).closest('.each_content_item').find('[data-product-code]').each(function () {
    arrProductCode.push($(this).data('product-code'));
});

var arrProductName = [];
$(this).closest('.each_content_item').find('[data-product-name]').each(function () {
    arrProductName.push($(this).data('product-name'));
});


问:
Calculating progressive pricing in PostgreSQL
I need to calculate revenue based on how many items a user has.
So for example, the first 10 items are free, up to 100 items are 0.50, up to 200 are 0.25 and up to 500 are 0.15 for example.

I have no idea where to start with this, can I get some direction please?

EG. If a user has 365 items, this would be (10 * 0) + (90 * 0.5) + (100 * 0.25) + (165 * 0.15)

Ideally I'd be doing this in python or something, but the dashboarding tool doesn't have that capability...

EDIT:
I should have mentioned that the number of items isn't actually the number they have, it's the limit they have chosen. The limit is saved as a single number in a subscription event. So for each user I will have an integer representing their max items eg. 365

答:
First number items using window function row_number,

then use a case expression to assign a proper value for each item.

Simple example: http://sqlfiddle.com/#!17/32e4a/9

```<code>SELECT user_id,
 SUM(
    CASE
       WHEN rn <= 10 THEN 0
       WHEN rn <= 100 THEN 0.5
       WHEN rn <= 200 THEN 0.25
       WHEN rn <= 500 THEN 0.15
       ELSE 0.05
    END
   ) As revenue
FROM (
  SELECT *,
    row_number() OVER (partition by user_id order by item_no ) As rn
  FROM mytable
) x
GROUP BY user_id
</code>```

I should have mentioned that the number of items isn't actually the
  number they have, it's the limit they have chosen. The limit is saved
  as a single number in a subscription event. So for each user I will
  have an integer representing their max items eg. 365

In this case the below query probably fits your needs:

Demo: http://sqlfiddle.com/#!17/e7a6a/2

```<code>SELECT *,
      (SELECT SUM(
          CASE
             WHEN rn <= 10 THEN 0
             WHEN rn <= 100 THEN 0.5
             WHEN rn <= 200 THEN 0.25
             WHEN rn <= 500 THEN 0.15
             ELSE 0.05
           END
            )
          FROM generate_series(1,t.user_limit) rn
       )
FROM mytab t;
</code>```

Body:
First number items using window function row_number,

then use a case expression to assign a proper value for each item.

Simple example: http://sqlfiddle.com/#!17/32e4a/9

SELECT user_id,
 SUM(
    CASE
       WHEN rn <= 10 THEN 0
       WHEN rn <= 100 THEN 0.5
       WHEN rn <= 200 THEN 0.25
       WHEN rn <= 500 THEN 0.15
       ELSE 0.05
    END
   ) As revenue
FROM (
  SELECT *,
    row_number() OVER (partition by user_id order by item_no ) As rn
  FROM mytable
) x
GROUP BY user_id

I should have mentioned that the number of items isn't actually the
  number they have, it's the limit they have chosen. The limit is saved
  as a single number in a subscription event. So for each user I will
  have an integer representing their max items eg. 365

In this case the below query probably fits your needs:

Demo: http://sqlfiddle.com/#!17/e7a6a/2

SELECT *,
      (SELECT SUM(
          CASE
             WHEN rn <= 10 THEN 0
             WHEN rn <= 100 THEN 0.5
             WHEN rn <= 200 THEN 0.25
             WHEN rn <= 500 THEN 0.15
             ELSE 0.05
           END
            )
          FROM generate_series(1,t.user_limit) rn
       )
FROM mytab t;


问:
Get events added by my app in android calendar
In my app, I am adding some event in the google calendar on a screen. When the user comes to the screen again, it adds the events again so in calendar the duplicate event is also visible.
So before adding any new event, I want to check if the event already exists. If I get all the events of the calendar and iterate over it, my app becomes very slow or hangs with a notification

```<code>too many calendar deletes
</code>```

The code that I am using to insert the values is :

```<code>final ContentValues event = new ContentValues();

    event.put(CalendarContract.Events.CALENDAR_ID, calendarId);

    event.put(CalendarContract.Events.TITLE, name);
    event.put(CalendarContract.Events.DTSTART, millisstarttime);
    event.put(CalendarContract.Events.DTEND, millisendtime);
    event.put(CalendarContract.Events.EVENT_LOCATION, venue);
    event.put(CalendarContract.Events.ALL_DAY, 0);   // 0 for false, 1 for true
    event.put(CalendarContract.Events.HAS_ALARM, 1);
    event.put(CalendarContract.Events.ACCESS_LEVEL, CalendarContract.Events.ACCESS_PRIVATE);
    event.put(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY);// 0 for false, 1 for true

    String timeZone = TimeZone.getDefault().getID();
    event.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone);

    this.getContentResolver().insert(baseUri, event);
</code>```

And I am trying to get the values :

```<code>private void deleteeve(ContentResolver cr,int calendarId) {

    String[] projection = {CalendarContract.Events._ID,
            CalendarContract.Events.CUSTOM_APP_PACKAGE,CalendarContract.Events.CALENDAR_ID,CalendarContract.Events.ORGANIZER};
    // Get a Cursor over the Events Provider.
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        return;
    }
    Cursor cursor = getContentResolver().query(
            CalendarContract.Events.CONTENT_URI, projection,"calendar_id=" + calendarId, null,
            null);
    assert cursor != null;
    cursor.moveToFirst();

    String idsToDelete = "";
    int nameIdx = cursor.getColumnIndexOrThrow(CalendarContract.Events.CUSTOM_APP_PACKAGE);
    int id=cursor.getColumnIndexOrThrow(CalendarContract.Events._ID);
    int org=cursor.getColumnIndexOrThrow(CalendarContract.Events.ORGANIZER);
    while (cursor.moveToNext()) {
        // Extract the name.
        String name = cursor.getString(nameIdx);
        String apppackage = getApplicationContext().getPackageName();
        String organizer=cursor.getString(org);
        String idevent = cursor.getString(id);
        for (int i = 0; i < cursor.getCount(); i++) {

            if (apppackage.equals(name)) {
                // MY CODE
            }

        }
    }

}
</code>```

I tried getting the events using package name, So is there anyway to get the events added by my app only, other than iterating over all events?

答:
You can try this if you don't want to create new calendar for your app.</p>

```<code> Cursor cursor = getContentResolver().query(
        CalendarContract.Events.CONTENT_URI, projection, CalendarContract.Events.CUSTOM_APP_PACKAGE = getApplicationContext().getPackageName(), null,
        null);
</code>```

Body:
In my app, I am adding some event in the google calendar on a screen. When the user comes to the screen again, it adds the events again so in calendar the duplicate event is also visible.
So before adding any new event, I want to check if the event already exists. If I get all the events of the calendar and iterate over it, my app becomes very slow or hangs with a notification

too many calendar deletes

The code that I am using to insert the values is :

final ContentValues event = new ContentValues();

    event.put(CalendarContract.Events.CALENDAR_ID, calendarId);

    event.put(CalendarContract.Events.TITLE, name);
    event.put(CalendarContract.Events.DTSTART, millisstarttime);
    event.put(CalendarContract.Events.DTEND, millisendtime);
    event.put(CalendarContract.Events.EVENT_LOCATION, venue);
    event.put(CalendarContract.Events.ALL_DAY, 0);   // 0 for false, 1 for true
    event.put(CalendarContract.Events.HAS_ALARM, 1);
    event.put(CalendarContract.Events.ACCESS_LEVEL, CalendarContract.Events.ACCESS_PRIVATE);
    event.put(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY);// 0 for false, 1 for true

    String timeZone = TimeZone.getDefault().getID();
    event.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone);

    this.getContentResolver().insert(baseUri, event);

And I am trying to get the values :

private void deleteeve(ContentResolver cr,int calendarId) {

    String[] projection = {CalendarContract.Events._ID,
            CalendarContract.Events.CUSTOM_APP_PACKAGE,CalendarContract.Events.CALENDAR_ID,CalendarContract.Events.ORGANIZER};
    // Get a Cursor over the Events Provider.
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        return;
    }
    Cursor cursor = getContentResolver().query(
            CalendarContract.Events.CONTENT_URI, projection,"calendar_id=" + calendarId, null,
            null);
    assert cursor != null;
    cursor.moveToFirst();

    String idsToDelete = "";
    int nameIdx = cursor.getColumnIndexOrThrow(CalendarContract.Events.CUSTOM_APP_PACKAGE);
    int id=cursor.getColumnIndexOrThrow(CalendarContract.Events._ID);
    int org=cursor.getColumnIndexOrThrow(CalendarContract.Events.ORGANIZER);
    while (cursor.moveToNext()) {
        // Extract the name.
        String name = cursor.getString(nameIdx);
        String apppackage = getApplicationContext().getPackageName();
        String organizer=cursor.getString(org);
        String idevent = cursor.getString(id);
        for (int i = 0; i < cursor.getCount(); i++) {

            if (apppackage.equals(name)) {
                // MY CODE
            }

        }
    }

}

I tried getting the events using package name, So is there anyway to get the events added by my app only, other than iterating over all events?

Body:
You can try this if you don't want to create new calendar for your app.

 Cursor cursor = getContentResolver().query(
        CalendarContract.Events.CONTENT_URI, projection, CalendarContract.Events.CUSTOM_APP_PACKAGE = getApplicationContext().getPackageName(), null,
        null);


问:
Twitter integrated in Iphone App
I used MGTwitterEngine

which try to login then request fail error comes

Error Detail

connectionIdentifier 6260FAFD-AE4E-4F05-AE67-FFA1DA18578F

error description The operation couldn’t be completed. (HTTP error 401.)

error user info
({
body = "\n\n Client application is not permitted to use xAuth.\n /oauth/access_token\n\n";
response = "";
})

Any Idea

-Amit Battan

答:
@taskinoor
there the code I am using ...
I have create application on twitter already

Controller .h file

```<code>#import <UIKit/UIKit.h>
#import "MGTwitterEngine.h"
@class OAToken;
@interface TwitterTestViewController : UIViewController <MGTwitterEngineDelegate> {
    MGTwitterEngine *twitterEngine;
    OAToken *token;
}
@end
</code>```

Controller .m file

```<code>#import "TwitterTestViewController.h"
@implementation TwitterTestViewController
- (void)awakeFromNib{
    // Put your Twitter username and password here:
    NSString *username = @"amit_bursys";
    NSString *password = @"mypassword";
    NSString *consumerKey = @"my_key";
    NSString *consumerSecret = @"my_seret";
    if (! username || ! password || !consumerKey || !consumerSecret) {
        NSLog(@"You forgot to specify your username/password/key/secret in AppController.m, things might not work!");
        NSLog(@"And if things are mysteriously working without the username/password, it's because NSURLConnection is using a session cookie from another connection.");
    }
    twitterEngine = [[MGTwitterEngine alloc] initWithDelegate:self];
    [twitterEngine setUsesSecureConnection:NO];
    [twitterEngine setConsumerKey:consumerKey secret:consumerSecret];
    [twitterEngine setUsername:username];
    [twitterEngine getXAuthAccessTokenForUsername:username password:password];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
}
- (void)dealloc {
    [super dealloc];
}
#pragma mark MGTwitterEngineDelegate methods
- (void)requestSucceeded:(NSString *)connectionIdentifier{
    NSLog(@"Request succeeded for connectionIdentifier = %@", connectionIdentifier);
}
- (void)requestFailed:(NSString *)connectionIdentifier withError:(NSError *)error{
    NSLog(@"Request failed for connectionIdentifier = %@, error = %@ (%@)",
          connectionIdentifier,
          [error localizedDescription],
          [error userInfo]);
}
- (void)statusesReceived:(NSArray *)statuses forRequest:(NSString *)connectionIdentifier{
    NSLog(@"Got statuses for %@:\r%@", connectionIdentifier, statuses);
}
- (void)directMessagesReceived:(NSArray *)messages forRequest:(NSString *)connectionIdentifier{
    NSLog(@"Got direct messages for %@:\r%@", connectionIdentifier, messages);
}
- (void)userInfoReceived:(NSArray *)userInfo forRequest:(NSString *)connectionIdentifier
{
    NSLog(@"Got user info for %@:\r%@", connectionIdentifier, userInfo);
}
@end
</code>```

and Code log is

```<code>2010-12-21 11:14:31.533 TwitterTest[734:207] Request failed for connectionIdentifier = D28BD476-7315-4510-B51A-968E516D169D, error = The operation couldn’t be completed. (HTTP error 401.) ({
    body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<hash>\n  <request>/oauth/access_token</request>\n  <error>Client application is not permitted to use xAuth.</error>\n</hash>\n";
    response = "<NSHTTPURLResponse: 0x6022470>";
})
</code>```

ContentLicense: CC BY-SA 2.5

Title: Twitter integrated in Iphone App

Body:
@taskinoor
there the code I am using ...
I have create application on twitter already

Controller .h file

#import <UIKit/UIKit.h>
#import "MGTwitterEngine.h"
@class OAToken;
@interface TwitterTestViewController : UIViewController <MGTwitterEngineDelegate> {
    MGTwitterEngine *twitterEngine;
    OAToken *token;
}
@end

Controller .m file

#import "TwitterTestViewController.h"
@implementation TwitterTestViewController
- (void)awakeFromNib{
    // Put your Twitter username and password here:
    NSString *username = @"amit_bursys";
    NSString *password = @"mypassword";
    NSString *consumerKey = @"my_key";
    NSString *consumerSecret = @"my_seret";
    if (! username || ! password || !consumerKey || !consumerSecret) {
        NSLog(@"You forgot to specify your username/password/key/secret in AppController.m, things might not work!");
        NSLog(@"And if things are mysteriously working without the username/password, it's because NSURLConnection is using a session cookie from another connection.");
    }
    twitterEngine = [[MGTwitterEngine alloc] initWithDelegate:self];
    [twitterEngine setUsesSecureConnection:NO];
    [twitterEngine setConsumerKey:consumerKey secret:consumerSecret];
    [twitterEngine setUsername:username];
    [twitterEngine getXAuthAccessTokenForUsername:username password:password];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
}
- (void)dealloc {
    [super dealloc];
}
#pragma mark MGTwitterEngineDelegate methods
- (void)requestSucceeded:(NSString *)connectionIdentifier{
    NSLog(@"Request succeeded for connectionIdentifier = %@", connectionIdentifier);
}
- (void)requestFailed:(NSString *)connectionIdentifier withError:(NSError *)error{
    NSLog(@"Request failed for connectionIdentifier = %@, error = %@ (%@)",
          connectionIdentifier,
          [error localizedDescription],
          [error userInfo]);
}
- (void)statusesReceived:(NSArray *)statuses forRequest:(NSString *)connectionIdentifier{
    NSLog(@"Got statuses for %@:\r%@", connectionIdentifier, statuses);
}
- (void)directMessagesReceived:(NSArray *)messages forRequest:(NSString *)connectionIdentifier{
    NSLog(@"Got direct messages for %@:\r%@", connectionIdentifier, messages);
}
- (void)userInfoReceived:(NSArray *)userInfo forRequest:(NSString *)connectionIdentifier
{
    NSLog(@"Got user info for %@:\r%@", connectionIdentifier, userInfo);
}
@end

and Code log is

2010-12-21 11:14:31.533 TwitterTest[734:207] Request failed for connectionIdentifier = D28BD476-7315-4510-B51A-968E516D169D, error = The operation couldn’t be completed. (HTTP error 401.) ({
    body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<hash>\n  <request>/oauth/access_token</request>\n  <error>Client application is not permitted to use xAuth.</error>\n</hash>\n";
    response = "<NSHTTPURLResponse: 0x6022470>";
})


问:
Hive query on emp table which displays ename,sal of those who are working as salesman and sal>max(sal) of clerk
I am new to hive environment, I want to find those employees who are working as salesman and also whose salary grater than maximum salary of  all clerks. I can write a query in SQL but I can't write it in hive.

Here you can find emp table that exactly I used.

答:
Quickly the SQL would be something like this

```<code>select ename,salary from employee where job = "SALESMAN" and Salary >
( select max(salary) from employee where job = "CLERK" )
</code>```

Note: This is not tested

Body:
Quickly the SQL would be something like this

select ename,salary from employee where job = "SALESMAN" and Salary >
( select max(salary) from employee where job = "CLERK" )

Note: This is not tested


问:
Deploy maven project in to AEM?
I have created a maven project with content and bundle folder i can build the project successfully in eclipse
use this command :-

```<code>        mvn clean install
</code>```

but my bundle jar and content zip not reflecting in AEM now i am manually uploading the zip and jar in to AEM but i need to deploy directly from eclipse with out manual intall.

Can anybody help on this ?

答:
install is a phase in the Maven lifecycle during which an artifact is installed in your local Maven repository.

It usually has nothing to do with installing anything in AEM. You need to use specific Maven plugins to achieve that.

If you generated your project based on the Adobe archetype, you need to specify, using a profile, that you want your app deployed.

```<code>mvn -PautoInstallPackage install
</code>```

This profile activates the Maven Vault Plugin and uses it to upload the CRX package to AEM. Here's a snippet from Adobe's AEM archetype where this behaviour is defined.

```<code><profile>
    <id>autoInstallPackage</id>
    <activation>
        <activeByDefault>false</activeByDefault>
    </activation>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>com.day.jcr.vault</groupId>
                    <artifactId>content-package-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>install-package</id>
                            <goals>
                                <goal>install</goal>
                            </goals>
                            <configuration>
                                <targetURL>http://${aem.host}:${aem.port}/crx/packmgr/service.jsp</targetURL>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</profile>
</code>```

Check out the official documentation for more information.

If, by any chance, your project happens to be using the Maven CRX Plugin (Adobe's archetype and its particular choice of plugins is just one of the options available in the wider AEM community), you need to explicitly invoke the crx:install goal.

```<code>mvn install crx:install
</code>```

The bottom line is, mvn install just takes care of installing artifacts in your local Maven repository. In order to deploy to AEM, you need to invoke something more or set up your project to activate some plugins automatically in a certain phase of the lifecycle.

Title: Deploy maven project in to AEM?

Body:
I have created a maven project with content and bundle folder i can build the project successfully in eclipse
use this command :-

        mvn clean install

but my bundle jar and content zip not reflecting in AEM now i am manually uploading the zip and jar in to AEM but i need to deploy directly from eclipse with out manual intall.

Can anybody help on this ?

Body:
install is a phase in the Maven lifecycle during which an artifact is installed in your local Maven repository.

It usually has nothing to do with installing anything in AEM. You need to use specific Maven plugins to achieve that.

If you generated your project based on the Adobe archetype, you need to specify, using a profile, that you want your app deployed.

mvn -PautoInstallPackage install

This profile activates the Maven Vault Plugin and uses it to upload the CRX package to AEM. Here's a snippet from Adobe's AEM archetype where this behaviour is defined.

<profile>
    <id>autoInstallPackage</id>
    <activation>
        <activeByDefault>false</activeByDefault>
    </activation>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>com.day.jcr.vault</groupId>
                    <artifactId>content-package-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>install-package</id>
                            <goals>
                                <goal>install</goal>
                            </goals>
                            <configuration>
                                <targetURL>http://${aem.host}:${aem.port}/crx/packmgr/service.jsp</targetURL>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</profile>

Check out the official documentation for more information.

If, by any chance, your project happens to be using the Maven CRX Plugin (Adobe's archetype and its particular choice of plugins is just one of the options available in the wider AEM community), you need to explicitly invoke the crx:install goal.

mvn install crx:install

The bottom line is, mvn install just takes care of installing artifacts in your local Maven repository. In order to deploy to AEM, you need to invoke something more or set up your project to activate some plugins automatically in a certain phase of the lifecycle.


问:
Android - How to differentiate between users who sign in and register from firebase signinintent builder?
How can I differentiate between users who sign in and register when using firebase signinintentbuilder? https://github.com/firebase/FirebaseUI-Android/blob/master/auth/src/main/java/com/firebase/ui/auth/AuthUI.java

A workaround for this is to store the user's UID when registering, but how can I store a UID if the user object is null when starting the signinintentbuilder?

This is the code that starts the signinintentbuilder : '

```<code>        if(FirebaseAuth.getInstance().getCurrentUser() == null) {
             // Start sign in/sign up activity
             startActivityForResult(
                AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .build(),
                SIGN_IN_REQUEST_CODE
           );
        } else {
        // User is already signed in. Therefore, display

        // a welcome Toast
        Toast.makeText(this,
                "Welcome " + FirebaseAuth.getInstance()
                        .getCurrentUser()
                        .getDisplayName(),
                Toast.LENGTH_LONG)
                .show();
    }'
</code>```

Highly appreciate anyone's advise right now!

答:
You can use onAuthStateChanged listener, it is always called on user signup or signin. </p>

```<code>    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getEmail());

                    presenter.saveLocationtoken(FirebaseInstanceId.getInstance().getToken(),
                            user.getUid(),
                            user.getEmail(),
                            setRoleOnCreateUser(user));

                    userSignedInListener.updateNavHeader(firebaseAuth);
                    getFragmentManager().popBackStack(); // end of auth flow
                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
//                    userSignedInListener.updateNavHeader(firebaseAuth);
                }
            }
</code>```

<p>It works even if you update your UID on every signin because firebase registration tokens might change for a certain user, after a certain period of time. </p>

Body:
How can I differentiate between users who sign in and register when using firebase signinintentbuilder? https://github.com/firebase/FirebaseUI-Android/blob/master/auth/src/main/java/com/firebase/ui/auth/AuthUI.java

A workaround for this is to store the user's UID when registering, but how can I store a UID if the user object is null when starting the signinintentbuilder?

This is the code that starts the signinintentbuilder : '

        if(FirebaseAuth.getInstance().getCurrentUser() == null) {
             // Start sign in/sign up activity
             startActivityForResult(
                AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .build(),
                SIGN_IN_REQUEST_CODE
           );
        } else {
        // User is already signed in. Therefore, display

        // a welcome Toast
        Toast.makeText(this,
                "Welcome " + FirebaseAuth.getInstance()
                        .getCurrentUser()
                        .getDisplayName(),
                Toast.LENGTH_LONG)
                .show();
    }'

Highly appreciate anyone's advise right now!

Body:
You can use onAuthStateChanged listener, it is always called on user signup or signin.

    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getEmail());

                    presenter.saveLocationtoken(FirebaseInstanceId.getInstance().getToken(),
                            user.getUid(),
                            user.getEmail(),
                            setRoleOnCreateUser(user));

                    userSignedInListener.updateNavHeader(firebaseAuth);
                    getFragmentManager().popBackStack(); // end of auth flow
                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
//                    userSignedInListener.updateNavHeader(firebaseAuth);
                }
            }

It works even if you update your UID on every signin because firebase registration tokens might change for a certain user, after a certain period of time.


问:
StringBuilder and string equality check
I am trying this sample of code and OpTest when System.Console.WriteLine(s == t); it returns false. Can somebody explain this?

```<code>public static void OpTest<T>(T s, T t) where T : class
{
    System.Console.WriteLine(s == t);
}
static void Main()
{
    string s1 = "строка";
    System.Text.StringBuilder sb = new System.Text.StringBuilder(s1);
    System.Console.Write(sb);
    string s2 = sb.ToString();
    OpTest<string>(s1, s2);
}
</code>```

答:
s == t in OpTest<T> method checks for reference equality, not value equality. In this case, it returns false due to difference of reference source of both StringBuilder class.

To get true value, you need to use Equals method:

```<code>public static void OpTest<T>(T s, T t) where T : class
{
    System.Console.WriteLine(s.Equals(t));
}
</code>```

Demo: .NET Fiddle Example

Title: StringBuilder and string equality check

Body:
I am trying this sample of code and OpTest when System.Console.WriteLine(s == t); it returns false. Can somebody explain this?

public static void OpTest<T>(T s, T t) where T : class
{
    System.Console.WriteLine(s == t);
}
static void Main()
{
    string s1 = "строка";
    System.Text.StringBuilder sb = new System.Text.StringBuilder(s1);
    System.Console.Write(sb);
    string s2 = sb.ToString();
    OpTest<string>(s1, s2);
}

Body:
s == t in OpTest<T> method checks for reference equality, not value equality. In this case, it returns false due to difference of reference source of both StringBuilder class.

To get true value, you need to use Equals method:

public static void OpTest<T>(T s, T t) where T : class
{
    System.Console.WriteLine(s.Equals(t));
}

Demo: .NET Fiddle Example


答:
Finally i got the answer after RND . the time was there with different time zone . post remove category[] from xaxis parameter , i have added the UTC : false while loading the chart .</p>

```<code><!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>PAN INDIA TPS</title>
 <script type="text/javascript" src="js/jquery.min.js"></script>
  <script type="text/javascript" src="js/highcharts.js"></script>
  <script type="text/javascript" src="js/data.js"></script>

    </head>

    <body>

     <script type="text/javascript">

     function requesttps() {
          return $.ajax({
            url: 'http://10.19.82.21/tpspanIndia.php',
            type: "GET",
            async: true,
            dataType: "json"
          });
        }

     var options = {
        chart: {
            renderTo: "TPSPAN",
            type: 'line',
            borderwidth: 1,
            zoomType: 'x',

            events: {
      load: function() {
        var series0 = this.series[0];
        var series1 = this.series[1];
        var series2 = this.series[2];
        var series3 = this.series[3];
        setInterval(function() {
          requesttps().done(function(point) {
            series0.update({
                type: 'area',
          name: point[0].name,
               data: point[0].data
                            });
            series1.update({
                type: 'area',
              name: point[1].name,
               data: point[1].data
                            });
            series2.update({
              type: 'area',
                name: point[2].name,
               data: point[2].data
                            });
            series3.update({
                   type: 'area',
               name: point[3].name,
               data: point[3].data
                            });
                                            });
                                }, 100000);
                        }
                    }

        },
        title: {
            text: 'PAN INDIA SETUP WISE TPS TREND'
        },

        xAxis: {
            tickInterval: 5,
            type: 'datetime',

            /*labels: {
                format: '{value:%H:%M:%S}',
                rotation: 45,
                align: 'right'
            }*/

        },
        /*yAxis: {
            title: {
                text: ''
            },
            //min: 0
        },*/
        tooltip: {

        formatter: function () {
                        return '<b>' + this.series.name + '</b><br/>' +
                            Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +'Count:'+
                            Highcharts.numberFormat(this.y, 0);
                    }

        },

        plotOptions: {
            spline: {
                marker: {
                    enabled: true
                }
            }
        },

        series: []
    };

    $(function() {

    Highcharts.setOptions({
                    global : {
                        useUTC : false
                }
                });
          requesttps().done(function(point) {
          options.series = point;
          var chart = new Highcharts.Chart(options);
          setTimeout(requesttps(), 100000);
          });
        });

        </script>

                <div id="TPSPAN" style="margin: center"></div>

    </body>

    </html>
</code>```

Title: high-chart not showing date and time in xaxis

Body:
Hi I have data as JSON format return by PHP . it will convert the date and time to UNIX format and return the data . I have to plot three series with last 5 minute date of current date, yesterday date and last week of same date.

every thing is going fine only the time is not showing in proper format , need help to populate the time in xaxis and tool tips .

sample data is

[{"name":"WDAY","data":[[1499060167,76],[1499060168,75],[1499060169,83],[1499060170,88],[1499060171,80],[1499060172,74],[1499060173,72],[1499060174,88],[1499060175,84],[1499060176,84],[1499060177,75],[1499060178,96],[1499060179,85],[1499060180,77],[1499060181,77],[1499060182,82],[1499060183,69],[1499060184,77],[1499060185,90],[1499060186,63],[1499060187,92],[1499060188,69],[1499060189,86],[1499060190,77],[1499060191,94],[1499060192,82],[1499060193,70],[1499060194,87],[1499060195,88],[1499060196,92],[1499060197,84],[1499060198,77],[1499060199,80],[1499060200,79],[1499060201,77],[1499060202,71],[1499060203,88],[1499060204,88],[1499060205,94],[1499060206,73],[1499060207,81],[1499060208,78],[1499060209,88],[1499060210,69],[1499060211,88],[1499060212,72],[1499060213,90],[1499060214,85],[1499060215,76],[1499060216,64],[1499060217,71],[1499060218,71],[1499060219,84],[1499060220,78],[1499060221,72],[1499060222,68],[1499060223,95],[1499060224,81],[1499060225,73],[1499060226,75],[1499060227,82],[1499060228,74],[1499060229,70],[1499060230,83],[1499060231,87],[1499060232,70],[1499060233,92],[1499060234,85],[1499060235,86],[1499060236,76],[1499060237,62],[1499060238,88],[1499060239,79],[1499060240,69],[1499060241,81],[1499060242,84],[1499060243,73],[1499060244,80],[1499060245,75],[1499060246,69],[1499060247,98],[1499060248,82],[1499060249,87],[1499060250,65],[1499060251,80],[1499060252,81],[1499060253,71],[1499060254,78],[1499060255,63],[1499060256,69],[1499060257,82],[1499060258,94],[1499060259,71],[1499060260,80],[1499060261,67],[1499060262,85],[1499060263,76],[1499060264,81],[1499060265,73],[1499060266,80],[1499060267,75],[1499060268,82],[1499060269,76],[1499060270,74],[1499060271,62],[1499060272,78],[1499060273,82],[1499060274,79],[1499060275,89],[1499060276,99],[1499060277,92],[1499060278,62],[1499060279,84],[1499060280,83],[1499060281,63],[1499060282,63],[1499060283,82],[1499060284,78],[1499060285,78],[1499060286,81],[1499060287,76],[1499060288,70],[1499060289,62],[1499060290,70],[1499060291,78],[1499060292,82],[1499060293,84],[1499060294,86],[1499060295,69],[1499060296,92],[1499060297,85],[1499060298,68],[1499060299,98],[1499060300,81],[1499060301,81],[1499060302,102],[1499060303,66],[1499060304,75],[1499060305,81],[1499060306,82],[1499060307,90],[1499060308,73],[1499060309,73],[1499060310,62],[1499060311,81],[1499060312,65],[1499060313,74],[1499060314,84],[1499060315,77],[1499060316,70],[1499060317,87],[1499060318,87],[1499060319,85],[1499060320,75],[1499060321,99],[1499060322,88],[1499060323,72],[1499060324,79],[1499060325,78],[1499060326,72],[1499060327,70],[1499060328,82],[1499060329,84],[1499060330,79],[1499060331,94],[1499060332,87],[1499060333,79],[1499060334,76],[1499060335,76],[1499060336,90],[1499060337,83],[1499060338,70],[1499060339,70],[1499060340,75],[1499060341,68],[1499060342,89],[1499060343,67],[1499060344,89],[1499060345,75],[1499060346,91],[1499060347,81],[1499060348,78],[1499060349,73],[1499060350,88],[1499060351,73],[1499060352,93],[1499060353,88],[1499060354,69],[1499060355,81],[1499060356,73],[1499060357,74],[1499060358,78],[1499060359,93],[1499060360,74],[1499060361,80],[1499060362,78],[1499060363,62],[1499060364,76],[1499060365,83],[1499060366,77],[1499060367,77],[1499060368,75],[1499060369,81],[1499060370,72],[1499060371,75],[1499060372,80],[1499060373,75],[1499060374,75],[1499060375,66],[1499060376,61],[1499060377,84],[1499060378,69],[1499060379,76],[1499060380,74],[1499060381,85],[1499060382,92],[1499060383,83],[1499060384,82],[1499060385,76],[1499060386,83],[1499060387,90],[1499060388,84],[1499060389,83],[1499060390,77],[1499060391,69],[1499060392,93],[1499060393,72],[1499060394,67],[1499060395,69],[1499060396,81],[1499060397,84],[1499060398,72],[1499060399,76],[1499060400,89],[1499060401,63],[1499060402,86],[1499060403,76],[1499060404,65],[1499060405,71],[1499060406,82],[1499060407,83],[1499060408,76],[1499060409,93],[1499060410,78],[1499060411,88],[1499060412,85],[1499060413,82],[1499060414,62],[1499060415,64],[1499060416,70],[1499060417,79],[1499060418,80],[1499060419,75],[1499060420,69],[1499060421,82],[1499060422,56],[1499060423,92],[1499060424,76],[1499060425,83],[1499060426,74],[1499060427,79],[1499060428,77],[1499060429,71],[1499060430,75],[1499060431,76],[1499060432,83],[1499060433,79],[1499060434,73],[1499060435,84],[1499060436,81],[1499060437,78],[1499060438,66],[1499060439,89],[1499060440,68],[1499060441,83],[1499060442,87],[1499060443,70],[1499060444,75],[1499060445,74],[1499060446,71],[1499060447,91],[1499060448,75],[1499060449,91],[1499060450,81],[1499060451,92],[1499060452,62],[1499060453,77],[1499060454,70],[1499060455,74],[1499060456,74],[1499060457,80],[1499060458,83],[1499060459,78],[1499060460,79],[1499060461,94],[1499060462,72],[1499060463,82],[1499060464,59],[1499060465,88],[1499060466,74]]},{"name":"YDAY","data":[[1499060166,61],[1499060167,59],[1499060168,55],[1499060169,59],[1499060170,55],[1499060171,58],[1499060172,49],[1499060173,50],[1499060174,54],[1499060175,69],[1499060176,56],[1499060177,56],[1499060178,62],[1499060179,65],[1499060180,70],[1499060181,46],[1499060182,53],[1499060183,60],[1499060184,72],[1499060185,71],[1499060186,45],[1499060187,64],[1499060188,64],[1499060189,56],[1499060190,65],[1499060191,48],[1499060192,65],[1499060193,72],[1499060194,63],[1499060195,52],[1499060196,60],[1499060197,57],[1499060198,67],[1499060199,57],[1499060200,65],[1499060201,87],[1499060202,53],[1499060203,58],[1499060204,54],[1499060205,61],[1499060206,58],[1499060207,57],[1499060208,62],[1499060209,59],[1499060210,70],[1499060211,67],[1499060212,57],[1499060213,54],[1499060214,45],[1499060215,55],[1499060216,52],[1499060217,63],[1499060218,61],[1499060219,63],[1499060220,59],[1499060221,49],[1499060222,69],[1499060223,60],[1499060224,65],[1499060225,66],[1499060226,63],[1499060227,55],[1499060228,68],[1499060229,55],[1499060230,62],[1499060231,64],[1499060232,63],[1499060233,54],[1499060234,70],[1499060235,49],[1499060236,54],[1499060237,67],[1499060238,65],[1499060239,59],[1499060240,49],[1499060241,77],[1499060242,77],[1499060243,43],[1499060244,56],[1499060245,56],[1499060246,43],[1499060247,55],[1499060248,59],[1499060249,63],[1499060250,68],[1499060251,49],[1499060252,67],[1499060253,66],[1499060254,58],[1499060255,64],[1499060256,71],[1499060257,49],[1499060258,71],[1499060259,53],[1499060260,67],[1499060261,46],[1499060262,67],[1499060263,49],[1499060264,65],[1499060265,60],[1499060266,62],[1499060267,59],[1499060268,52],[1499060269,65],[1499060270,50],[1499060271,65],[1499060272,52],[1499060273,66],[1499060274,51],[1499060275,61],[1499060276,57],[1499060277,47],[1499060278,51],[1499060279,59],[1499060280,66],[1499060281,62],[1499060282,51],[1499060283,66],[1499060284,63],[1499060285,60],[1499060286,64],[1499060287,65],[1499060288,74],[1499060289,72],[1499060290,65],[1499060291,69],[1499060292,63],[1499060293,57],[1499060294,67],[1499060295,54],[1499060296,65],[1499060297,57],[1499060298,59],[1499060299,59],[1499060300,61],[1499060301,71],[1499060302,57],[1499060303,47],[1499060304,56],[1499060305,72],[1499060306,64],[1499060307,52],[1499060308,56],[1499060309,69],[1499060310,69],[1499060311,62],[1499060312,75],[1499060313,54],[1499060314,70],[1499060315,52],[1499060316,68],[1499060317,72],[1499060318,61],[1499060319,54],[1499060320,61],[1499060321,55],[1499060322,61],[1499060323,64],[1499060324,73],[1499060325,50],[1499060326,70],[1499060327,58],[1499060328,62],[1499060329,64],[1499060330,62],[1499060331,56],[1499060332,62],[1499060333,64],[1499060334,69],[1499060335,63],[1499060336,55],[1499060337,67],[1499060338,59],[1499060339,68],[1499060340,66],[1499060341,65],[1499060342,69],[1499060343,67],[1499060344,65],[1499060345,54],[1499060346,57],[1499060347,59],[1499060348,56],[1499060349,51],[1499060350,72],[1499060351,63],[1499060352,71],[1499060353,48],[1499060354,70],[1499060355,74],[1499060356,74],[1499060357,65],[1499060358,55],[1499060359,83],[1499060360,65],[1499060361,57],[1499060362,60],[1499060363,52],[1499060364,55],[1499060365,61],[1499060366,58],[1499060367,60],[1499060368,59],[1499060369,61],[1499060370,56],[1499060371,80],[1499060372,67],[1499060373,78],[1499060374,60],[1499060375,64],[1499060376,59],[1499060377,66],[1499060378,60],[1499060379,74],[1499060380,54],[1499060381,57],[1499060382,48],[1499060383,69],[1499060384,68],[1499060385,61],[1499060386,70],[1499060387,50],[1499060388,55],[1499060389,45],[1499060390,60],[1499060391,59],[1499060392,54],[1499060393,69],[1499060394,67],[1499060395,58],[1499060396,62],[1499060397,42],[1499060398,65],[1499060399,71],[1499060400,64],[1499060401,48],[1499060402,60],[1499060403,67],[1499060404,51],[1499060405,57],[1499060406,58],[1499060407,67],[1499060408,66],[1499060409,72],[1499060410,61],[1499060411,67],[1499060412,63],[1499060413,62],[1499060414,54],[1499060415,50],[1499060416,47],[1499060417,67],[1499060418,66],[1499060419,64],[1499060420,68],[1499060421,62],[1499060422,55],[1499060423,53],[1499060424,58],[1499060425,54],[1499060426,65],[1499060427,47],[1499060428,58],[1499060429,34],[1499060430,72],[1499060431,51],[1499060432,74],[1499060433,66],[1499060434,45],[1499060435,66],[1499060436,63],[1499060437,63],[1499060438,62],[1499060439,69],[1499060440,56],[1499060441,67],[1499060442,62],[1499060443,78],[1499060444,55],[1499060445,59],[1499060446,48],[1499060447,54],[1499060448,56],[1499060449,70],[1499060450,55],[1499060451,60],[1499060452,68],[1499060453,54],[1499060454,58],[1499060455,60],[1499060456,52],[1499060457,55],[1499060458,56],[1499060459,48],[1499060460,55],[1499060461,58],[1499060462,57],[1499060463,70],[1499060464,72],[1499060465,61]]},{"name":"ToDAY","data":[[1499060165,72],[1499060166,62],[1499060167,75],[1499060168,76],[1499060169,63],[1499060170,87],[1499060171,65],[1499060172,61],[1499060173,58],[1499060174,55],[1499060175,62],[1499060176,76],[1499060177,71],[1499060178,58],[1499060179,69],[1499060180,59],[1499060181,74],[1499060182,81],[1499060183,77],[1499060184,56],[1499060185,78],[1499060186,70],[1499060187,82],[1499060188,73],[1499060189,84],[1499060190,74],[1499060191,79],[1499060192,64],[1499060193,79],[1499060194,69],[1499060195,64],[1499060196,70],[1499060197,72],[1499060198,62],[1499060199,66],[1499060200,63],[1499060201,94],[1499060202,78],[1499060203,66],[1499060204,75],[1499060205,73],[1499060206,77],[1499060207,63],[1499060208,64],[1499060209,77],[1499060210,75],[1499060211,70],[1499060212,77],[1499060213,69],[1499060214,56],[1499060215,65],[1499060216,65],[1499060217,72],[1499060218,84],[1499060219,74],[1499060220,68],[1499060221,76],[1499060222,73],[1499060223,69],[1499060224,62],[1499060225,61],[1499060226,60],[1499060227,51],[1499060228,77],[1499060229,74],[1499060230,64],[1499060231,69],[1499060232,60],[1499060233,63],[1499060234,78],[1499060235,78],[1499060236,69],[1499060237,61],[1499060238,63],[1499060239,65],[1499060240,74],[1499060241,73],[1499060242,70],[1499060243,59],[1499060244,71],[1499060245,67],[1499060246,65],[1499060247,66],[1499060248,74],[1499060249,77],[1499060250,72],[1499060251,64],[1499060252,59],[1499060253,53],[1499060254,79],[1499060255,58],[1499060256,74],[1499060257,84],[1499060258,61],[1499060259,70],[1499060260,60],[1499060261,64],[1499060262,59],[1499060263,78],[1499060264,62],[1499060265,65],[1499060266,64],[1499060267,73],[1499060268,60],[1499060269,55],[1499060270,70],[1499060271,65],[1499060272,67],[1499060273,72],[1499060274,70],[1499060275,72],[1499060276,72],[1499060277,63],[1499060278,75],[1499060279,60],[1499060280,65],[1499060281,71],[1499060282,78],[1499060283,75],[1499060284,63],[1499060285,71],[1499060286,63],[1499060287,60],[1499060288,64],[1499060289,59],[1499060290,65],[1499060291,73],[1499060292,81],[1499060293,74],[1499060294,56],[1499060295,83],[1499060296,60],[1499060297,73],[1499060298,65],[1499060299,85],[1499060300,70],[1499060301,71],[1499060302,81],[1499060303,76],[1499060304,79],[1499060305,79],[1499060306,63],[1499060307,70],[1499060308,84],[1499060309,67],[1499060310,78],[1499060311,63],[1499060312,61],[1499060313,89],[1499060314,62],[1499060315,64],[1499060316,70],[1499060317,63],[1499060318,58],[1499060319,70],[1499060320,67],[1499060321,66],[1499060322,54],[1499060323,66],[1499060324,62],[1499060325,83],[1499060326,74],[1499060327,70],[1499060328,71],[1499060329,60],[1499060330,64],[1499060331,62],[1499060332,69],[1499060333,72],[1499060334,61],[1499060335,69],[1499060336,59],[1499060337,69],[1499060338,71],[1499060339,73],[1499060340,86],[1499060341,77],[1499060342,67],[1499060343,74],[1499060344,73],[1499060345,68],[1499060346,76],[1499060347,83],[1499060348,58],[1499060349,76],[1499060350,93],[1499060351,80],[1499060352,65],[1499060353,73],[1499060354,76],[1499060355,54],[1499060356,75],[1499060357,70],[1499060358,72],[1499060359,62],[1499060360,70],[1499060361,73],[1499060362,70],[1499060363,76],[1499060364,67],[1499060365,58],[1499060366,64],[1499060367,55],[1499060368,67],[1499060369,65],[1499060370,68],[1499060371,72],[1499060372,73],[1499060373,80],[1499060374,73],[1499060375,65],[1499060376,62],[1499060377,72],[1499060378,61],[1499060379,74],[1499060380,67],[1499060381,88],[1499060382,72],[1499060383,78],[1499060384,77],[1499060385,61],[1499060386,60],[1499060387,55],[1499060388,58],[1499060389,66],[1499060390,72],[1499060391,75],[1499060392,68],[1499060393,74],[1499060394,64],[1499060395,64],[1499060396,81],[1499060397,67],[1499060398,54],[1499060399,75],[1499060400,77],[1499060401,52],[1499060402,55],[1499060403,78],[1499060404,71],[1499060405,58],[1499060406,69],[1499060407,69],[1499060408,86],[1499060409,75],[1499060410,59],[1499060411,66],[1499060412,68],[1499060413,67],[1499060414,60],[1499060415,68],[1499060416,63],[1499060417,72],[1499060418,45],[1499060419,68],[1499060420,93],[1499060421,78],[1499060422,53],[1499060423,74],[1499060424,63],[1499060425,83],[1499060426,76],[1499060427,76],[1499060428,61],[1499060429,67],[1499060430,75],[1499060431,69],[1499060432,66],[1499060433,73],[1499060434,51],[1499060435,60],[1499060436,69],[1499060437,63],[1499060438,64],[1499060439,63],[1499060440,65],[1499060441,70],[1499060442,68],[1499060443,55],[1499060444,58],[1499060445,59],[1499060446,77],[1499060447,71],[1499060448,72],[1499060449,69],[1499060450,65],[1499060451,77],[1499060452,74],[1499060453,66],[1499060454,74],[1499060455,74],[1499060456,64],[1499060457,73],[1499060458,60],[1499060459,71],[1499060460,67],[1499060461,66],[1499060462,78],[1499060463,72],[1499060464,71],[1499060465,81]]}]

and my code is

<!DOCTYPE html>

The xaxis is not correct and tool tips also

Body:
Finally i got the answer after RND . the time was there with different time zone . post remove category[] from xaxis parameter , i have added the UTC : false while loading the chart .

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>PAN INDIA TPS</title>
 <script type="text/javascript" src="js/jquery.min.js"></script>
  <script type="text/javascript" src="js/highcharts.js"></script>
  <script type="text/javascript" src="js/data.js"></script>

    </head>

    <body>

     <script type="text/javascript">

     function requesttps() {
          return $.ajax({
            url: 'http://10.19.82.21/tpspanIndia.php',
            type: "GET",
            async: true,
            dataType: "json"
          });
        }

     var options = {
        chart: {
            renderTo: "TPSPAN",
            type: 'line',
            borderwidth: 1,
            zoomType: 'x',

            events: {
      load: function() {
        var series0 = this.series[0];
        var series1 = this.series[1];
        var series2 = this.series[2];
        var series3 = this.series[3];
        setInterval(function() {
          requesttps().done(function(point) {
            series0.update({
                type: 'area',
          name: point[0].name,
               data: point[0].data
                            });
            series1.update({
                type: 'area',
              name: point[1].name,
               data: point[1].data
                            });
            series2.update({
              type: 'area',
                name: point[2].name,
               data: point[2].data
                            });
            series3.update({
                   type: 'area',
               name: point[3].name,
               data: point[3].data
                            });
                                            });
                                }, 100000);
                        }
                    }

        },
        title: {
            text: 'PAN INDIA SETUP WISE TPS TREND'
        },

        xAxis: {
            tickInterval: 5,
            type: 'datetime',

            /*labels: {
                format: '{value:%H:%M:%S}',
                rotation: 45,
                align: 'right'
            }*/

        },
        /*yAxis: {
            title: {
                text: ''
            },
            //min: 0
        },*/
        tooltip: {

        formatter: function () {
                        return '<b>' + this.series.name + '</b><br/>' +
                            Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +'Count:'+
                            Highcharts.numberFormat(this.y, 0);
                    }

        },

        plotOptions: {
            spline: {
                marker: {
                    enabled: true
                }
            }
        },

        series: []
    };

    $(function() {

    Highcharts.setOptions({
                    global : {
                        useUTC : false
                }
                });
          requesttps().done(function(point) {
          options.series = point;
          var chart = new Highcharts.Chart(options);
          setTimeout(requesttps(), 100000);
          });
        });

        </script>

                <div id="TPSPAN" style="margin: center"></div>

    </body>

    </html>


问:
how to dismiss alert view after validation?
I had used SCLAlertView used for forgot password in this i had placed a textfield to enter email so that after making successful validation only it need to hide without this it should not hide can anyone help me how to implement this ?

My code is shown below

```<code>@IBAction func forgetPasswordButton(_ sender: Any) {
        let appearance = SCLAlertView.SCLAppearance(showCloseButton: true)
        let alert = SCLAlertView(appearance: appearance)
        let txt = alert.addTextField("Enter your emailid")
        _ = alert.addButton("Submit", action: {
            let action = txt.text
                print(action as Any)
        })
        if(txt.text?.isEmpty)! == true{

        }else{

        }
        _ = alert.showEdit("Forgot Password", subTitle:"Please enter your email address below.You will receive a link to reset your password",closeButtonTitle: "Cancel")
    }
</code>```

答:
use the property of hideView() and call like

```<code>let action = txt.text
            print(action as Any)
       alert.hideView()
    })
</code>```

for more reference you can get the sample here

Body:
I had used SCLAlertView used for forgot password in this i had placed a textfield to enter email so that after making successful validation only it need to hide without this it should not hide can anyone help me how to implement this ?

My code is shown below

@IBAction func forgetPasswordButton(_ sender: Any) {
        let appearance = SCLAlertView.SCLAppearance(showCloseButton: true)
        let alert = SCLAlertView(appearance: appearance)
        let txt = alert.addTextField("Enter your emailid")
        _ = alert.addButton("Submit", action: {
            let action = txt.text
                print(action as Any)
        })
        if(txt.text?.isEmpty)! == true{

        }else{

        }
        _ = alert.showEdit("Forgot Password", subTitle:"Please enter your email address below.You will receive a link to reset your password",closeButtonTitle: "Cancel")
    }

Body:
use the property of hideView() and call like

let action = txt.text
            print(action as Any)
       alert.hideView()
    })

for more reference you can get the sample here


问:
Is it possible to check if a request was made from IMG tag?
I have an ActionResult at http://example/image.png

Is there a way to determine if the URL is being requested from

```<code><img src="http://example/image.png" />
</code>```

Or was opened from

```<code><a href="http://example/image.png" target="_blank" />
</code>```

?

So I can control the result with...

```<code>public ActionResult ViewPhoto()
{
    if (<img src />)
    {
        return File();
    }
    else
    {
        return View();
    }
}
</code>```

答: You can check if Request.Headers["Accept"] does not contain the string "html".

Body:
I have an ActionResult at http://example/image.png

Is there a way to determine if the URL is being requested from

Or was opened from

?

So I can control the result with...

public ActionResult ViewPhoto()
{
    if ()
    {
        return File();
    }
    else
    {
        return View();
    }
}


问:
How to check for last item when looping through a structure in ColdFusion?
I want to loop over a structure and output something for all items except the last one. For arrays this can easily be done by checking whether the current index is the last one, though how to do it for structures?

Example code:

```<code><cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
</cfscript>

<cfoutput>
<cfloop collection="#myStruct#" item="item">
  #myStruct[item]#
  <!--- Here should be the conditional output --->
</cfloop>
</cfoutput>
</code>```

答:
Just increment your own "index" as you loop:

```<code><cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
totalItems = StructCount( myStruct );
thisItemNumber = 1;
</cfscript>

<cfoutput>
<cfloop collection="#myStruct#" item="item">
  #myStruct[item]#
  <cfset thisIsNotTheLastItem = ( thisItemNumber LT totalItems )>
    <cfif thisIsNotTheLastItem>
        is not the last item<br/>
    </cfif>
    <cfset thisItemNumber++>
</cfloop>
</cfoutput>
</code>```

EDIT: Here's an alternative using an array

```<code><cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
totalItems = StructCount( myStruct );
keys = StructKeyArray( myStruct );
lastItem = myStruct[ keys[ totalItems ] ];
</cfscript>
<cfoutput>
<cfloop array="#keys#" item="key">
    #myStruct[ key ]#
    <cfif myStruct[ key ] IS NOT lastItem>
        is not the last item<br/>
    </cfif>
</cfloop>
</cfoutput>
</code>```

Body:
I want to loop over a structure and output something for all items except the last one. For arrays this can easily be done by checking whether the current index is the last one, though how to do it for structures?

Example code:

<cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
</cfscript>

<cfoutput>
<cfloop collection="#myStruct#" item="item">
  #myStruct[item]#

</cfloop>
</cfoutput>

Body:
Just increment your own "index" as you loop:

<cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
totalItems = StructCount( myStruct );
thisItemNumber = 1;
</cfscript>

<cfoutput>
<cfloop collection="#myStruct#" item="item">
  #myStruct[item]#
  <cfset thisIsNotTheLastItem = ( thisItemNumber LT totalItems )>
    <cfif thisIsNotTheLastItem>
        is not the last item<br/>
    </cfif>
    <cfset thisItemNumber++>
</cfloop>
</cfoutput>

EDIT: Here's an alternative using an array

<cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
totalItems = StructCount( myStruct );
keys = StructKeyArray( myStruct );
lastItem = myStruct[ keys[ totalItems ] ];
</cfscript>
<cfoutput>
<cfloop array="#keys#" item="key">
    #myStruct[ key ]#
    <cfif myStruct[ key ] IS NOT lastItem>
        is not the last item<br/>
    </cfif>
</cfloop>
</cfoutput>


问:
Is this done with a regular expression? Formatting Latitude Longitude
I am trying to format a polygon (several lat/long coordinates connected together) using Leaflet Draw. Here is the format return and what I have done so far:

```<code>map.on("draw:drawstop", polyPointToString);
function polyPointToString(e){
    console.log("Unaltered Coordinates: " + coords);
    polyStringParse = coords.toString().replace(/[^\d,.-]/g, '');
    console.log("Polyparse: " + polyStringParse);
    polyStringParseRegExp = polyStringParse.replace(/([^,]+[^,]),/g,'$1 ');
    console.log("PolyparseRegExp: " + polyStringParseRegExp);
}
</code>```

Unaltered Coordinates is this:

```<code>//Unaltered Coordinates: LatLng(46.58907, -102.74414),LatLng(46.58907, -102.74414),LatLng(46.58907, -102.74414)
</code>```

PolyParse is this (only numbers, dashes, and decimal points left):

```<code>//Polyparse: 46.58907,-102.74414,46.58907,-102.74414,46.58907,-102.74414
</code>```

PolyparseRegExpt is this(it keeps removing ALL commas :-(   ):

```<code>//Polyparse2: 46.58907 -102.74414 46.58907 -102.74414 46.58907 -102.74414
</code>```

What is need: Comma 1, 3, 5, 7.... etc removed so that I have:

number number, number number, number number,........

Basilcally, every odd numbed comma. right now it's removing all commas for some reason.

答:
It looks like coords is an array of Leaflet's LatLngs. Using toString() is an odd thing to do, considering that you can use .lat and .lng to access the LatLng's properties.

It also looks like you're trying to convert your data into WKT (Well-Known-Text) due to yur use of spaces and commas.

So you can convert a LatLng into a WKT coordinate pair with something like:

```<code>var latlng = L.latLng(...)
var wktPoint = latlng.lng + ' ' + latlng.lat;
</code>```

And, if you have an array of LatLngs, you can use Array.prototype.map and Array.prototype.join to great effect here:

```<code>var coords = [ L.latLng(...), L.latLng(...), ... ];

var wktLineString = coords.map(function(ll){
    // For every item in the array, return a string.
    // The call to .map() will thus return an array of strings
    return ll.lng + ' ' + ll.lat;

    // Once the array of strings is ready, join those strings
    // with the given separator.
}).join(',');
</code>```

As I'm assuming you're using WKT, note the swapping of the coordinates so you can have lng-lat instead of lat-lng. Also note you can use toFixed() and the like to have better control of the output.

Body:
I am trying to format a polygon (several lat/long coordinates connected together) using Leaflet Draw. Here is the format return and what I have done so far:

map.on("draw:drawstop", polyPointToString);
function polyPointToString(e){
    console.log("Unaltered Coordinates: " + coords);
    polyStringParse = coords.toString().replace(/[^\d,.-]/g, '');
    console.log("Polyparse: " + polyStringParse);
    polyStringParseRegExp = polyStringParse.replace(/([^,]+[^,]),/g,'$1 ');
    console.log("PolyparseRegExp: " + polyStringParseRegExp);
}

Unaltered Coordinates is this:

//Unaltered Coordinates: LatLng(46.58907, -102.74414),LatLng(46.58907, -102.74414),LatLng(46.58907, -102.74414)

PolyParse is this (only numbers, dashes, and decimal points left):

//Polyparse: 46.58907,-102.74414,46.58907,-102.74414,46.58907,-102.74414

PolyparseRegExpt is this(it keeps removing ALL commas :-(   ):

//Polyparse2: 46.58907 -102.74414 46.58907 -102.74414 46.58907 -102.74414

What is need: Comma 1, 3, 5, 7.... etc removed so that I have:

number number, number number, number number,........

Basilcally, every odd numbed comma. right now it's removing all commas for some reason.

Body:
It looks like coords is an array of Leaflet's LatLngs. Using toString() is an odd thing to do, considering that you can use .lat and .lng to access the LatLng's properties.

It also looks like you're trying to convert your data into WKT (Well-Known-Text) due to yur use of spaces and commas.

So you can convert a LatLng into a WKT coordinate pair with something like:

var latlng = L.latLng(...)
var wktPoint = latlng.lng + ' ' + latlng.lat;

And, if you have an array of LatLngs, you can use Array.prototype.map and Array.prototype.join to great effect here:

var coords = [ L.latLng(...), L.latLng(...), ... ];

var wktLineString = coords.map(function(ll){
    // For every item in the array, return a string.
    // The call to .map() will thus return an array of strings
    return ll.lng + ' ' + ll.lat;

    // Once the array of strings is ready, join those strings
    // with the given separator.
}).join(',');

As I'm assuming you're using WKT, note the swapping of the coordinates so you can have lng-lat instead of lat-lng. Also note you can use toFixed() and the like to have better control of the output.


问:
what is notifycollectionchangedaction reset value
I have an observable collection...SelectableDataContext<T>..And in the generic class SelectableDataContext<T> is...having two private member variables

Private T item.

Private bool isSelected.

When the IsSelected property changes...My collection's changed property is not firing .

I think it should fire...because it's Reset in INotifyCollectionChangedAction.

答: Collection changed will be fired if and only if you modify the collection that is via either Adding a new Item or Removing an existing item from the collection.</p>


问:
Removing public/index.php?
How do we remove the public/index.php from ci-bonfire 0.7 ?

I see there are instructions to remove the root index.php but I am unable to remove the root public/index.php and there are no instructions related to it.

I have tried instructions in http://cibonfire.com/docs/bonfire/removing_index without any success. I keep getting the 404 when I go to

```<code>http://localhost/Bonfire-0.7/index.php
</code>```

but

http://localhost/Bonfire-0.7/public/index.php

works fine.

答:
Hello I had this error in CodeIgniter the installation in the server works such the next example:

SERVER_IP/public/index.php/controller/method

But I need

SERVER_IP/controller/method

My Solution is very very simple, my project is in the root directory then I go to the root directory and I have to create a .htaccess file configuration. like this:

```<code><IfModule mod_rewrite.c>
   RewriteEngine On
   //Setting de base URL.
   RewriteBase /public
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   //Setting the pattern to match
   RewriteRule ^(.*)$ index.php/$1/ [L]
</IfModule>
</code>```

The final result is:

Request: SERVER_IP/login => SERVER_IP/public/index.php/login

Request: SERVER_IP/login/doLogin => SERVER_IP/public/index.php/login/doLogin

Request: SERVER_IP/login/logout?noredirect=1 => SERVER_IP/public/index.php/login/logout?noredirect=1

Good Luck...

Title: Removing public/index.php?

Body:
How do we remove the public/index.php from ci-bonfire 0.7 ?

I see there are instructions to remove the root index.php but I am unable to remove the root public/index.php and there are no instructions related to it.

I have tried instructions in http://cibonfire.com/docs/bonfire/removing_index without any success. I keep getting the 404 when I go to

http://localhost/Bonfire-0.7/index.php

but

http://localhost/Bonfire-0.7/public/index.php

works fine.

Body:
Hello I had this error in CodeIgniter the installation in the server works such the next example:

SERVER_IP/public/index.php/controller/method

But I need

SERVER_IP/controller/method

My Solution is very very simple, my project is in the root directory then I go to the root directory and I have to create a .htaccess file configuration. like this:

<IfModule mod_rewrite.c>
   RewriteEngine On
   //Setting de base URL.
   RewriteBase /public
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   //Setting the pattern to match
   RewriteRule ^(.*)$ index.php/$1/ [L]
</IfModule>

The final result is:

Request: SERVER_IP/login => SERVER_IP/public/index.php/login

Request: SERVER_IP/login/doLogin => SERVER_IP/public/index.php/login/doLogin

Request: SERVER_IP/login/logout?noredirect=1 => SERVER_IP/public/index.php/login/logout?noredirect=1

Good Luck...

ContentLicense: CC BY-SA 4.0


问:
Make inputs accessible regardless of where they are
Is there a plugin that makes inputs checked work regardless of where they are located. I will be making lots of radio and checkbox inputs that will be buried in divs, but the inputs will need to control multiple divs when checked. I don't really want to make all of them work individually through jquery. I'd rather let css take care of what should happen when checked.

div {
  position: absolute;
  background: rgba(85, 183, 255, 0.25);
}

.box2 {
  left: 120px;
}

.box3 {
  left: 240px;
}

input {
  position: absolute;
  width: 100%;
  height: 100%;
}

.a {
  width: 100px;
  height: 100px;
}

.b {
  width: 80px;
  height: 80px;
  left: 10px;
  top: 10px;
}

.c {
  width: 60px;
  height: 60px;
  left: 10px;
  top: 10px;
}

.container {
  position: absolute;
  width: 100px;
  height: 200px;
  top: 140px;
  background: rgba(85, 183, 255, 0.25);
}

.con2 {
  left: 120px;
}

.con3 {
  left: 240px;
}

.alter {
  postion: absolute;
  width: 80px;
  height: 80px;
  background: rgba(255, 0, 0, 0.5);
  left: 10px;
  top: 60px;
  transition: 1s;
}

.radio1:checked ~ .me1 {
  background: green;
}

.radio2:checked ~ .me2 {
  height: 100px;
  top: 50px;
}

.radio2:checked ~ .me3 {
  transform: scale(2px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a box1">
  <div class="b">
    <div class="c">
      <input type="radio" name="radio" class="radio1">
    </div>
  </div>
</div>
<div class="a box2">
  <div class="b">
    <input type="radio" name="radio" class="radio2">
  </div>
</div>
<div class="a box3">
  <div class="b">
    <div class="c">
      <input type="radio" name="radio" class="radio3">
    </div>
  </div>
</div>

<div class="container con1">
  <div class="alter me1"></div>
</div>
<div class="container con2">
  <div class="alter me3"></div>
</div>
<div class="container con3">
  <div class="alter me3"></div>
</div></code>```

答:
I'm not quite sure, what you intend to do, but maybe this helps.
The code triggers as soon as one radio button is checked and afterwards checks if all radio button boxes are selected.

You may probably do something else then, instead of showing a continue link.
Hope this helps, otherwise describe more clear, what you intend to do.

```<code>$(":radio").change(function() {
        var names = {};
        $(':radio').each(function() {
            names[$(this).attr('name')] = true;
        });
        var count = 0;
        $.each(names, function() {
            count++;
        });
        if ($(':radio:checked').length === count) {
            $('#linkContinue').show();
        }
    }).change();
</code>```

Body:
Is there a plugin that makes inputs checked work regardless of where they are located. I will be making lots of radio and checkbox inputs that will be buried in divs, but the inputs will need to control multiple divs when checked. I don't really want to make all of them work individually through jquery. I'd rather let css take care of what should happen when checked.

div {
  position: absolute;
  background: rgba(85, 183, 255, 0.25);
}

.box2 {
  left: 120px;
}

.box3 {
  left: 240px;
}

input {
  position: absolute;
  width: 100%;
  height: 100%;
}

.a {
  width: 100px;
  height: 100px;
}

.b {
  width: 80px;
  height: 80px;
  left: 10px;
  top: 10px;
}

.c {
  width: 60px;
  height: 60px;
  left: 10px;
  top: 10px;
}

.container {
  position: absolute;
  width: 100px;
  height: 200px;
  top: 140px;
  background: rgba(85, 183, 255, 0.25);
}

.con2 {
  left: 120px;
}

.con3 {
  left: 240px;
}

.alter {
  postion: absolute;
  width: 80px;
  height: 80px;
  background: rgba(255, 0, 0, 0.5);
  left: 10px;
  top: 60px;
  transition: 1s;
}

.radio1:checked ~ .me1 {
  background: green;
}

.radio2:checked ~ .me2 {
  height: 100px;
  top: 50px;
}

.radio2:checked ~ .me3 {
  transform: scale(2px);
}

      <input type="radio" name="radio" class="radio1">

    <input type="radio" name="radio" class="radio2">

      <input type="radio" name="radio" class="radio3">

Body:
I'm not quite sure, what you intend to do, but maybe this helps.
The code triggers as soon as one radio button is checked and afterwards checks if all radio button boxes are selected.

You may probably do something else then, instead of showing a continue link.
Hope this helps, otherwise describe more clear, what you intend to do.

$(":radio").change(function() {
        var names = {};
        $(':radio').each(function() {
            names[$(this).attr('name')] = true;
        });
        var count = 0;
        $.each(names, function() {
            count++;
        });
        if ($(':radio:checked').length === count) {
            $('#linkContinue').show();
        }
    }).change();


问:
Microsoft SQL Server Management Studio Opening Error
I installed SQL Server Management Studio and it worked fine. After that I updated my Visual Studio from 2010 to 2013 Express edition, now it is not working with this error message :

Cannot find one or more components. Please re install the application

I re-installed it but still same issue. Any suggestion?

答:
The SQL Server 2017 Management Studio answer

SSMS 17.1 also depends on Visual Studio 2015 shell (isolated). I had to repair the Shell to get SSMS to work. In case someone is looking for VS 2015 Shell: LINK

If you cannot find the installer using the above link, the SSMS 17.x installer HERE includes the VS 2015 Shell.

Scott Hanselman has also conveniently included a link to every (>= 2008 R2) Express and SSMS version here: LINK


问:
How to convert XML to Dictionary
I've xml as following:

```<code><?xml version="1.0" encoding="UTF-8"?>
<root>
  <data name="LogIn">Log In</data>
  <data name="Password">Password</data>
</root>
</code>```

I success to do that without Linq, any one can help me to convert the following code to Linq:

```<code>using (XmlReader reader = XmlReader.Create(_xml))
{
    while (reader.Read())
    {
       if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "data")
       {
          reader.MoveToAttribute("name");
          string key = reader.Value;
          reader.MoveToContent();
          string value = reader.ReadElementContentAsString();
          _dictionary.Add(key, value);
       }
    }
    reader.Close();
}
</code>```

答:
This is an old question, but in case someone comes across a 'Typed' xml (e.g from a SharedPreference file of an android app), you can handle it as below: Here is a sample of such an xml I took from an Instagram app.

```<code><?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<boolean name="pinnable_stickers" value="false" />
<string name="phone_number">+254711339900</string>
<int name="score" value="0" />
<string name="subscription_list">[]</string>
<long name="last_address_book_updated_timestamp" value="1499326818875" />
 //...other properties
</map>
</code>```

Note the inconsistency in the value property. Some fields(e.g of type string) don't have it explicitly defined.

```<code>var elements = XElement.Load(filePath)
.Elements()
.ToList();
var dict = new Dictionary<string, string>();
var _dict = elements.ToDictionary(key => key.Attribute("name").Value,
                        val => val.Attribute("value") != null ?
                        val.Attribute("value").Value : val.Value);
</code>```

Title: How to convert XML to Dictionary

Body:
I've xml as following:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <data name="LogIn">Log In</data>
  <data name="Password">Password</data>
</root>

I success to do that without Linq, any one can help me to convert the following code to Linq:

using (XmlReader reader = XmlReader.Create(_xml))
{
    while (reader.Read())
    {
       if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "data")
       {
          reader.MoveToAttribute("name");
          string key = reader.Value;
          reader.MoveToContent();
          string value = reader.ReadElementContentAsString();
          _dictionary.Add(key, value);
       }
    }
    reader.Close();
}

Body:
This is an old question, but in case someone comes across a 'Typed' xml (e.g from a SharedPreference file of an android app), you can handle it as below: Here is a sample of such an xml I took from an Instagram app.

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<boolean name="pinnable_stickers" value="false" />
<string name="phone_number">+254711339900</string>
<int name="score" value="0" />
<string name="subscription_list">[]</string>
<long name="last_address_book_updated_timestamp" value="1499326818875" />
 //...other properties
</map>

Note the inconsistency in the value property. Some fields(e.g of type string) don't have it explicitly defined.

var elements = XElement.Load(filePath)
.Elements()
.ToList();
var dict = new Dictionary<string, string>();
var _dict = elements.ToDictionary(key => key.Attribute("name").Value,
                        val => val.Attribute("value") != null ?
                        val.Attribute("value").Value : val.Value);


问:
Javascript indexOf on an array of objects
if I have an array like:

```<code>var myArray = [
                {
                    'color':'red',
                    'name': 'redName'
                },
                {
                    'color':'blue',
                    'name': 'blueName'
                },
                {
                    'color':'green',
                    'name': 'greenName'
                    },
                {
                    'color':'yellow',
                    'name': 'yellowName'
                },
             ];
</code>```

How do I get the index of say, "blue"?

答:
You can use .findIndex() method

In your case

```<code>var findeMe = "blue";
myArray.findIndex(function(row){
return row.color == findMe;
});
</code>```

I hope it help.

Body:
if I have an array like:

var myArray = [
                {
                    'color':'red',
                    'name': 'redName'
                },
                {
                    'color':'blue',
                    'name': 'blueName'
                },
                {
                    'color':'green',
                    'name': 'greenName'
                    },
                {
                    'color':'yellow',
                    'name': 'yellowName'
                },
             ];

How do I get the index of say, "blue"?

Body:
You can use .findIndex() method

In your case

var findeMe = "blue";
myArray.findIndex(function(row){
return row.color == findMe;
});

I hope it help.


问:
Completion of Exchange once Aggregated
I am pulling messages from rabbit and aggregating them.  I have noticed that even with autoAck=false the messages are ackd as soon as they have been aggregated.  This means that if my process crashes the messages will not be re-queued for rety.

I have plugged in the leveldb java db as the aggregation repo which solves the problem, as I presume it will only ack once it has aggregated and stored in repo?  To be honest level-db doesn't make me feel comfortable based on its activity and issues with the C version, guess I can switch it to a SQL repo.

So. Question is, is there something I can do so Camel will only Ack the messages of exchanges once the aggregated message has completed its journey?  After aggregation my next step is to simple write to disk.

答:
That is by design, then aggregator is a stateful EIP. So the incoming message is handed over to the aggregator, and then continued, and thus the rabbit consumer that processed the message is completed and its acked.

You need to plugin a persistent aggregation repository as you say.

Since you last step is to write to disk, I would re-design so you take each message from rabbit and write to disk first, and then do another from disk -> aggregate -> disk.

Title: Completion of Exchange once Aggregated