问:
Difference in time based on time records and subequent time records from same table
I placed a sample of some data on SQLFiddle where I'm trying to figure out how to build a query from this data that will give:

The TIMEDIFF() of the TimeStr field of the scl1_fill table and the very next sc1_weight table TimeStr field

example: SELECT TIMEDIFF('2017-11-14 07:21:29','2017-11-14 07:15:56')

I think I need to emulate ROW_NUMBER() with MySQL and I always seem to have trouble with that for some reason using variables and sub queries to get the row numbers, etc.

I tried quite a few things and came up short every time so not even sure it's worth showing what I tried so I will provide what I have and the expected results for visualization/clarification.

Essentially when the sc1_fill gets a 1 value the device starts to fill and when the sc1_weight gets any value then that means it met the weight setpoint and gives back a value at that point.

Getting the time difference between the two will show the amount of time it took from the time the sc1_fill started until the very next record time wise the sc1_weight gets any value ran.

I figured I could throw this as a value on the sc1_weight records with the TIMEDIFF() and have a new column and have all other records show NULL and that'd work (see Expected Results).

Full Table Data

(Always and only get data from one specific date so e.g. WHERE TimeStr LIKE '2017-11-14%')

```<code>| test_tbl |               TimeStr |   Value |
----------------------------------------------
sc1_setpnt      2017-11-14 00:05:01     650
sc1_disch       2017-11-14 07:10:24     1
sc1_fill        2017-11-14 07:15:56     1
sc1_weight      2017-11-14 07:21:29     651
sc1_disch       2017-11-14 07:26:18     1
sc1_fill        2017-11-14 07:27:32     1
sc1_weight      2017-11-14 07:33:07     650
sc1_disch       2017-11-14 08:18:36     1
sc1_fill        2017-11-14 08:19:53     1
sc1_weight      2017-11-14 08:25:29     651
sc1_disch       2017-11-14 08:30:21     1
sc1_fill        2017-11-14 08:31:39     1
sc1_weight      2017-11-14 08:37:20     650
sc1_disch       2017-11-14 08:46:00     1
sc1_fill        2017-11-14 08:47:17     1
sc1_weight      2017-11-14 08:52:50     649
sc1_disch       2017-11-14 09:03:22     1
sc1_fill        2017-11-14 09:04:36     1
sc1_weight      2017-11-14 09:10:10     651
sc1_disch       2017-11-14 09:18:45     1
sc1_fill        2017-11-14 09:20:35     1
sc1_weight      2017-11-14 09:26:11     650
sc1_disch       2017-11-14 09:36:40     1
sc1_fill        2017-11-14 09:37:59     1
sc1_weight      2017-11-14 09:43:39     650
sc1_disch       2017-11-14 09:46:55     1
sc1_fill        2017-11-14 09:53:49     1
sc1_weight      2017-11-14 09:59:42     650
sc1_disch       2017-11-14 10:36:06     1
sc1_fill        2017-11-14 10:37:27     1
sc1_weight      2017-11-14 10:43:14     650
sc1_disch       2017-11-14 10:50:44     1
sc1_fill        2017-11-14 10:52:01     1
sc1_weight      2017-11-14 10:57:47     650
sc1_disch       2017-11-14 11:05:46     1
sc1_fill        2017-11-14 11:07:19     1
sc1_weight      2017-11-14 11:12:48     650
sc1_disch       2017-11-14 11:25:25     1
sc1_fill        2017-11-14 11:36:18     1
sc1_fill        2017-11-14 11:39:12     1
sc1_fill        2017-11-14 11:45:26     1
sc1_weight      2017-11-14 11:50:39     651
sc1_disch       2017-11-14 12:00:45     1
sc1_fill        2017-11-14 12:04:44     1
sc1_weight      2017-11-14 12:10:16     651
sc1_disch       2017-11-14 12:58:48     1
sc1_fill        2017-11-14 13:00:01     1
sc1_weight      2017-11-14 13:05:23     651
sc1_disch       2017-11-14 13:06:19     1
sc1_fill        2017-11-14 13:10:52     1
sc1_weight      2017-11-14 13:16:19     650
sc1_disch       2017-11-14 13:18:27     1
sc1_fill        2017-11-14 13:24:35     1
sc1_weight      2017-11-14 13:30:01     651
sc1_disch       2017-11-14 13:31:35     1
sc1_fill        2017-11-14 13:35:40     1
sc1_weight      2017-11-14 13:41:05     650
sc1_disch       2017-11-14 13:47:04     1
sc1_fill        2017-11-14 13:50:19     1
sc1_weight      2017-11-14 13:55:43     649
sc1_disch       2017-11-14 14:06:57     1
sc1_fill        2017-11-14 14:08:11     1
sc1_weight      2017-11-14 14:13:32     651
sc1_disch       2017-11-14 14:26:10     1
sc1_fill        2017-11-14 14:27:24     1
sc1_weight      2017-11-14 14:32:49     650
sc1_disch       2017-11-14 14:42:00     1
sc1_fill        2017-11-14 14:43:11     1
sc1_weight      2017-11-14 14:48:25     650
</code>```

Expected Results

```<code>| test_tbl |               TimeStr |   Value |     FillTime |
-------------------------------------------------------------
sc1_setpnt      2017-11-14 00:05:01     650              NULL
sc1_disch       2017-11-14 07:10:24     1                NULL
sc1_fill        2017-11-14 07:15:56     1                NULL
sc1_weight      2017-11-14 07:21:29     651          00:05:33
sc1_disch       2017-11-14 07:26:18     1                NULL
sc1_fill        2017-11-14 07:27:32     1                NULL
sc1_weight      2017-11-14 07:33:07     650          00:05:35
sc1_disch       2017-11-14 08:18:36     1                NULL
sc1_fill        2017-11-14 08:19:53     1                NULL
sc1_weight      2017-11-14 08:25:29     651          00:05:36
sc1_disch       2017-11-14 08:30:21     1                NULL
sc1_fill        2017-11-14 08:31:39     1                NULL
sc1_weight      2017-11-14 08:37:20     650         00:05:41
sc1_disch       2017-11-14 08:46:00     1                NULL
</code>```

Making Matters Worse

Okay to make matters worse, it seems at times there are multiple sc1_fill values of 1 before the subsequent sc1_weight value but I would only need to calculate the most recent or newest TimeStr of the set to get the fill time (e.g. SELECT TIMEDIFF('2017-11-14 11:50:39','2017-11-14 11:45:26'))

Expected results where this is the case

```<code>| test_tbl |               TimeStr |   Value |     FillTime |
-------------------------------------------------------------
sc1_fill        2017-11-14 11:36:18     1               NULL
sc1_fill        2017-11-14 11:39:12     1               NULL
sc1_fill        2017-11-14 11:45:26     1               NULL
sc1_weight      2017-11-14 11:50:39     651         00:05:13
sc1_disch       2017-11-14 12:00:45     1               NULL
</code>```

Body:
I placed a sample of some data on SQLFiddle where I'm trying to figure out how to build a query from this data that will give:

The TIMEDIFF() of the TimeStr field of the scl1_fill table and the very next sc1_weight table TimeStr field

example: SELECT TIMEDIFF('2017-11-14 07:21:29','2017-11-14 07:15:56')

I think I need to emulate ROW_NUMBER() with MySQL and I always seem to have trouble with that for some reason using variables and sub queries to get the row numbers, etc.

I tried quite a few things and came up short every time so not even sure it's worth showing what I tried so I will provide what I have and the expected results for visualization/clarification.

Essentially when the sc1_fill gets a 1 value the device starts to fill and when the sc1_weight gets any value then that means it met the weight setpoint and gives back a value at that point.

Getting the time difference between the two will show the amount of time it took from the time the sc1_fill started until the very next record time wise the sc1_weight gets any value ran.

I figured I could throw this as a value on the sc1_weight records with the TIMEDIFF() and have a new column and have all other records show NULL and that'd work (see Expected Results).

Full Table Data

(Always and only get data from one specific date so e.g. WHERE TimeStr LIKE '2017-11-14%')

| test_tbl |               TimeStr |   Value |
----------------------------------------------
sc1_setpnt      2017-11-14 00:05:01     650
sc1_disch       2017-11-14 07:10:24     1
sc1_fill        2017-11-14 07:15:56     1
sc1_weight      2017-11-14 07:21:29     651
sc1_disch       2017-11-14 07:26:18     1
sc1_fill        2017-11-14 07:27:32     1
sc1_weight      2017-11-14 07:33:07     650
sc1_disch       2017-11-14 08:18:36     1
sc1_fill        2017-11-14 08:19:53     1
sc1_weight      2017-11-14 08:25:29     651
sc1_disch       2017-11-14 08:30:21     1
sc1_fill        2017-11-14 08:31:39     1
sc1_weight      2017-11-14 08:37:20     650
sc1_disch       2017-11-14 08:46:00     1
sc1_fill        2017-11-14 08:47:17     1
sc1_weight      2017-11-14 08:52:50     649
sc1_disch       2017-11-14 09:03:22     1
sc1_fill        2017-11-14 09:04:36     1
sc1_weight      2017-11-14 09:10:10     651
sc1_disch       2017-11-14 09:18:45     1
sc1_fill        2017-11-14 09:20:35     1
sc1_weight      2017-11-14 09:26:11     650
sc1_disch       2017-11-14 09:36:40     1
sc1_fill        2017-11-14 09:37:59     1
sc1_weight      2017-11-14 09:43:39     650
sc1_disch       2017-11-14 09:46:55     1
sc1_fill        2017-11-14 09:53:49     1
sc1_weight      2017-11-14 09:59:42     650
sc1_disch       2017-11-14 10:36:06     1
sc1_fill        2017-11-14 10:37:27     1
sc1_weight      2017-11-14 10:43:14     650
sc1_disch       2017-11-14 10:50:44     1
sc1_fill        2017-11-14 10:52:01     1
sc1_weight      2017-11-14 10:57:47     650
sc1_disch       2017-11-14 11:05:46     1
sc1_fill        2017-11-14 11:07:19     1
sc1_weight      2017-11-14 11:12:48     650
sc1_disch       2017-11-14 11:25:25     1
sc1_fill        2017-11-14 11:36:18     1
sc1_fill        2017-11-14 11:39:12     1
sc1_fill        2017-11-14 11:45:26     1
sc1_weight      2017-11-14 11:50:39     651
sc1_disch       2017-11-14 12:00:45     1
sc1_fill        2017-11-14 12:04:44     1
sc1_weight      2017-11-14 12:10:16     651
sc1_disch       2017-11-14 12:58:48     1
sc1_fill        2017-11-14 13:00:01     1
sc1_weight      2017-11-14 13:05:23     651
sc1_disch       2017-11-14 13:06:19     1
sc1_fill        2017-11-14 13:10:52     1
sc1_weight      2017-11-14 13:16:19     650
sc1_disch       2017-11-14 13:18:27     1
sc1_fill        2017-11-14 13:24:35     1
sc1_weight      2017-11-14 13:30:01     651
sc1_disch       2017-11-14 13:31:35     1
sc1_fill        2017-11-14 13:35:40     1
sc1_weight      2017-11-14 13:41:05     650
sc1_disch       2017-11-14 13:47:04     1
sc1_fill        2017-11-14 13:50:19     1
sc1_weight      2017-11-14 13:55:43     649
sc1_disch       2017-11-14 14:06:57     1
sc1_fill        2017-11-14 14:08:11     1
sc1_weight      2017-11-14 14:13:32     651
sc1_disch       2017-11-14 14:26:10     1
sc1_fill        2017-11-14 14:27:24     1
sc1_weight      2017-11-14 14:32:49     650
sc1_disch       2017-11-14 14:42:00     1
sc1_fill        2017-11-14 14:43:11     1
sc1_weight      2017-11-14 14:48:25     650

Expected Results

| test_tbl |               TimeStr |   Value |     FillTime |
-------------------------------------------------------------
sc1_setpnt      2017-11-14 00:05:01     650              NULL
sc1_disch       2017-11-14 07:10:24     1                NULL
sc1_fill        2017-11-14 07:15:56     1                NULL
sc1_weight      2017-11-14 07:21:29     651          00:05:33
sc1_disch       2017-11-14 07:26:18     1                NULL
sc1_fill        2017-11-14 07:27:32     1                NULL
sc1_weight      2017-11-14 07:33:07     650          00:05:35
sc1_disch       2017-11-14 08:18:36     1                NULL
sc1_fill        2017-11-14 08:19:53     1                NULL
sc1_weight      2017-11-14 08:25:29     651          00:05:36
sc1_disch       2017-11-14 08:30:21     1                NULL
sc1_fill        2017-11-14 08:31:39     1                NULL
sc1_weight      2017-11-14 08:37:20     650         00:05:41
sc1_disch       2017-11-14 08:46:00     1                NULL

Making Matters Worse

Okay to make matters worse, it seems at times there are multiple sc1_fill values of 1 before the subsequent sc1_weight value but I would only need to calculate the most recent or newest TimeStr of the set to get the fill time (e.g. SELECT TIMEDIFF('2017-11-14 11:50:39','2017-11-14 11:45:26'))

Expected results where this is the case

| test_tbl |               TimeStr |   Value |     FillTime |
-------------------------------------------------------------
sc1_fill        2017-11-14 11:36:18     1               NULL
sc1_fill        2017-11-14 11:39:12     1               NULL
sc1_fill        2017-11-14 11:45:26     1               NULL
sc1_weight      2017-11-14 11:50:39     651         00:05:13
sc1_disch       2017-11-14 12:00:45     1               NULL

Body:
Whilst you didn't request this summary output, I arrived at an approach that may be of use, a result looks like this

+----+---------+--------+---------------------+---------------------+----------+--------------+
|    | filllno | weight |     start_fill      |      end_fill       | duration | num_of_fills |
+----+---------+--------+---------------------+---------------------+----------+--------------+
|  1 |       0 |    651 | 14.11.2017 07:15:56 | 14.11.2017 07:21:29 | 00:05:33 |            1 |
|  2 |       1 |    650 | 14.11.2017 07:27:32 | 14.11.2017 07:33:07 | 00:05:35 |            1 |
|  3 |       2 |    651 | 14.11.2017 08:19:53 | 14.11.2017 08:25:29 | 00:05:36 |            1 |
|  4 |       3 |    650 | 14.11.2017 08:31:39 | 14.11.2017 08:37:20 | 00:05:41 |            1 |
|  5 |       4 |    649 | 14.11.2017 08:47:17 | 14.11.2017 08:52:50 | 00:05:33 |            1 |
|  6 |       5 |    651 | 14.11.2017 09:04:36 | 14.11.2017 09:10:10 | 00:05:34 |            1 |
|  7 |       6 |    650 | 14.11.2017 09:20:35 | 14.11.2017 09:26:11 | 00:05:36 |            1 |
|  8 |       7 |    650 | 14.11.2017 09:37:59 | 14.11.2017 09:43:39 | 00:05:40 |            1 |
|  9 |       8 |    650 | 14.11.2017 09:53:49 | 14.11.2017 09:59:42 | 00:05:53 |            1 |
| 10 |       9 |    650 | 14.11.2017 10:37:27 | 14.11.2017 10:43:14 | 00:05:47 |            1 |
| 11 |      10 |    650 | 14.11.2017 10:52:01 | 14.11.2017 10:57:47 | 00:05:46 |            1 |
| 12 |      11 |    650 | 14.11.2017 11:07:19 | 14.11.2017 11:12:48 | 00:05:29 |            1 |
| 13 |      12 |    651 | 14.11.2017 11:45:26 | 14.11.2017 11:50:39 | 00:05:13 |            3 |
| 14 |      13 |    651 | 14.11.2017 12:04:44 | 14.11.2017 12:10:16 | 00:05:32 |            1 |
| 15 |      14 |    651 | 14.11.2017 13:00:01 | 14.11.2017 13:05:23 | 00:05:22 |            1 |
| 16 |      15 |    650 | 14.11.2017 13:10:52 | 14.11.2017 13:16:19 | 00:05:27 |            1 |
| 17 |      16 |    651 | 14.11.2017 13:24:35 | 14.11.2017 13:30:01 | 00:05:26 |            1 |
| 18 |      17 |    650 | 14.11.2017 13:35:40 | 14.11.2017 13:41:05 | 00:05:25 |            1 |
| 19 |      18 |    649 | 14.11.2017 13:50:19 | 14.11.2017 13:55:43 | 00:05:24 |            1 |
| 20 |      19 |    651 | 14.11.2017 14:08:11 | 14.11.2017 14:13:32 | 00:05:21 |            1 |
| 21 |      20 |    650 | 14.11.2017 14:27:24 | 14.11.2017 14:32:49 | 00:05:25 |            1 |
| 22 |      21 |    650 | 14.11.2017 14:43:11 | 14.11.2017 14:48:25 | 00:05:14 |            1 |
+----+---------+--------+---------------------+---------------------+----------+--------------+

Demo here

select
      case when value = 1 then fillno else fillno-2 end filllno
    , max(value)                                        weight
    , max(case when value = 1 then TimeStr end)         start_fill
    , max(TimeStr)                                      end_fill
    , timediff(max(TimeStr),max(case when value = 1 then TimeStr end)) duration
    , count(*) - 1                                      num_of_fills
from (
      SELECT *
      , IF(value <> 1, @prev := value, @prev) pweight
      , IF(value <> 1, @counter := @counter+1, @counter - 1) fillno
      FROM test_tbl
      cross join (select @counter :=0, @prev:=0) vars
      where tbl in ('sc1_fill','sc1_weight','sc1_setpnt')
      order by TimeStr ASC
    ) d
where tbl in ('sc1_fill','sc1_weight')
group by
    case when value = 1 then fillno else fillno-2 end
order by start_fill ASC
;

The inner subquery prepares the rows with information that will align the fills to weight (via "fillno") and hence permits the aggregated view you see above. Those rows look like this sample:

+----+------------+---------------------+-------+--------------+----------+---------+--------+
|    |    tbl     |       TimeStr       | Value | @counter :=0 | @prev:=0 | pweight | fillno |
+----+------------+---------------------+-------+--------------+----------+---------+--------+
|  1 | sc1_setpnt | 14.11.2017 00:05:01 |   650 |            0 |        0 |     650 |      1 |
|  2 | sc1_fill   | 14.11.2017 07:15:56 |     1 |            0 |        0 |     650 |      0 |
|  3 | sc1_weight | 14.11.2017 07:21:29 |   651 |            0 |        0 |     651 |      2 |
|  4 | sc1_fill   | 14.11.2017 07:27:32 |     1 |            0 |        0 |     651 |      1 |
|  5 | sc1_weight | 14.11.2017 07:33:07 |   650 |            0 |        0 |     650 |      3 |
|  6 | sc1_fill   | 14.11.2017 08:19:53 |     1 |            0 |        0 |     650 |      2 |
|  7 | sc1_weight | 14.11.2017 08:25:29 |   651 |            0 |        0 |     651 |      4 |
|  8 | sc1_fill   | 14.11.2017 08:31:39 |     1 |            0 |        0 |     651 |      3 |
|  9 | sc1_weight | 14.11.2017 08:37:20 |   650 |            0 |        0 |     650 |      5 |
| 10 | sc1_fill   | 14.11.2017 08:47:17 |     1 |            0 |        0 |     650 |      4 |
| 11 | sc1_weight | 14.11.2017 08:52:50 |   649 |            0 |        0 |     649 |      6 |
| 12 | sc1_fill   | 14.11.2017 09:04:36 |     1 |            0 |        0 |     649 |      5 |
+----+------------+---------------------+-------+--------------+----------+---------+--------+

The logic does account for 2 or more fill events as requested but also counts these so you can see any that have occurred.


来源: stackexchange

问:
How to install multiple openjdk versions on alpine-based docker container
I wish to install jdk7 and jdk8 on an alpine container side by side. I would like to pick jdk7 only if an env variable is set.

I've chained FROM openjdk:7-alpine and FROM openjdk:8-alpine, but regardless of their relative order, the latter one overwrites the former. So, I am left with only 1 installation as seen in '/usr/lib/jvm'.

Why I need this:

I need this setup for a slave container for Jenkins. Now, jenkins remoting jar runs ONLY on jdk8 now. So, I need it. Plus, since I am spawning this container for a project which needs jdk7 as default jdk, I need that too.

My Dockerfile: https://github.com/ankurshashcode/docker-slave/blob/alpine/Dockerfile

答:
You should keep it simple and use one base image.

Use openjdk7 as base image, install openjdk8 as a package.
This will overwrite openjdk7 as the default JDK while leaving it in the image.

```<code>   # Example Dockerfile
   FROM openjdk:7-alpine
   RUN apk add --no-cache openjdk8

   # Other setup...
</code>```

Verify

```<code>$> java -version
openjdk version "1.8.0_131"
OpenJDK Runtime Environment (IcedTea 3.4.0) (Alpine 8.131.11-r2)
OpenJDK 64-Bit Server VM (build 25.131-b11, mixed mode)

$> ls /usr/lib/jvm/
default-jvm       java-1.7-openjdk  java-1.8-openjdk
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You should keep it simple and use one base image.

Use openjdk7 as base image, install openjdk8 as a package.
This will overwrite openjdk7 as the default JDK while leaving it in the image.

   # Example Dockerfile
   FROM openjdk:7-alpine
   RUN apk add --no-cache openjdk8

   # Other setup...

Verify

$> java -version
openjdk version "1.8.0_131"
OpenJDK Runtime Environment (IcedTea 3.4.0) (Alpine 8.131.11-r2)
OpenJDK 64-Bit Server VM (build 25.131-b11, mixed mode)

$> ls /usr/lib/jvm/
default-jvm       java-1.7-openjdk  java-1.8-openjdk

ContentLicense: CC BY-SA 3.0


问:
How to filter users in mysql database based on their star rating
So I am Currently working on a project where I need to filter active users based on the star rating from a select input field.

Below is my users table

```<code>| id | username | firstname | lastname | description | active |
---------------------------------------------------------------
| 2  | kay      | Albert    | Kojo     | Tall        | 1      |
| 3  | kay123   | Mary      | Thompson | Tall        | 1      |
| 4  | kay124   | Francis   | Addai    |             | 1      |
</code>```

Below is my user_reviews table

```<code>| id | user_id| rating |
------------------------
| 1  |   2    |  5     |
| 2  |   3    |  3     |
</code>```

Below is my current query:

```<code>$ratings = mysqli_real_escape_string($db, $_POST['rating']);

SELECT
  *,
  users.id,
  FORMAT(AVG( user_reviews.rating ), 1) AS rating_value,
  count( user_reviews.user_id ) AS review_count
FROM
  users
  LEFT JOIN user_reviews ON users.id = user_reviews.user_id
WHERE
  users.username LIKE '%%'
AND users.active = 1 AND (users.description != "" OR users.description IS
  NOT NULL)
GROUP BY
  users.id
HAVING
  $ratings <= rating_value
ORDER BY
  review_count DESC
</code>```

The above query only returns users who are found in user_reviews table. I would be very glad if someone can help me retrieve users who are in the user_reviews table and users who are not.

答:
You can try this query:

```<code>SELECT
   users.*,
   (SELECT FORMAT(AVG(rating),1) FROM user_reviews where users.id = user_reviews.user_id) AS rating_value,
   (SELECT count(user_id) FROM user_reviews where users.id = user_reviews.user_id) AS review_count
FROM
   users
WHERE
   users.username LIKE '%%'
   AND users.active = 1 AND (users.description != "" OR users.description IS
   NOT NULL)
HAVING
   $rating <= rating_value
ORDER BY
   review_count DESC
</code>```

It will return the output like below:

(Without HAVING $rating <= rating_value)

```<code>| id | username |firstname | lastname | description | active | rating_value | review_count |
----------------------------------------------------------------------------------
| 2  | kay      | Albert   | Kojo     | Tall        | 1      | 5.0          |  1           |
| 3  | kay123   | Mary     | Thompson | Tall        | 1      | 3.0          |  1           |
| 4  | kay134   | Francis  | Addai    |             | 1      |  NULL        |  0           |
</code>```

(With HAVING $rating <= rating_value, where $rating == 4)

```<code>| id | username |firstname | lastname | description | active | rating_value | review_count |
----------------------------------------------------------------------------------
| 2  | kay      | Albert   | Kojo     | Tall        | 1      | 5.0          |  1           |
</code>```

Note:

We don't need to use the GROUP_BY as the GROUP_BY will make your results only show the ones in relation.

Body:
So I am Currently working on a project where I need to filter active users based on the star rating from a select input field.

Below is my users table

| id | username | firstname | lastname | description | active |
---------------------------------------------------------------
| 2  | kay      | Albert    | Kojo     | Tall        | 1      |
| 3  | kay123   | Mary      | Thompson | Tall        | 1      |
| 4  | kay124   | Francis   | Addai    |             | 1      |

Below is my user_reviews table

| id | user_id| rating |
------------------------
| 1  |   2    |  5     |
| 2  |   3    |  3     |

Below is my current query:

$ratings = mysqli_real_escape_string($db, $_POST['rating']);

SELECT
  *,
  users.id,
  FORMAT(AVG( user_reviews.rating ), 1) AS rating_value,
  count( user_reviews.user_id ) AS review_count
FROM
  users
  LEFT JOIN user_reviews ON users.id = user_reviews.user_id
WHERE
  users.username LIKE '%%'
AND users.active = 1 AND (users.description != "" OR users.description IS
  NOT NULL)
GROUP BY
  users.id
HAVING
  $ratings <= rating_value
ORDER BY
  review_count DESC

The above query only returns users who are found in user_reviews table. I would be very glad if someone can help me retrieve users who are in the user_reviews table and users who are not.

Body:
You can try this query:

SELECT
   users.*,
   (SELECT FORMAT(AVG(rating),1) FROM user_reviews where users.id = user_reviews.user_id) AS rating_value,
   (SELECT count(user_id) FROM user_reviews where users.id = user_reviews.user_id) AS review_count
FROM
   users
WHERE
   users.username LIKE '%%'
   AND users.active = 1 AND (users.description != "" OR users.description IS
   NOT NULL)
HAVING
   $rating <= rating_value
ORDER BY
   review_count DESC

It will return the output like below:

(Without HAVING $rating <= rating_value)

| id | username |firstname | lastname | description | active | rating_value | review_count |
----------------------------------------------------------------------------------
| 2  | kay      | Albert   | Kojo     | Tall        | 1      | 5.0          |  1           |
| 3  | kay123   | Mary     | Thompson | Tall        | 1      | 3.0          |  1           |
| 4  | kay134   | Francis  | Addai    |             | 1      |  NULL        |  0           |

(With HAVING $rating <= rating_value, where $rating == 4)

| id | username |firstname | lastname | description | active | rating_value | review_count |
----------------------------------------------------------------------------------
| 2  | kay      | Albert   | Kojo     | Tall        | 1      | 5.0          |  1           |

Note:

We don't need to use the GROUP_BY as the GROUP_BY will make your results only show the ones in relation.


问:
how can I get just a single div to refresh on submit as apposed to the entire page?
I am working  with a dynamically  generated page written in PHP. The divon the page contain contents listed  FancyBox  links that open editing screens.
Once editing is complete and the user closes the FancyBox modal the changes
need to be reflected on the parent page.

Right, so I was able to find a solution that refreshes the entire page on submit
using

```<code>  parent.location.reload (true);
</code>```

to refresh the entire parent page. But, that causes a browser prompt
that is confusing to users and a bit of over kill as I really only
need the information edited to refresh.

how can I get just a single div to refresh on submit  as
apposed to the entire page??????

答:
Instead of using submit in html you can submit your form using the ajax - </p>

```<code>$('#formid').submit(function(){
        var data = $(this).serialize();  //this gives you the data of all elements of form in serialized format
        $.ajax({
              type: 'POST',
              dataType:"json",
              url: 'your url',
              data: data,
              success: function(data){

                           //replace the contents of the div you want to refresh here.
                           }
        });
    });
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am working  with a dynamically  generated page written in PHP. The divon the page contain contents listed  FancyBox  links that open editing screens.
Once editing is complete and the user closes the FancyBox modal the changes
need to be reflected on the parent page.

Right, so I was able to find a solution that refreshes the entire page on submit
using

  parent.location.reload (true);

to refresh the entire parent page. But, that causes a browser prompt
that is confusing to users and a bit of over kill as I really only
need the information edited to refresh.

how can I get just a single div to refresh on submit  as
apposed to the entire page??????

Body:
Instead of using submit in html you can submit your form using the ajax -

$('#formid').submit(function(){
        var data = $(this).serialize();  //this gives you the data of all elements of form in serialized format
        $.ajax({
              type: 'POST',
              dataType:"json",
              url: 'your url',
              data: data,
              success: function(data){

                           //replace the contents of the div you want to refresh here.
                           }
        });
    });


问:
Error Gradle sync failed: Failed to find CMake
I try to run an empty project in android studio by using C++.

Error:

Gradle sync failed: Failed to find CMake.
            Install from Android Studio under File/Settings/Appearance & Behavior/System Settings/Android SDK/SDK Tools/CMake.
            Expected CMake executable at C:\Development\android-sdk\cmake\bin\cmake.exe.
            Consult IDE log for more details (Help | Show Log)

I saw android studio sit for help
https://developer.android.com/studio/projects/add-native-code.html#download-ndk

...there was an image:

https://developer.android.com/studio/images/projects/ndk-install_2-2_2x.png

i saw "File/Settings/Appearance & Behavior/System Settings/Android SDK/SDK Tools/CMake." and there was no Cmake option to enable!

答:
Android Studio 3 in OS X

Go to top menu:
Android Studio > Preferences... > Appearance & Behavior > System Settings > Android SDK

Choose the tab named SDK Tools. If there is nothing to show, see status bar, it could be loading... Wait awhile and you will see CMake option

Just check and apply. Wait for installation to finish. Restart Android Studio.


问:
What do I do to get the program to recognize a lower and uppercase A and count them in total?
I have this program and I need it to count the lower and uppercase A's in a data file. I'm not sure what to use between charAt or substring. It's also all in a while loop, and I was getting at the fact that maybe I need to use the next() method? Maybe? I just need to find these characters and count them up in total.</p>

```<code>import static java.lang.System.*;
import java.util.*;
import java.io.*;

public class Java2305{
    public static void main(String args[]){
        new Solution();
}}

class Solution
{
    private Scanner fileScan;

    Solution()
    {
        run();
    }

    void run()
    {
        int count = 0;

        try
        {
            fileScan = new Scanner(new File("letters01.dat"));

            while(fileScan.hasNext() )
            {
                String getA = fileScan.substring("A");
                out.println(getA);
                count++;
            }

        }
        catch(Exception e){}

        out.println();
        out.println("The letter 'A' occurs "+count+" times.");
        out.println();
        out.println();
    }
}
</code>```

答:
Why are you using Scanner?  That is meant for scanning text for delimited tokens using regular expressions, but you are not really using that.

I suggest you use a Reader instead, then you can call its read() method to read individual characters:

```<code>int count = 0;

try
{
    Reader fileReader = new FileReader("letters01.dat");
    /* or:
    Reader fileReader = new InputStreamReader(
        new FileInputStream("letters01.dat"),
        "the file's charset here"
    );
    */

    int value = fileReader.read();
    while (value != -1)
    {
        char ch = (char) value;
        if ((ch == 'a') || (ch == 'A'))
            count++;
        value = fileReader.read();
    }
}
catch(Exception e){}
</code>```

You can use a BufferedReader to read the file more efficiently:

```<code>Reader fileReader = new BufferedReader(new FileReader("letters01.dat"));
/* or:
Reader fileReader = new BufferedReader(
    new InputStreamReader(
        new FileInputStream("letters01.dat"),
        "the file's charset here"
    )
);
*/
</code>```

And then optionally process it line-by-line instead of char-by-char (though you can still do that, too):

```<code>int count = 0;

try
{
    String line = fileReader.readLine();
    while (line != null)
    {
        for(int i = 0; i < line.length(); ++i)
        {
            char ch = line.charAt(i);
            if ((ch == 'a') || (ch == 'A'))
                count++;
        }
        line = fileReader.readLine();
    }
}
catch(Exception e){}
</code>```

Body:
I have this program and I need it to count the lower and uppercase A's in a data file. I'm not sure what to use between charAt or substring. It's also all in a while loop, and I was getting at the fact that maybe I need to use the next() method? Maybe? I just need to find these characters and count them up in total.

import static java.lang.System.*;
import java.util.*;
import java.io.*;

public class Java2305{
    public static void main(String args[]){
        new Solution();
}}

class Solution
{
    private Scanner fileScan;

    Solution()
    {
        run();
    }

    void run()
    {
        int count = 0;

        try
        {
            fileScan = new Scanner(new File("letters01.dat"));

            while(fileScan.hasNext() )
            {
                String getA = fileScan.substring("A");
                out.println(getA);
                count++;
            }

        }
        catch(Exception e){}

        out.println();
        out.println("The letter 'A' occurs "+count+" times.");
        out.println();
        out.println();
    }
}

Body:
Why are you using Scanner?  That is meant for scanning text for delimited tokens using regular expressions, but you are not really using that.

I suggest you use a Reader instead, then you can call its read() method to read individual characters:

int count = 0;

try
{
    Reader fileReader = new FileReader("letters01.dat");
    /* or:
    Reader fileReader = new InputStreamReader(
        new FileInputStream("letters01.dat"),
        "the file's charset here"
    );
    */

    int value = fileReader.read();
    while (value != -1)
    {
        char ch = (char) value;
        if ((ch == 'a') || (ch == 'A'))
            count++;
        value = fileReader.read();
    }
}
catch(Exception e){}

You can use a BufferedReader to read the file more efficiently:

Reader fileReader = new BufferedReader(new FileReader("letters01.dat"));
/* or:
Reader fileReader = new BufferedReader(
    new InputStreamReader(
        new FileInputStream("letters01.dat"),
        "the file's charset here"
    )
);
*/

And then optionally process it line-by-line instead of char-by-char (though you can still do that, too):

int count = 0;

try
{
    String line = fileReader.readLine();
    while (line != null)
    {
        for(int i = 0; i < line.length(); ++i)
        {
            char ch = line.charAt(i);
            if ((ch == 'a') || (ch == 'A'))
                count++;
        }
        line = fileReader.readLine();
    }
}
catch(Exception e){}


问:
Hash table print and insert function
I am writing a hash table function and the data it has is from a text file. The text file has a four digit student ID and a name with embedded spaces. The problem is the insert function doesn't get the first line from the file. I run the program and when I test it, the first student from the file doesn't come up. I check the rest of the students name by inputting their ID's and they output their names. Also, it doesn't output the full name it gets from the file, just the first. If I look up chris campos from the file, I would type in its four digit ID, but only chris will be output not chris campos.

If you want to see the full code, I will edit the post, but I believe the error should be in the code I posted. I think the code is right, but I want to see if others can see the error or how I can improve it.

Also, I am curious, I am using chaining to handle collisions. How can I make the program output all the names in the bucket that have the same four digit ID. If two names have the same ID, how can I make the program output the two names when the user inputs the ID.

2301 Robb Arredondo
5401 Chris Campos
6305 Yogi Bear
9108 Yoshi Man
0310 John Du
1812 Maria Yu
4318 Power Ranger
7122 Bob Chan
8225 Will Boo
5324 Ghost Lee
0134 Mary Su
2150 Jane Mary
1100 Gary Campos
2305 Alan Kong
3420 Bill Nye
5608 Alex Garcia
9112 Goku Nani
6750 Paul Avalos
1220 Jason Noni
9005 Oscar Roger
6550 Geo Qwerty
1112 Mini Me
2315 Garfield Beria
4201 Just Saying
```

<p>Here is how my program gets the data from the file:</p>

```HashTable hashtable;
std::ifstream file("students.txt");
int option;
std::string studentID;
std::string studentName;
std::string line;

if (!file.is_open())
{
    std::cout << "Error in opening file\n";
}
else
{
    while (std::getline(file, line))
    {
        file >> studentID >> studentName;
        hashtable.Insert(studentID, studentName);
    }

    file.close();
}
```

<p>Here is my insert function..</p>

```void HashTable::Insert(std::string ID, std::string name)
{
    int location = Hash(ID, tableSize);

    if (listofStudents[location]->m_idNum == "empty")
    {
        listofStudents[location]->m_idNum = ID;
        listofStudents[location]->m_Name = name;
    }
    else
    {

        Student* ptr = listofStudents[location];
        Student* newStudent = new Student;
        newStudent->m_Name = name;
        newStudent->m_idNum = ID;
        newStudent->next = NULL;

        while (ptr->next != NULL)
        {
            ptr = ptr->next;
        }
        ptr->next = newStudent;
    }

}
```

<p>Here is my retrieve function...</p>

```void HashTable::Retrieve(std::string ID)
{
int location = Hash(ID, tableSize);
Student* ptr;

for (ptr = listofStudents[location]; ptr; ptr = ptr->next)
{
    if (ptr->m_idNum == ID)
    {
        std::cout << "--------------------\n";
        std::cout << "Name of Student: " << ptr->m_Name << std::endl;
        std::cout << "---------------------\n";
    }
    else
        std::cout << "No Student Found\n";
}
}
```

<p>Here is my hash function if you want to see how the hashing technique is working.It converts a string to an int. The reason I am using a string is because I need to use a string for the assignment.</p>

```int HashTable::Hash(const std::string& key, int tablesize)
{
    int hashVal = 0;
    for (int i = 0; i < key.length(); i++)
    {
        hashVal =  37 * hashVal + key[i];
    }
    hashVal %= tablesize;

    if (hashVal < 0)
        hashVal += tablesize;

    return hashVal;
}
```

答:
The culprit is here:

```<code>file >> studentID >> studentName;
</code>```

This doesn't do what you think it does. I would suggest dumping line into a std::stringstream and then extracting the fields from that:

```<code>while (std::getline(file, line))
{
    std::stringstream ss(line);
    std::string ID;
    std::string firstName;
    std::string lastName;

    ss >> ID >> firstName >> lastName;
    hashtable.Insert(studentID, firstName + " " + lastName);
}
</code>```

Note that you are trying to dump the name into a single string, but in fact there are two fields (first and last name), so you need two variables. You can combine them after that into a single string.

P.S. Re the hash table, the STL hashmap implementation (std::unordered_map) is your friend.

Title: Hash table print and insert function

Body:
I am writing a hash table function and the data it has is from a text file. The text file has a four digit student ID and a name with embedded spaces. The problem is the insert function doesn't get the first line from the file. I run the program and when I test it, the first student from the file doesn't come up. I check the rest of the students name by inputting their ID's and they output their names. Also, it doesn't output the full name it gets from the file, just the first. If I look up chris campos from the file, I would type in its four digit ID, but only chris will be output not chris campos.

If you want to see the full code, I will edit the post, but I believe the error should be in the code I posted. I think the code is right, but I want to see if others can see the error or how I can improve it.

Also, I am curious, I am using chaining to handle collisions. How can I make the program output all the names in the bucket that have the same four digit ID. If two names have the same ID, how can I make the program output the two names when the user inputs the ID.

2301 Robb Arredondo
5401 Chris Campos
6305 Yogi Bear
9108 Yoshi Man
0310 John Du
1812 Maria Yu
4318 Power Ranger
7122 Bob Chan
8225 Will Boo
5324 Ghost Lee
0134 Mary Su
2150 Jane Mary
1100 Gary Campos
2305 Alan Kong
3420 Bill Nye
5608 Alex Garcia
9112 Goku Nani
6750 Paul Avalos
1220 Jason Noni
9005 Oscar Roger
6550 Geo Qwerty
1112 Mini Me
2315 Garfield Beria
4201 Just Saying

Here is how my program gets the data from the file:

HashTable hashtable;
std::ifstream file("students.txt");
int option;
std::string studentID;
std::string studentName;
std::string line;

if (!file.is_open())
{
    std::cout << "Error in opening file\n";
}
else
{
    while (std::getline(file, line))
    {
        file >> studentID >> studentName;
        hashtable.Insert(studentID, studentName);
    }

    file.close();
}

Here is my insert function..

void HashTable::Insert(std::string ID, std::string name)
{
    int location = Hash(ID, tableSize);

    if (listofStudents[location]->m_idNum == "empty")
    {
        listofStudents[location]->m_idNum = ID;
        listofStudents[location]->m_Name = name;
    }
    else
    {

        Student* ptr = listofStudents[location];
        Student* newStudent = new Student;
        newStudent->m_Name = name;
        newStudent->m_idNum = ID;
        newStudent->next = NULL;

        while (ptr->next != NULL)
        {
            ptr = ptr->next;
        }
        ptr->next = newStudent;
    }

}

Here is my retrieve function...

void HashTable::Retrieve(std::string ID)
{
int location = Hash(ID, tableSize);
Student* ptr;

for (ptr = listofStudents[location]; ptr; ptr = ptr->next)
{
    if (ptr->m_idNum == ID)
    {
        std::cout << "--------------------\n";
        std::cout << "Name of Student: " << ptr->m_Name << std::endl;
        std::cout << "---------------------\n";
    }
    else
        std::cout << "No Student Found\n";
}
}

Here is my hash function if you want to see how the hashing technique is working.It converts a string to an int. The reason I am using a string is because I need to use a string for the assignment.

int HashTable::Hash(const std::string& key, int tablesize)
{
    int hashVal = 0;
    for (int i = 0; i < key.length(); i++)
    {
        hashVal =  37 * hashVal + key[i];
    }
    hashVal %= tablesize;

    if (hashVal < 0)
        hashVal += tablesize;

    return hashVal;
}

Body:
The culprit is here:

file >> studentID >> studentName;

This doesn't do what you think it does. I would suggest dumping line into a std::stringstream and then extracting the fields from that:

while (std::getline(file, line))
{
    std::stringstream ss(line);
    std::string ID;
    std::string firstName;
    std::string lastName;

    ss >> ID >> firstName >> lastName;
    hashtable.Insert(studentID, firstName + " " + lastName);
}

Note that you are trying to dump the name into a single string, but in fact there are two fields (first and last name), so you need two variables. You can combine them after that into a single string.

P.S. Re the hash table, the STL hashmap implementation (std::unordered_map) is your friend.


问:
Error when trying with Azure Government endpoint with Azure Storage Java Library
I am trying to use the Azure Storage Java library with the Azure Government endpoints. My code is as follows.

```<code>CloudStorageAccount account = CloudStorageAccount.parse(connectionString);
</code>```

connectionString has the suffix of Azure Gov cloud. For some reason the values for the blob.storage URI are still marked as blob.core.windows.net and I receive the following error. I am unable to run any blob operations.

```<code>com.microsoft.azure.storage.StorageException: The server encountered an unknown failure: at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:178)
at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:214)
at com.microsoft.azure.storage.blob.CloudBlobContainer.exists(CloudBlobContainer.java:749)
at com.microsoft.azure.storage.blob.CloudBlobContainer.exists(CloudBlobContainer.java:736)
at com.microsoft.azure.storage.blob.CloudBlobContainer.exists(CloudBlobContainer.java:710)
at com.scalegrid.cloudconnector.azure.AzureStorageClient.createContainerIfItDoesntExist(AzureStorageClient.java:369)

java.net.UnknownHostException: XXXX.core.usgovcloudapi.net
ERROR ~ s failed.
Code:12207
</code>```

Is there any way I can get this to work ?

Update

I was using an earlier version of the Azure storage Java. Storage endpoints have not been added at this point. Updating to the newer version fixed it.

答:
I found the snippet of C# code from official page.

```<code>var credentials = new StorageCredentials(storageAccountName, storageAccountKey);

var storageAccount = new CloudStorageAccount(credentials, "core.usgovcloudapi.net", useHttps: true);
</code>```

So , I think you need to change the way you initialize the client.

I found the above method in the Java official sdk.

```<code>CloudStorageAccount(StorageCredentials storageCredentials, boolean useHttps, String endpointSuffix)
Creates an instance of the CloudStorageAccount class using the specified account credentials.
</code>```

So , please refer to the sample code below to modify your code.

```<code> StorageCredentialsAccountAndKey storageCredentials =  new StorageCredentialsAccountAndKey(<your account name>, <your account key>);

CloudStorageAccount storageAccount  = new CloudStorageAccount(storageCredentials, true, "core.windows.net");

// Create the Azure Files client.
 CloudFileClient fileClient = storageAccount.createCloudFileClient();
</code>```

Please note that you can find your own gov Endpointsuffix parameters  at the end of the connectstring on portal.

Hope it helps you.

Body:
I am trying to use the Azure Storage Java library with the Azure Government endpoints. My code is as follows.

CloudStorageAccount account = CloudStorageAccount.parse(connectionString);

connectionString has the suffix of Azure Gov cloud. For some reason the values for the blob.storage URI are still marked as blob.core.windows.net and I receive the following error. I am unable to run any blob operations.

com.microsoft.azure.storage.StorageException: The server encountered an unknown failure: at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:178)
at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:214)
at com.microsoft.azure.storage.blob.CloudBlobContainer.exists(CloudBlobContainer.java:749)
at com.microsoft.azure.storage.blob.CloudBlobContainer.exists(CloudBlobContainer.java:736)
at com.microsoft.azure.storage.blob.CloudBlobContainer.exists(CloudBlobContainer.java:710)
at com.scalegrid.cloudconnector.azure.AzureStorageClient.createContainerIfItDoesntExist(AzureStorageClient.java:369)

java.net.UnknownHostException: XXXX.core.usgovcloudapi.net
ERROR ~ s failed.
Code:12207

Is there any way I can get this to work ?

Update

I was using an earlier version of the Azure storage Java. Storage endpoints have not been added at this point. Updating to the newer version fixed it.

Body:
I found the snippet of C# code from official page.

var credentials = new StorageCredentials(storageAccountName, storageAccountKey);

var storageAccount = new CloudStorageAccount(credentials, "core.usgovcloudapi.net", useHttps: true);

So , I think you need to change the way you initialize the client.

I found the above method in the Java official sdk.

CloudStorageAccount(StorageCredentials storageCredentials, boolean useHttps, String endpointSuffix)
Creates an instance of the CloudStorageAccount class using the specified account credentials.

So , please refer to the sample code below to modify your code.

 StorageCredentialsAccountAndKey storageCredentials =  new StorageCredentialsAccountAndKey(<your account name>, <your account key>);

CloudStorageAccount storageAccount  = new CloudStorageAccount(storageCredentials, true, "core.windows.net");

// Create the Azure Files client.
 CloudFileClient fileClient = storageAccount.createCloudFileClient();

Please note that you can find your own gov Endpointsuffix parameters  at the end of the connectstring on portal.

Hope it helps you.


问:
How to avoid the overwriting without using .push() in Firebase? Using the autoincrement to generate ID to replace .push()
I try to generate the ID(autoincrement) to replace the unique ID. Could somebody help me to solve this problem? Thank you!

```<code>public void SignUp(){

    int UserCount = 1;
    String identifier ="User" + UserCount;
    Firebase userRef = firebaseRef.child("Users");
    EditText nameInput = (EditText) findViewById(R.id.nameTxt);
    String name = nameInput.getText().toString();

    EditText passInput = (EditText) findViewById(R.id.passwordTxt);
    String password = passInput.getText().toString();

    EditText addrInput = (EditText) findViewById(R.id.addressTxt);
    String address = addrInput.getText().toString();
    if (!name.equals("")){
        Map<String, String> infor= new HashMap<String, String>();
        caloocan.put("Usersname", name);
        caloocan.put("Userspassword", password);
        caloocan.put("Usersaddress", address);

        Map<String, Map<String, String>> users = new HashMap<String, Map<String, String>>();
        users.put(identifier,infor);

        userRef.setValue(users);
        UserCount++;
    }
}
</code>```

Unique ID which is generated by Firebase

Generate the ID by using auto-increment just like I'm using in SQL database

答:
You can try this:

```<code>final DatabaseReference firebaseRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference mCounterRef = firebaseRef.child("counter");
// listen for single change
mCounterRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // getValue() returns Long
        long count = (long) dataSnapshot.child("Users").getValue();

        System.out.println("count before setValue()=" + count);

        mCounterRef.child("count").setValue(++count);  // <= Change to ++count

        System.out.println("count after setValue()=" + count);

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // throw an error if setValue() is rejected
        throw databaseError.toException();
    }
});
</code>```

If the app crashed while running then you should add this part:

```<code>mCounterRef.child("users").setValue(++count, new
    DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError databaseError,
                           DatabaseReference databaseReference) {
            if (databaseError != null) {
                System.out.println("Error: " + databaseError.getMessage());
            }
        }
    });
</code>```

Body:
I try to generate the ID(autoincrement) to replace the unique ID. Could somebody help me to solve this problem? Thank you!

public void SignUp(){

    int UserCount = 1;
    String identifier ="User" + UserCount;
    Firebase userRef = firebaseRef.child("Users");
    EditText nameInput = (EditText) findViewById(R.id.nameTxt);
    String name = nameInput.getText().toString();

    EditText passInput = (EditText) findViewById(R.id.passwordTxt);
    String password = passInput.getText().toString();

    EditText addrInput = (EditText) findViewById(R.id.addressTxt);
    String address = addrInput.getText().toString();
    if (!name.equals("")){
        Map<String, String> infor= new HashMap<String, String>();
        caloocan.put("Usersname", name);
        caloocan.put("Userspassword", password);
        caloocan.put("Usersaddress", address);

        Map<String, Map<String, String>> users = new HashMap<String, Map<String, String>>();
        users.put(identifier,infor);

        userRef.setValue(users);
        UserCount++;
    }
}

Unique ID which is generated by Firebase

Generate the ID by using auto-increment just like I'm using in SQL database

Body:
You can try this:

final DatabaseReference firebaseRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference mCounterRef = firebaseRef.child("counter");
// listen for single change
mCounterRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // getValue() returns Long
        long count = (long) dataSnapshot.child("Users").getValue();

        System.out.println("count before setValue()=" + count);

        mCounterRef.child("count").setValue(++count);  // <= Change to ++count

        System.out.println("count after setValue()=" + count);

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // throw an error if setValue() is rejected
        throw databaseError.toException();
    }
});

If the app crashed while running then you should add this part:

mCounterRef.child("users").setValue(++count, new
    DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError databaseError,
                           DatabaseReference databaseReference) {
            if (databaseError != null) {
                System.out.println("Error: " + databaseError.getMessage());
            }
        }
    });


问:
Sharepoint 2013 - Radio button default check is not working not even script is working
I tried all options like Checked, Checked = true/false etc but non works in SP2013.

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input name="sections" id="option1" type="radio"/></code>```

答:
Firstly, you have the wrong ID for the radio button, the id of this radio is option1. The first step should be to get that element and then change the status of checked. Here's the snippet that could help you.

please try :

```<code>var input = document.getElementById("option1");
input.checked=true;
</code>```

Body:
I tried all options like Checked, Checked = true/false etc but non works in SP2013.

<input name="sections" id="option1" type="radio"/>

Body:
Firstly, you have the wrong ID for the radio button, the id of this radio is option1. The first step should be to get that element and then change the status of checked. Here's the snippet that could help you.

please try :

var input = document.getElementById("option1");
input.checked=true;


问:
How to mass change the link in WordPress?
the thing is, In my WordPress website i have posted some links to some post. and the domain name of the links have been changed and they are so much in an amount in total of 549 posts.the link is like this yourdomain.com/free-access/ and they are in a button. so any suggestions how can i change the domain name. </p>

<p>thanks </p>

答:
You can do a global search and replace with a plugin. There are others but I suggest Better Search and Replace. It's in the WordPress Repository and is free.

Before you make a change like this you should run a full backup, just in case anything goes wrong.

The plugin in question will let you do a dry run, that is you enter your search text and replace text, select the tables you want to search in and then check the box to Run as Dry Run. This will show you where your changes would be made without actually making them, so you're sure you've entered the right search and replace terms.

You can also make changes like this directly on the database tables using SQL but I strongly recommend against it. This tool is much safer.

Body:
the thing is, In my WordPress website i have posted some links to some post. and the domain name of the links have been changed and they are so much in an amount in total of 549 posts.the link is like this yourdomain.com/free-access/ and they are in a button. so any suggestions how can i change the domain name.

thanks


问:
APP freeze when i start it using notification pending intent in nadroid
so I'm using UrhoSharp 1.5.22 and its work perfectly but when i send notification using notification manager and try to click it, the app freeze with white blank page without throwing exception....i even try to put break point and it didn't work ether ... in earlier use of urho 1.1.214 this problem doesn't appear but i don't think i can take instance from Urho Application class that control the scene .
my code of Surface creation is:

```<code>var mLayout = FindViewById<AbsoluteLayout>(Resource.Id.absoluteLayout1);
var surface = UrhoSurface.CreateSurface(this);
mLayout.AddView(surface);
var app = await surface.Show<MyScene>(null, false);
</code>```

and for notification :

```<code>var nMgr = (NotificationManager)GetSystemService(NotificationService);
var notification = new Notification(ico, "blablabla");
Intent intent = new Intent(this, typeof(MainActivity));
intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.SingleTop | ActivityFlags.ClearTask);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent,0);
notification.SetLatestEventInfo(this, "blablabla", newnot, pendingIntent);
nMgr.Notify((int)NotificationFlags.ForegroundService, notification);

ActivityFlags.NewTask neded because i need to start the app from Service
</code>```

// ============== if it was a bug in urho release please let me no if i can take the instance in 1.1.2.14 release for example or it will be fixed in the next version.
thanks .

edit: I'm trying to open the activity from BGService

答:
Modify your ActivityFlags from :

```<code>intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.SingleTop | ActivityFlags.ClearTask);
</code>```

To :

```<code>intent.SetFlags(ActivityFlags.SingleTop | ActivityFlags.ClearTop);
</code>```

Body:
so I'm using UrhoSharp 1.5.22 and its work perfectly but when i send notification using notification manager and try to click it, the app freeze with white blank page without throwing exception....i even try to put break point and it didn't work ether ... in earlier use of urho 1.1.214 this problem doesn't appear but i don't think i can take instance from Urho Application class that control the scene .
my code of Surface creation is:

var mLayout = FindViewById<AbsoluteLayout>(Resource.Id.absoluteLayout1);
var surface = UrhoSurface.CreateSurface(this);
mLayout.AddView(surface);
var app = await surface.Show<MyScene>(null, false);

and for notification :

var nMgr = (NotificationManager)GetSystemService(NotificationService);
var notification = new Notification(ico, "blablabla");
Intent intent = new Intent(this, typeof(MainActivity));
intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.SingleTop | ActivityFlags.ClearTask);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent,0);
notification.SetLatestEventInfo(this, "blablabla", newnot, pendingIntent);
nMgr.Notify((int)NotificationFlags.ForegroundService, notification);

ActivityFlags.NewTask neded because i need to start the app from Service

// ============== if it was a bug in urho release please let me no if i can take the instance in 1.1.2.14 release for example or it will be fixed in the next version.
thanks .

edit: I'm trying to open the activity from BGService

Body:
Modify your ActivityFlags from :

intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.SingleTop | ActivityFlags.ClearTask);

To :

intent.SetFlags(ActivityFlags.SingleTop | ActivityFlags.ClearTop);


问:
Equation for testing if a point is inside a circle
If you have  a circle with center (center_x, center_y) and radius radius, how do you test if a given point with coordinates (x, y) is inside the circle?

答:
Moving into the world of 3D if you want to check if a 3D point is in a Unit Sphere you end up doing something similar. All that is needed to work in 2D is to use 2D vector operations.</p>

```<code>    public static bool Intersects(Vector3 point, Vector3 center, float radius)
    {
        Vector3 displacementToCenter = point - center;

        float radiusSqr = radius * radius;

        bool intersects = displacementToCenter.magnitude < radiusSqr;

        return intersects;
    }
</code>```

OwnerDisplayName: directedition

LastEditorDisplayName: David Segonds

Body:
Moving into the world of 3D if you want to check if a 3D point is in a Unit Sphere you end up doing something similar. All that is needed to work in 2D is to use 2D vector operations.

    public static bool Intersects(Vector3 point, Vector3 center, float radius)
    {
        Vector3 displacementToCenter = point - center;

        float radiusSqr = radius * radius;

        bool intersects = displacementToCenter.magnitude < radiusSqr;

        return intersects;
    }


问:
How to stop "Next" button replacing "Go" button on android 7 soft keyboard while focusing an input of asp website
When I focus on an input of the website on some browsers in Android 7 (Chrome, Firefox...), the "Go" button was replaced by "Next" button. It will be helpful for the form have multiple fields but it's terrible for the asp website, because there is only one form tag in the whole page. It means when I have multiple form in a page, it just moves the focus from this form to another form when I click the "Go/Next" button instead of submitting the form.

Do we have any attribute for the input to ask the OS stop replacing the "Go" button?

Best regards,

Hanh Dang

答:
If you set UseSubmitBehavior="false" the button will be rendered as a <s><button></s> <input type='button'> element with JavaScript that causes the postback (instead of a <input type='submit'> element) and this may be enough to trick the Android browser (btw which browser are you using?) into thinking there is no way to submit the form and it not display the Go button for the last form entry box.

Edit

I see your comment that this did not work. Depending on the type of JavaScript framework you are using you may be able to code a traditional <button> (or anything else like ) and use href="https://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.getpostbackeventreference(v=vs.110).aspx" rel="nofollow noreferrer">GetPostBackEventReference to generate the code to manually initiate a postback (or just call __doPostBack - not recommended but hey, this is old asp.net, right!?).

Body:
If you set UseSubmitBehavior="false" the button will be rendered as a <s><button></s> <input type='button'> element with JavaScript that causes the postback (instead of a <input type='submit'> element) and this may be enough to trick the Android browser (btw which browser are you using?) into thinking there is no way to submit the form and it not display the Go button for the last form entry box.

Edit

I see your comment that this did not work. Depending on the type of JavaScript framework you are using you may be able to code a traditional <button> (or anything else like <a class='btn'>) and use GetPostBackEventReference to generate the code to manually initiate a postback (or just call __doPostBack - not recommended but hey, this is old asp.net, right!?).


问:
statements run in main but not when called from a function
Sorry. I really tried to solve this myself. But i don't understand. The statements ran okay when i place them in main. But when i call them in a function from main, segmentation fault happens. Does it mean memory overflowed?

```<code>void displayTime(char state[]) {
    time_t totalSec = time(NULL);//total no of secs since EPOCH
    struct tm *currTime = localtime(&totalSec); //store local time in struct declared in time.h
    char *result;
    strftime(result, 20, "%Y:%m:%d %H:%M:%S", currTime); //E.g. 2017:11:12 12:30:48 Max is 20 characters including \0
    printf("Program at %s\n", result );
}

int main() {
    displayTime("started");
    return 0;
}
</code>```

答:
```<code>//char * result; // this is just a pointer with no memory to point to
char result[256] = {0,}; // now this will work
strftime(result, 20, "%Y:%m:%d %H:%M:%S", currTime);//E.g. 2017:11:12 12:30:48 Max is 20 characters including \0
</code>```

alternatively

```<code>//char * result; // this is just a pointer with no memory to point to
char *result = malloc( 256 * sizeof(char));
if( result )
{
    strftime(result, 20, "%Y:%m:%d %H:%M:%S", currTime);//E.g. 2017:11:12 12:30:48 Max is 20 characters including \0
}
</code>```

Body:
Sorry. I really tried to solve this myself. But i don't understand. The statements ran okay when i place them in main. But when i call them in a function from main, segmentation fault happens. Does it mean memory overflowed?

void displayTime(char state[]) {
    time_t totalSec = time(NULL);//total no of secs since EPOCH
    struct tm *currTime = localtime(&totalSec); //store local time in struct declared in time.h
    char *result;
    strftime(result, 20, "%Y:%m:%d %H:%M:%S", currTime); //E.g. 2017:11:12 12:30:48 Max is 20 characters including \0
    printf("Program at %s\n", result );
}

int main() {
    displayTime("started");
    return 0;
}

Body:
//char * result; // this is just a pointer with no memory to point to
char result[256] = {0,}; // now this will work
strftime(result, 20, "%Y:%m:%d %H:%M:%S", currTime);//E.g. 2017:11:12 12:30:48 Max is 20 characters including \0

alternatively

//char * result; // this is just a pointer with no memory to point to
char *result = malloc( 256 * sizeof(char));
if( result )
{
    strftime(result, 20, "%Y:%m:%d %H:%M:%S", currTime);//E.g. 2017:11:12 12:30:48 Max is 20 characters including \0
}


问:
How to use this.onclick to check the buttons Id
There are 5 buttons where each button will do a different thing.

The first button will change a paragraph to green (in HTML file, Id="button1").

The second button will change a paragraph to blue (in HTML file, Id="button2").

```<code>window.onload = pageLoad;

function pageLoad() {
  this.onclick = makeChange;
}

function makeChange() {
  var paragraph = document.getElementById("paragraph");
  if (this.id = "button1") {
    paragraph.style.color = "green";
  } else {
    // change the color
  }
}
</code>```

This doesn't work because I can't get the id of the button, I tried to debug it using:

```<code>paragraph.innerHTML = this.id;// I got "undefined"
</code>```

Is there anyway I can get which button is pressed, and based on which button is pressed, change the text color differently? I want to use only 1 function(exclude pageLoad) to do this and I don't to have 5 variableS and 5 onclick lines and no jquery.

```<code>var paragraph = document.GetElementById("button1");
var paragraph = document.GetElementById("button2");
var paragraph = document.GetElementById("button3");
....
</code>```

答:
Using an event listener to leverage Event Delegation has a few advantages over an on event (ex. onclick) property or attribute event handler:

Unlike on event handlers, event listeners can be used multiple times on multiple objects and elements.

By setting the 3rd parameter to true, you can listen for events in capture phase. It's rarely needed.

We can setup a pattern to take advantage of the 3 Event.eventPhases:

Capture: Starting from Event.currentTarget (ex. #set) the event chain goes down the DOM tree to the end of this phase is...

Target: The element that is the origin of the event is the Event.target (ex. #btn*).In simpler terms, e.target is the element clicked, checked, changed, etc. This element will be the context related to the event, in many ways e.target is like this (in this demo, e.target is one of the buttons and this is the ancestor (fieldset#set, e.cT)...

Bubbling: This is the phase after the callback is initiated and the event chain reverses its path back up to the Event.currentTarget. On its way up, should there be any other elements registered to this particular event would also be triggered. This may be an unwanted behavior depending on the developer's intentions and circumstances. For those cases, Event.stopPropagation() can be called (usually placed as the last statement in the callback). Upon reaching the end of the bubbling phase, the e.cT calls the callback (this callback will be in the context of e.target, this context allows us to identify the clicked button)

Event Delegation is a process in which we setup our event listener on a higher level in the DOM (an ancestor element), then at target phase the clicked button will be identified by referencing e.target. This gives us a powerful and eloquent way to handle an unlimited amount of elements with a single event listener. No on event handler is capable of doing this under normal circumstances without the use of specialized interface.

More details are commented in demo

Demo

/* Reference an ancestor element of all the buttons.
|| In this case the best choice would be
|| fieldset#set. You could also use , document,
|| or even window, but the further the ancestor is,
|| the chances of unwanted behavior from other elements
|| become greater.
*/
var set = document.getElementById('set');

/* Register #set on the click event.
|| Now #set is considered the Event.currentTarget.
|| The e.cT (#set) will listen for the event (click)
|| to occur upon itself and any of its decsendants.
|| Once event occurs, #set (e.cT) will run the
|| callback function (findBtn).
*/
set.addEventListener('click', findBtn, false);

/* This is the callback function which is a normal
|| function that is called when a registered event
|| happens.
*/
function findBtn(e) {

  // An array of 5 colors
  var rainbow = ['purple', 'blue', 'green', 'yellow', 'red'];

  // Reference to the paragraph (
)
  var text = document.querySelector('p');

  /* if e,target (the element clicked), is NOT
  || e.cT, then...
  */
  if (e.target !== e.currentTarget) {

    /*...and if e.T (Event.target) tagName is
    || 'BUTTON', then...
    */
    if (e.target.tagName === 'BUTTON') {

      // ...get the button's #id
      var tgtID = e.target.id;

      /* The id of each button is basically just
      || an index number. Although I do not
      || recommend it normally, it is valid to start
      || with a number for an #id.
      || This statement uses the style property to
      || access the paragraph's CSS color property
      || and changes the value according to the
      || index of the rainbow array which in turn is
      || determined by the e.T (button clicked) #id
      */
      text.style.color = rainbow[tgtID];

    }

  }
  // End function
  return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><fieldset id='set'>
  <legend>Event Delegation</legend>
  <button id='0'>Purple</button>
  <button id='1'>Blue</button>
  <button id='2'>Green</button>
  <button id='3'>Yellow</button>
  <button id='4'>Red</button>
</fieldset>

<p>Click any of the five buttons to change this text.</p></code>```

Body:
There are 5 buttons where each button will do a different thing.

The first button will change a paragraph to green (in HTML file, Id="button1").

The second button will change a paragraph to blue (in HTML file, Id="button2").

window.onload = pageLoad;

function pageLoad() {
  this.onclick = makeChange;
}

function makeChange() {
  var paragraph = document.getElementById("paragraph");
  if (this.id = "button1") {
    paragraph.style.color = "green";
  } else {
    // change the color
  }
}

This doesn't work because I can't get the id of the button, I tried to debug it using:

paragraph.innerHTML = this.id;// I got "undefined"

Is there anyway I can get which button is pressed, and based on which button is pressed, change the text color differently? I want to use only 1 function(exclude pageLoad) to do this and I don't to have 5 variableS and 5 onclick lines and no jquery.

var paragraph = document.GetElementById("button1");
var paragraph = document.GetElementById("button2");
var paragraph = document.GetElementById("button3");
....

Body:
Using an event listener to leverage Event Delegation has a few advantages over an on event (ex. onclick) property or attribute event handler:

Unlike on event handlers, event listeners can be used multiple times on multiple objects and elements.

By setting the 3rd parameter to true, you can listen for events in capture phase. It's rarely needed.

We can setup a pattern to take advantage of the 3 Event.eventPhases:

Capture: Starting from Event.currentTarget (ex. #set) the event chain goes down the DOM tree to the end of this phase is...

Target: The element that is the origin of the event is the Event.target (ex. #btn*).In simpler terms, e.target is the element clicked, checked, changed, etc. This element will be the context related to the event, in many ways e.target is like this (in this demo, e.target is one of the buttons and this is the ancestor (fieldset#set, e.cT)...

Bubbling: This is the phase after the callback is initiated and the event chain reverses its path back up to the Event.currentTarget. On its way up, should there be any other elements registered to this particular event would also be triggered. This may be an unwanted behavior depending on the developer's intentions and circumstances. For those cases, Event.stopPropagation() can be called (usually placed as the last statement in the callback). Upon reaching the end of the bubbling phase, the e.cT calls the callback (this callback will be in the context of e.target, this context allows us to identify the clicked button)

Event Delegation is a process in which we setup our event listener on a higher level in the DOM (an ancestor element), then at target phase the clicked button will be identified by referencing e.target. This gives us a powerful and eloquent way to handle an unlimited amount of elements with a single event listener. No on event handler is capable of doing this under normal circumstances without the use of specialized interface.

More details are commented in demo

Demo

/* Reference an ancestor element of all the buttons.
|| In this case the best choice would be
|| fieldset#set. You could also use <body>, document,
|| or even window, but the further the ancestor is,
|| the chances of unwanted behavior from other elements
|| become greater.
*/
var set = document.getElementById('set');

/* Register #set on the click event.
|| Now #set is considered the Event.currentTarget.
|| The e.cT (#set) will listen for the event (click)
|| to occur upon itself and any of its decsendants.
|| Once event occurs, #set (e.cT) will run the
|| callback function (findBtn).
*/
set.addEventListener('click', findBtn, false);

/* This is the callback function which is a normal
|| function that is called when a registered event
|| happens.
*/
function findBtn(e) {

  // An array of 5 colors
  var rainbow = ['purple', 'blue', 'green', 'yellow', 'red'];

  // Reference to the paragraph (<p>)
  var text = document.querySelector('p');

  /* if e,target (the element clicked), is NOT
  || e.cT, then...
  */
  if (e.target !== e.currentTarget) {

    /*...and if e.T (Event.target) tagName is
    || 'BUTTON', then...
    */
    if (e.target.tagName === 'BUTTON') {

      // ...get the button's #id
      var tgtID = e.target.id;

      /* The id of each button is basically just
      || an index number. Although I do not
      || recommend it normally, it is valid to start
      || with a number for an #id.
      || This statement uses the style property to
      || access the paragraph's CSS color property
      || and changes the value according to the
      || index of the rainbow array which in turn is
      || determined by the e.T (button clicked) #id
      */
      text.style.color = rainbow[tgtID];

    }

  }
  // End function
  return false;
}

<fieldset id='set'>
  <legend>Event Delegation</legend>
  <button id='0'>Purple</button>
  <button id='1'>Blue</button>
  <button id='2'>Green</button>
  <button id='3'>Yellow</button>
  <button id='4'>Red</button>
</fieldset>

<p>Click any of the five buttons to change this text.</p>


问:
Error on my program - How to split words by spaces on a list? Python (used Dictionaries, Lists, .txt file)
Hey my program has this which I think should work, I have gone through the whole program and everything seems fine. But somehow the program doesn't split the words in the list by spaces.
I have used lists and dictionaries in my code which seem to work, I have tested a few things but when I input the .txt file everything is fine and the program works perfectly but when you input your own words the program seems to put all of the words with spaces (example of what I mean: if I input house phone keyboard the program adds all 3 words as if they were one)

My question is how can I split the words by spaces when the user inputs the words themselves instead of using a .txt file?

```<code>#These are the helper variables
wordsList = []
wordsDict = {}
words = 0
typeFile = 0
textFile = 0
text = 0
sortValue = 0
#Here we ask the person if they want to input their own words or use a .txt
file
print("Input 'a' to input your own words or input 'b' to input text from a
.txt file")
typeFile = input()

#Here we make an if statement if they chose to input their own words
if typeFile == "a":
    print("enter 'x' when finished")
    while True:
        #Here we ask the user to input their words
        print("Input your words")
        words = input()
        #This will finish asking for input when the user enters x
        if words == 'x':
            break
        #this puts the words on the list
        wordsList.append(words)
#Here we make an if statement if they chose to use a .txt file
if typeFile == "b":
    #This asks for the .txt file they want to open
    words = input("input which .txt file you would like to use
    (text_file.txt)")
    #This opens the file
    textFile = open(words, 'r')
    text = textFile.read()
    #This adds the words of the file into the list and separates each word
    by spaces
    wordsList = text.split()

#This sorts the list
for text in range(len(wordsList)):
        #This looks if the word has been added to the dictionary
        if wordsList[text] in wordsDict.keys():
            #this will add a +1 value to the word if it is in already in the
dictionary
            wordsDict[wordsList[text]] += 1
        #This looks if the word has been added to the dictionary
        if wordsList[text] not in wordsDict.keys():
            #this adds the word to the dictionary if it isnt already in
            wordsDict[wordsList[text]] = 1

#This sorts the words from lowest to highest
sortValue = sorted(wordsDict.items(), key = lambda t:t[1])
#These will print the top 5 used words in the list
print("These are the most used 5 words")
for num in range(1,6):
    print(num,':',sortValue[num*-1])
words = input("Press return to exit.")
</code>```

答:
I'm using python 3.6.3 and the following code works fine for me.</p>

```<code>import os

cmd = None
words_list = list()
words_dict = dict()

while cmd != 'x':
    cmd = input('What you want to do? [a] to enter your own sentence; [i]mport a file; e[x]it:  ')
    if cmd == 'a':
        os.system('clear')
        sentence = input('Enter your sentence: ')
        split_sentence = sentence.split(' ')
        words_list.append(split_sentence)
    elif cmd == 'i':
        # Add code to read each line in file.
        os.system('clear')
        print('Importing file...')
    elif cmd != 'x':
        os.system('clear')
        print(f'{cmd} is an invalid command.')
    else:
        os.system('clear')
        print('Good Bye!')

def list_to_dict(sentence_list):
    for i in sentence_list:
        for j in i:
            if j in words_dict:
                words_dict[j] += 1
            else:
                words_dict[j] = 1
    return words_dict

print(list_to_dict(words_list))
</code>```

Body:
Hey my program has this which I think should work, I have gone through the whole program and everything seems fine. But somehow the program doesn't split the words in the list by spaces.
I have used lists and dictionaries in my code which seem to work, I have tested a few things but when I input the .txt file everything is fine and the program works perfectly but when you input your own words the program seems to put all of the words with spaces (example of what I mean: if I input house phone keyboard the program adds all 3 words as if they were one)

My question is how can I split the words by spaces when the user inputs the words themselves instead of using a .txt file?

#These are the helper variables
wordsList = []
wordsDict = {}
words = 0
typeFile = 0
textFile = 0
text = 0
sortValue = 0
#Here we ask the person if they want to input their own words or use a .txt
file
print("Input 'a' to input your own words or input 'b' to input text from a
.txt file")
typeFile = input()

#Here we make an if statement if they chose to input their own words
if typeFile == "a":
    print("enter 'x' when finished")
    while True:
        #Here we ask the user to input their words
        print("Input your words")
        words = input()
        #This will finish asking for input when the user enters x
        if words == 'x':
            break
        #this puts the words on the list
        wordsList.append(words)
#Here we make an if statement if they chose to use a .txt file
if typeFile == "b":
    #This asks for the .txt file they want to open
    words = input("input which .txt file you would like to use
    (text_file.txt)")
    #This opens the file
    textFile = open(words, 'r')
    text = textFile.read()
    #This adds the words of the file into the list and separates each word
    by spaces
    wordsList = text.split()

#This sorts the list
for text in range(len(wordsList)):
        #This looks if the word has been added to the dictionary
        if wordsList[text] in wordsDict.keys():
            #this will add a +1 value to the word if it is in already in the
dictionary
            wordsDict[wordsList[text]] += 1
        #This looks if the word has been added to the dictionary
        if wordsList[text] not in wordsDict.keys():
            #this adds the word to the dictionary if it isnt already in
            wordsDict[wordsList[text]] = 1

#This sorts the words from lowest to highest
sortValue = sorted(wordsDict.items(), key = lambda t:t[1])
#These will print the top 5 used words in the list
print("These are the most used 5 words")
for num in range(1,6):
    print(num,':',sortValue[num*-1])
words = input("Press return to exit.")

Body:
I'm using python 3.6.3 and the following code works fine for me.

import os

cmd = None
words_list = list()
words_dict = dict()

while cmd != 'x':
    cmd = input('What you want to do? [a] to enter your own sentence; [i]mport a file; e[x]it:  ')
    if cmd == 'a':
        os.system('clear')
        sentence = input('Enter your sentence: ')
        split_sentence = sentence.split(' ')
        words_list.append(split_sentence)
    elif cmd == 'i':
        # Add code to read each line in file.
        os.system('clear')
        print('Importing file...')
    elif cmd != 'x':
        os.system('clear')
        print(f'{cmd} is an invalid command.')
    else:
        os.system('clear')
        print('Good Bye!')

def list_to_dict(sentence_list):
    for i in sentence_list:
        for j in i:
            if j in words_dict:
                words_dict[j] += 1
            else:
                words_dict[j] = 1
    return words_dict

print(list_to_dict(words_list))


问:
Is there something similar to Android's dimens.xml in iOS?
I recently found out that I should be placing all my sizing/dimensions in dimens.xml for Android applications that I want to support multiple screen resolutions.

Is there something similar that I should do in iOS to support multiple screen resolutions? I code all my views in the back end (no storyboards) and when I want to position a view (padding, margins, etc.) I simply add hard-coded numbers to the X and Y properties of the view's frame. Same thing for Width, Height, Font size, etc. I imagine my iOS apps that I coded like this will look awkward on different screen resolutions like this?

By the way, I'm using Xamarin (Xamarin.Android and Xamarin.iOS). But I would understand answers using native code.

答:
There is nothing like dimens in iOS.

I believe proper constraints with AutoLayout can work well on padding,margins,Width,Height,etc.

However, if you still want to find a way to achieve it , here is a temporary workaround.

Create a static Class named Dimens.

```<code>public static class Dimens
{
    public static int Height
    {
        get {
            string device = DeviceHardware.Model;

            if (device.Contains("iPhone4"))
            {
                return 10;
            }
            else if (device.Contains("iPhone5"))
            {
                return 15;
            }
            else if (device.Equals("iPhone 6") || device.Equals("iPhone 6S"))
            {
                return 20;
            }
            else if (device.Equals("iPhone 6 Plus") || device.Equals("iPhone 6S Plus"))
            {
                return 25;
            }
            //other device

            return 0;
        }
    }
}
</code>```

Usage:

```<code>View.Height = Dimens.Height;
</code>```

Here is the plugin which can check your device type.

Body:
There is nothing like dimens in iOS.

I believe proper constraints with AutoLayout can work well on padding,margins,Width,Height,etc.

However, if you still want to find a way to achieve it , here is a temporary workaround.

Create a static Class named Dimens.

public static class Dimens
{
    public static int Height
    {
        get {
            string device = DeviceHardware.Model;

            if (device.Contains("iPhone4"))
            {
                return 10;
            }
            else if (device.Contains("iPhone5"))
            {
                return 15;
            }
            else if (device.Equals("iPhone 6") || device.Equals("iPhone 6S"))
            {
                return 20;
            }
            else if (device.Equals("iPhone 6 Plus") || device.Equals("iPhone 6S Plus"))
            {
                return 25;
            }
            //other device

            return 0;
        }
    }
}

Usage:

View.Height = Dimens.Height;

Here is the plugin which can check your device type.


问:
How to retrieve Orders from Volusion using his API
I have a c# application which connects to Volusion store, I need to get all Orders. I'm trying this

http://mywebsite/net/WebService.aspx?Login="myuser"&EncryptedPassword="mypassword"&EDI_Name=Generic\Orders&SELECT_Columns=*WHERE_Column=o.OrderStatus&WHERE_Value=Processing

and I getting this in response.

```<code><?xml version="1.0" encoding="UTF-8"?><xmldata />
</code>```

I am using Postman to do this. I have an Order already crated in my store in processing status. What I'm doing wrong.

答: Make sure the API user credentials that you are using have the proper level of access or nothing will be returned. I would recommend setting up a separate API account for this specific function not used for general administration. This way you will not have to be concerned about updating the user password and thus you will not have a changing Encrypted Password in turn.</p>

Body:
I have a c# application which connects to Volusion store, I need to get all Orders. I'm trying this

http://mywebsite/net/WebService.aspx?Login="myuser"&EncryptedPassword="mypassword"&EDI_Name=Generic\Orders&SELECT_Columns=*WHERE_Column=o.OrderStatus&WHERE_Value=Processing

and I getting this in response.

<?xml version="1.0" encoding="UTF-8"?><xmldata />

I am using Postman to do this. I have an Order already crated in my store in processing status. What I'm doing wrong.


问:
First tensorflow tutorial doesn't work with different training data
I've recently installed tensorflow on my computer, but I'm confused about some results I'm getting from the first tutorial program. It's a very simple linear regression model that finds W and b for W*x + b = y:

```<code>import tensorflow as tf

# Model parameters
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = W*x + b
y = tf.placeholder(tf.float32)

# loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

# training data
x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
for i in range(1000):
  sess.run(train, {x: x_train, y: y_train})

# evaluate training accuracy
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))
</code>```

result:

```<code>W: [-0.9999969] b: [ 0.99999082] loss: 5.69997e-11
</code>```

It works!

But then I changed the training data from:

```<code>x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
</code>```

to:

```<code>x_train = [145, 146, 147, 148]
y_train = [151, 152, 153, 154]
</code>```

I should theoretically get W: [~1] b: [~6] loss: ~0, but instead I get:

```<code>W: [ nan] b: [ nan] loss: nan
</code>```

Below is a print of i, W, b, and loss after 10 iterations of training

```<code>[0, '0.3', '-0.3', '4.74e+04']
[1, '1276', '8.408', '1.396e+11']
[2, '-2.188e+06', '-1.494e+04', '4.111e+17']
[3, '3.755e+09', '2.563e+07', '1.211e+24']
[4, '-6.445e+12', '-4.399e+10', '3.566e+30']
[5, '1.106e+16', '7.549e+13', '1.05e+37']
[6, '-1.898e+19', '-1.296e+17', 'inf']
[7, '3.257e+22', '2.223e+20', 'inf']
[8, '-5.59e+25', '-3.816e+23', 'inf']
[9, '9.594e+28', '6.548e+26', 'inf']
</code>```

Does anyone know what could be causing this? I'm using Tensorflow 1.4.0 (CPU only) with Python 3.5.2 on Ubuntu 16.04

EDIT: normalizing the data helped, thanks!

答:
Turn down your learning rate

normalize your train data like (x-mean)/std.

I recommend second.You can have a try.

Body:
I've recently installed tensorflow on my computer, but I'm confused about some results I'm getting from the first tutorial program. It's a very simple linear regression model that finds W and b for W*x + b = y:

import tensorflow as tf

# Model parameters
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = W*x + b
y = tf.placeholder(tf.float32)

# loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

# training data
x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
for i in range(1000):
  sess.run(train, {x: x_train, y: y_train})

# evaluate training accuracy
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))

result:

W: [-0.9999969] b: [ 0.99999082] loss: 5.69997e-11

It works!

But then I changed the training data from:

x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]

to:

x_train = [145, 146, 147, 148]
y_train = [151, 152, 153, 154]

I should theoretically get W: [~1] b: [~6] loss: ~0, but instead I get:

W: [ nan] b: [ nan] loss: nan

Below is a print of i, W, b, and loss after 10 iterations of training

[0, '0.3', '-0.3', '4.74e+04']
[1, '1276', '8.408', '1.396e+11']
[2, '-2.188e+06', '-1.494e+04', '4.111e+17']
[3, '3.755e+09', '2.563e+07', '1.211e+24']
[4, '-6.445e+12', '-4.399e+10', '3.566e+30']
[5, '1.106e+16', '7.549e+13', '1.05e+37']
[6, '-1.898e+19', '-1.296e+17', 'inf']
[7, '3.257e+22', '2.223e+20', 'inf']
[8, '-5.59e+25', '-3.816e+23', 'inf']
[9, '9.594e+28', '6.548e+26', 'inf']

Does anyone know what could be causing this? I'm using Tensorflow 1.4.0 (CPU only) with Python 3.5.2 on Ubuntu 16.04

EDIT: normalizing the data helped, thanks!


问:
AngularJS & jQuery - How to find the ID of a child div on a Click event for its parent?
I have code in HTML like:

```<code><div id="edit" ng-click="editFunction($scope)">
  <span id="1">
    click1
  </span>
  <span id="2">
    click2
  </span>
  <span id="3">
    click3
  </span>
  <span id="4">
    click4
  </span>
  ....
</div>
</code>```

In controller.js:

```<code>myDIV.controller('control',function($scope){
   $scope.editFunction($event){
    alert($event.target.id);
   }
});
</code>```

When a user clicks on the div tag, he should click on any of the span tags. Using the code we are able to get the div id.

However, I need to know which span is clicked. Meaning, the ID of that span.

答:
U can use like this </p>

```<code> <div id="edit" ng-click="editFunction($event)">
 element.target.attributes.id.value
</code>```

Body:
I have code in HTML like:

    click1

    click2

    click3

    click4

  ....

In controller.js:

myDIV.controller('control',function($scope){
   $scope.editFunction($event){
    alert($event.target.id);
   }
});

When a user clicks on the div tag, he should click on any of the span tags. Using the code we are able to get the div id.

However, I need to know which span is clicked. Meaning, the ID of that span.

Body:
U can use like this

 <div id="edit" ng-click="editFunction($event)">
 element.target.attributes.id.value