问:
TSQL - Iterate through list of dates, group data, and insert into table
So I have data being imported into a table in the following format. For any months missing, assume the MM, App_Amt, ClaimCnt, and UnqPtCnt columns are 0:

```<code>location|health_plan| plan_type | pcp |  MM  |App_Amt|ClaimCnt|UnqPtCnt|Date
SoJ     |BLUE SHIELD|    COM    | 2384|  18  | 0.00  |   0    |   0    |2014-01-01
SoJ     |BLUE SHIELD|    COM    | 2384|  20  |1430.08|   1    |   1    |2014-02-01
SoJ     |BLUE SHIELD|    COM    | 2384|  19  | 468.69|   4    |   3    |2014-03-01
SoJ     |BLUE SHIELD|    COM    | 2384|  19  | 184.12|   2    |   2    |2014-04-01
SoJ     |BLUE SHIELD|    COM    | 2384|  19  | 184.12|   2    |   2    |2014-05-01
SoJ     |BLUE SHIELD|    COM    | 2384|  15  |2321.79|   3    |   3    |2014-06-01
SoJ     |BLUE SHIELD|    COM    | 2384|  18  | 258.18|   2    |   2    |2014-07-01
SoJ     |BLUE SHIELD|    COM    | 2384|  22  | 258.18|   2    |   2    |2014-08-01
SoJ     |BLUE SHIELD|    COM    | 2384|  83  | 395.29|   3    |   2    |2014-09-01
SoJ     |BLUE SHIELD|    COM    | 2384|  28  | 258.18|   2    |   2    |2014-10-01
SoJ     |BLUE SHIELD|    COM    | 2384|  32  | 571.02|   4    |   4    |2014-11-01
SoJ     |BLUE SHIELD|    COM    | 2384|  14  | 258.18|   2    |   2    |2014-12-01
</code>```

I need to calculate a rolling/trailing 12 months based on this dataset. I will take the average of MM, sum of App_Amt, sum of ClaimCnt, and sum of UnqPtCt and group by location, health_plan, plan_type, and PCP and I have a list of date ranges I want to iterate through:

I am getting this list of dates from the source table itself. It currently has the 1st of the month from the last 3 years. Next month, the data will shift over one month. For example, right now it has a minimum date of 01/01/2014 and maximum date of 11/01/2016 but next month in April the minimum date will be 02/01/2014 and maximum date will be 12/01/2016.

```<code>declare @end_dt date
set @end_dt = dateadd(month,-4,getdate())

select distinct [date] as start_dt,DATEADD(month,11,[date]) end_dt from [dbo].[OON_Summary]

select * from @Rolling where end_dt <= @end_dt

 start_dt | end_dt
2014-01-01|2014-12-01
2014-02-01|2015-01-01
2014-03-01|2015-02-01
2014-04-01|2015-03-01
2014-05-01|2015-04-01
2014-06-01|2015-05-01
2014-07-01|2015-06-01
2014-08-01|2015-07-01
2014-09-01|2015-08-01
2014-10-01|2015-09-01
2014-11-01|2015-10-01
2014-12-01|2015-11-01
2015-01-01|2015-12-01
2015-02-01|2016-01-01
2015-03-01|2016-02-01
2015-04-01|2016-03-01
2015-05-01|2016-04-01
2015-06-01|2016-05-01
2015-07-01|2016-06-01
2015-08-01|2016-07-01
2015-09-01|2016-08-01
2015-10-01|2016-09-01
2015-11-01|2016-10-01
2015-12-01|2016-11-01
</code>```

So far I have this simple query but it's far too manual and I know there must be a better way to automate this.

```<code>declare @start_dt date
declare @end_dt date
set @start_dt = '2014-01-01'
set @end_dt = '2014-12-01'

insert into [dbo].[OON_Rolling12]
  SELECT
  ,[location]
  ,[health plan]
  ,[plan_type]
  ,[pcp]
  ,AVG([MM]) [MM]
  ,SUM([App_Amt]) [App_Amt]
  ,SUM([ClaimCnt]) [ClaimCnt]
  ,SUM([UnqPtCnt]) UnqPtCnt
  ,@end_dt as AsOfDate
FROM [dbo].[OON_Summary]
WHERE [Date] >= @start_dt AND [Date] <= @end_dt
GROUP BY
   [location]
  ,[health plan]
  ,[plan_type]
  ,[pcp]
</code>```

Running the query once will produce the first line in the output below. Essentially I am grouping all of the data from Jan 1 2014 through Dec 1 2014 and calling it Dec 2014 data. How can I iterate through that list of dates and generate the rest of the rows automatically?

```<code>location|health_plan| plan_type | pcp |  MM  |App_Amt|ClaimCnt|UnqPtCnt |AsOfDate
SoJ     |BLUE SHIELD|    COM    | 2384|  25  |6565.83|   27   |   25    |2014-12-01
SoJ     |BLUE SHIELD|    COM    | 2384|  24  |6565.83|   27   |   25    |2015-01-01
SoJ     |BLUE SHIELD|    COM    | 2384|  22  |5135.75|   26   |   24    |2015-02-01
SoJ     |BLUE SHIELD|    COM    | 2384|  20  |4689.06|   22   |   21    |2015-03-01
SoJ     |BLUE SHIELD|    COM    | 2384|  19  |4504.94|   20   |   19    |2015-04-01
SoJ     |BLUE SHIELD|    COM    | 2384|  17  |4320.82|   18   |   17    |2015-05-01
SoJ     |BLUE SHIELD|    COM    | 2384|  16  |1999.03|   15   |   14    |2015-06-01
SoJ     |BLUE SHIELD|    COM    | 2384|  14  |1740.85|   13   |   12    |2015-07-01
SoJ     |BLUE SHIELD|    COM    | 2384|  13  |1482.67|   11   |   10    |2015-08-01
SoJ     |BLUE SHIELD|    COM    | 2384|  6   |1087.38|    8   |   8     |2015-09-01
SoJ     |BLUE SHIELD|    COM    | 2384|  3   |829.20 |    6   |   6     |2015-10-01
SoJ     |BLUE SHIELD|    COM    | 2384|  0   |258.18 |    2   |   2     |2015-11-01
SoJ     |BLUE SHIELD|    COM    | 2384|  0   | 0.00  |    0   |   0     |2015-12-01
</code>```

答:
You can use OUTER APPLY to get the aggregated values for the last 12 months.

```<code>SELECT
   o1.[location]
  ,o1.[health plan]
  ,o1.[plan_type]
  ,o1.[pcp]
  ,o2.[MM]
  ,o2.[App_Amt]
  ,o2.[ClaimCnt]
  ,o2.[UnqPtCnt]
FROM [dbo].[OON_Summary] o1
OUTER APPLY (SELECT AVG([MM]) as [MM]
                   ,SUM([App_Amt]) as [App_Amt]
                   ,SUM([ClaimCnt]) as [ClaimCnt]
                   ,SUM([UnqPtCnt]) as UnqPtCnt
             FROM [dbo].[OON_Summary] o2
             WHERE o1.[location]=o2.[location] AND o1.[health plan]=o2.[health plan]
             AND o1.[plan_type]=o2.[plan_type] AND o1.[pcp]=o2.[pcp]
             AND o2.[date] BETWEEN DATEADD(month,-11,o1.[date]) AND o1.[date]
             ) o2
</code>```

This is slightly easier in sql server versions 2012+ with window functions.

Body:
So I have data being imported into a table in the following format. For any months missing, assume the MM, App_Amt, ClaimCnt, and UnqPtCnt columns are 0:

location|health_plan| plan_type | pcp |  MM  |App_Amt|ClaimCnt|UnqPtCnt|Date
SoJ     |BLUE SHIELD|    COM    | 2384|  18  | 0.00  |   0    |   0    |2014-01-01
SoJ     |BLUE SHIELD|    COM    | 2384|  20  |1430.08|   1    |   1    |2014-02-01
SoJ     |BLUE SHIELD|    COM    | 2384|  19  | 468.69|   4    |   3    |2014-03-01
SoJ     |BLUE SHIELD|    COM    | 2384|  19  | 184.12|   2    |   2    |2014-04-01
SoJ     |BLUE SHIELD|    COM    | 2384|  19  | 184.12|   2    |   2    |2014-05-01
SoJ     |BLUE SHIELD|    COM    | 2384|  15  |2321.79|   3    |   3    |2014-06-01
SoJ     |BLUE SHIELD|    COM    | 2384|  18  | 258.18|   2    |   2    |2014-07-01
SoJ     |BLUE SHIELD|    COM    | 2384|  22  | 258.18|   2    |   2    |2014-08-01
SoJ     |BLUE SHIELD|    COM    | 2384|  83  | 395.29|   3    |   2    |2014-09-01
SoJ     |BLUE SHIELD|    COM    | 2384|  28  | 258.18|   2    |   2    |2014-10-01
SoJ     |BLUE SHIELD|    COM    | 2384|  32  | 571.02|   4    |   4    |2014-11-01
SoJ     |BLUE SHIELD|    COM    | 2384|  14  | 258.18|   2    |   2    |2014-12-01

I need to calculate a rolling/trailing 12 months based on this dataset. I will take the average of MM, sum of App_Amt, sum of ClaimCnt, and sum of UnqPtCt and group by location, health_plan, plan_type, and PCP and I have a list of date ranges I want to iterate through:

I am getting this list of dates from the source table itself. It currently has the 1st of the month from the last 3 years. Next month, the data will shift over one month. For example, right now it has a minimum date of 01/01/2014 and maximum date of 11/01/2016 but next month in April the minimum date will be 02/01/2014 and maximum date will be 12/01/2016.

declare @end_dt date
set @end_dt = dateadd(month,-4,getdate())

select distinct [date] as start_dt,DATEADD(month,11,[date]) end_dt from [dbo].[OON_Summary]

select * from @Rolling where end_dt <= @end_dt

 start_dt | end_dt
2014-01-01|2014-12-01
2014-02-01|2015-01-01
2014-03-01|2015-02-01
2014-04-01|2015-03-01
2014-05-01|2015-04-01
2014-06-01|2015-05-01
2014-07-01|2015-06-01
2014-08-01|2015-07-01
2014-09-01|2015-08-01
2014-10-01|2015-09-01
2014-11-01|2015-10-01
2014-12-01|2015-11-01
2015-01-01|2015-12-01
2015-02-01|2016-01-01
2015-03-01|2016-02-01
2015-04-01|2016-03-01
2015-05-01|2016-04-01
2015-06-01|2016-05-01
2015-07-01|2016-06-01
2015-08-01|2016-07-01
2015-09-01|2016-08-01
2015-10-01|2016-09-01
2015-11-01|2016-10-01
2015-12-01|2016-11-01

So far I have this simple query but it's far too manual and I know there must be a better way to automate this.

declare @start_dt date
declare @end_dt date
set @start_dt = '2014-01-01'
set @end_dt = '2014-12-01'

insert into [dbo].[OON_Rolling12]
  SELECT
  ,[location]
  ,[health plan]
  ,[plan_type]
  ,[pcp]
  ,AVG([MM]) [MM]
  ,SUM([App_Amt]) [App_Amt]
  ,SUM([ClaimCnt]) [ClaimCnt]
  ,SUM([UnqPtCnt]) UnqPtCnt
  ,@end_dt as AsOfDate
FROM [dbo].[OON_Summary]
WHERE [Date] >= @start_dt AND [Date] <= @end_dt
GROUP BY
   [location]
  ,[health plan]
  ,[plan_type]
  ,[pcp]

Running the query once will produce the first line in the output below. Essentially I am grouping all of the data from Jan 1 2014 through Dec 1 2014 and calling it Dec 2014 data. How can I iterate through that list of dates and generate the rest of the rows automatically?

location|health_plan| plan_type | pcp |  MM  |App_Amt|ClaimCnt|UnqPtCnt |AsOfDate
SoJ     |BLUE SHIELD|    COM    | 2384|  25  |6565.83|   27   |   25    |2014-12-01
SoJ     |BLUE SHIELD|    COM    | 2384|  24  |6565.83|   27   |   25    |2015-01-01
SoJ     |BLUE SHIELD|    COM    | 2384|  22  |5135.75|   26   |   24    |2015-02-01
SoJ     |BLUE SHIELD|    COM    | 2384|  20  |4689.06|   22   |   21    |2015-03-01
SoJ     |BLUE SHIELD|    COM    | 2384|  19  |4504.94|   20   |   19    |2015-04-01
SoJ     |BLUE SHIELD|    COM    | 2384|  17  |4320.82|   18   |   17    |2015-05-01
SoJ     |BLUE SHIELD|    COM    | 2384|  16  |1999.03|   15   |   14    |2015-06-01
SoJ     |BLUE SHIELD|    COM    | 2384|  14  |1740.85|   13   |   12    |2015-07-01
SoJ     |BLUE SHIELD|    COM    | 2384|  13  |1482.67|   11   |   10    |2015-08-01
SoJ     |BLUE SHIELD|    COM    | 2384|  6   |1087.38|    8   |   8     |2015-09-01
SoJ     |BLUE SHIELD|    COM    | 2384|  3   |829.20 |    6   |   6     |2015-10-01
SoJ     |BLUE SHIELD|    COM    | 2384|  0   |258.18 |    2   |   2     |2015-11-01
SoJ     |BLUE SHIELD|    COM    | 2384|  0   | 0.00  |    0   |   0     |2015-12-01

Body:
You can use OUTER APPLY to get the aggregated values for the last 12 months.

SELECT
   o1.[location]
  ,o1.[health plan]
  ,o1.[plan_type]
  ,o1.[pcp]
  ,o2.[MM]
  ,o2.[App_Amt]
  ,o2.[ClaimCnt]
  ,o2.[UnqPtCnt]
FROM [dbo].[OON_Summary] o1
OUTER APPLY (SELECT AVG([MM]) as [MM]
                   ,SUM([App_Amt]) as [App_Amt]
                   ,SUM([ClaimCnt]) as [ClaimCnt]
                   ,SUM([UnqPtCnt]) as UnqPtCnt
             FROM [dbo].[OON_Summary] o2
             WHERE o1.[location]=o2.[location] AND o1.[health plan]=o2.[health plan]
             AND o1.[plan_type]=o2.[plan_type] AND o1.[pcp]=o2.[pcp]
             AND o2.[date] BETWEEN DATEADD(month,-11,o1.[date]) AND o1.[date]
             ) o2

This is slightly easier in sql server versions 2012+ with window functions.


来源: stackexchange

问:
Set operations (union, intersection) on Swift array?
Are there any standard library calls I can use to either perform set operations on two arrays, or implement such logic myself (ideally as functionally and also efficiently as possible)?</p>

答:
The most efficient method I know is by using godel numbers.  Google for godel encoding.

The idea is so.  Suppose you have N possible numbers and need to make sets of them.  For example, N=100,000 and want to make sets like {1,2,3}, {5, 88, 19000} etc.

The idea is to keep the list of N prime numbers in memory and for a given set {a, b, c, ...} you encode it as

```<code> prime[a]*prime[b]*prime[c]*...
</code>```

So you encode a set as a BigNumber.  The operations with BigNumbers, despite the fact that they are slower than operations with Integers are still very fast.

To unite 2 sets A, B, you take

```<code>  UNITE(A, B) = lcm(a, b)
</code>```

lowest-common-multiple of A and B as A and B are sets and both numbers.

To make the intersection you take

```<code> INTERSECT(A, B) = gcd (a, b)
</code>```

greatest common divisor.

and so on.

This encoding is called godelization, you can google for more, all the language of arithmetics written using the logic of Frege can be encoded using numbers in this way.

To get the operation is-member?  it is very simple --

```<code>ISMEMBER(x, S) = remainder(s,x)==0
</code>```

To get the cardinal it's a little more complicated --

```<code>CARDINAL(S) = # of prime factors in s
</code>```

you decompose the number S representing the set in product of prime factors and add their exponents.  In case the set does not allow duplicates you will have all exponents 1.

ContentLicense: CC BY-SA 3.0

Body:
The most efficient method I know is by using godel numbers.  Google for godel encoding.

The idea is so.  Suppose you have N possible numbers and need to make sets of them.  For example, N=100,000 and want to make sets like {1,2,3}, {5, 88, 19000} etc.

The idea is to keep the list of N prime numbers in memory and for a given set {a, b, c, ...} you encode it as

 prime[a]*prime[b]*prime[c]*...

So you encode a set as a BigNumber.  The operations with BigNumbers, despite the fact that they are slower than operations with Integers are still very fast.

To unite 2 sets A, B, you take

  UNITE(A, B) = lcm(a, b)

lowest-common-multiple of A and B as A and B are sets and both numbers.

To make the intersection you take

 INTERSECT(A, B) = gcd (a, b)

greatest common divisor.

and so on.

This encoding is called godelization, you can google for more, all the language of arithmetics written using the logic of Frege can be encoded using numbers in this way.

To get the operation is-member?  it is very simple --

ISMEMBER(x, S) = remainder(s,x)==0

To get the cardinal it's a little more complicated --

CARDINAL(S) = # of prime factors in s

you decompose the number S representing the set in product of prime factors and add their exponents.  In case the set does not allow duplicates you will have all exponents 1.


问:
Loop over a file and run a shell script
I have a shell script in Linux:

```<code>#!/bin/bash
#This script is to import tables from mysql to hdfs
source /home/$USER/mysql/source.sh
[ $# -ne 1 ] && { echo "Usage : $0 table ";exit 1; }
table=$1
sqoop import --connect ${domain}:${port}/${database} \
             --username ${username} --password ${password}\
             --query "select * from ${table} where \$CONDITIONS" \
             -m 1 --as-parquetfile --hive-import --hive-database ${hivedatabase} \
             --hive-table ${table} --map-column-java Date=String \
             --target-dir /user/hive/warehouse/${hivedatabase}.db/${table}\
             --outdir /home/$USER/logs/outdir

echo "****************************************************"
</code>```

This script takes table names as the argument. The table names are in a file called tables.txt.

The source.sh file contents:

```<code>domain=jdbc:mysql://XXXXXXXXX
port=3306
database=testing
username=xxxxxx
password=xxxxxxx
hivedatabase=testing
</code>```

Now I want to schedule this script in parallel. What I want to do is schedule this script for 10 tables at a time. Like take the 1st 10 table names from tables.txt and then run this script. If the script is executed for a table then take the 11th table and so on...

Is it possible to do in cron jobs, or how can we achieve that.

Please suggest a best method.

答:
For the purposes of this answer, let's assume your script is in a file named load_data.sh, your settings are in settings.sh, and your list of table names is in tables.txt.  Now you can run:

```<code>xargs --max-procs 10 -n 1 sh load_data.sh < tables.txt
</code>```

Read the xargs man page for details; the --max-procs causes xargs to spawn up to 10 processes at a time, and it will pass a single table name to each invocation.

Title: Loop over a file and run a shell script

Body:
I have a shell script in Linux:

#!/bin/bash
#This script is to import tables from mysql to hdfs
source /home/$USER/mysql/source.sh
[ $# -ne 1 ] && { echo "Usage : $0 table ";exit 1; }
table=$1
sqoop import --connect ${domain}:${port}/${database} \
             --username ${username} --password ${password}\
             --query "select * from ${table} where \$CONDITIONS" \
             -m 1 --as-parquetfile --hive-import --hive-database ${hivedatabase} \
             --hive-table ${table} --map-column-java Date=String \
             --target-dir /user/hive/warehouse/${hivedatabase}.db/${table}\
             --outdir /home/$USER/logs/outdir

echo "****************************************************"

This script takes table names as the argument. The table names are in a file called tables.txt.

The source.sh file contents:

domain=jdbc:mysql://XXXXXXXXX
port=3306
database=testing
username=xxxxxx
password=xxxxxxx
hivedatabase=testing

Now I want to schedule this script in parallel. What I want to do is schedule this script for 10 tables at a time. Like take the 1st 10 table names from tables.txt and then run this script. If the script is executed for a table then take the 11th table and so on...

Is it possible to do in cron jobs, or how can we achieve that.

Please suggest a best method.

Body:
For the purposes of this answer, let's assume your script is in a file named load_data.sh, your settings are in settings.sh, and your list of table names is in tables.txt.  Now you can run:

xargs --max-procs 10 -n 1 sh load_data.sh < tables.txt

Read the xargs man page for details; the --max-procs causes xargs to spawn up to 10 processes at a time, and it will pass a single table name to each invocation.


问:
pandas: replace NaN with the last non-NaN value in column
I have an excel file which lists basketball teams and the players on each team. The first row for a new team states the team name in column 0 and a player on that team in column 1. The next row simply has a player on that team in column 1 (nothing in column 0 as the team is implied from the last stated team). This is repeated for every team.

```<code>Warriors    Stephen Curry
-           Klay Thompson
-           Kevin Durant
Clippers    Chris Paul
-           Blake Griffen
-           JJ Redick
Raptors     Kyle Lowry
-           Demar Derozan
</code>```

I'm importing the data into a pandas dataframe and counting the number of players on each team.

```<code>import pandas as pd
df = read_excel('data.xlsx')
print(df)

     Team        Player
0    Warriors    Stephen Curry
1    NaN         Klay Thompson
2    NaN         Kevin Durant
3    Clippers    Chris Paul
4    NaN         Blake Griffen
5    NaN         JJ Redick
6    Raptors     Kyle Lowry
7    NaN         Demar Derozan
</code>```

Is there anyway I can replace NaN with the appropriate team name (I know I just need to fill in the empty spots in the excel file but it looks much cleaner if I handle this on the import or via pandas). I imagine I need to iterate through the dataframe, store the team name if it's not NaN and replace NaN with the currently stored team name until a new team arises.

If you don't know basketball, my dataframe should look like this when all is said and done:

```<code>     Team        Player
0    Warriors    Stephen Curry
1    Warriors    Klay Thompson
2    Warriors    Kevin Durant
3    Clippers    Chris Paul
4    Clippers    Blake Griffen
5    Clippers    JJ Redick
6    Raptors     Kyle Lowry
7    Raptors     Demar Derozan
</code>```

答:
You can do this using the fillna() method on the dataframe. The method='ffill' tells it to fill forward with the last valid value.

```<code>df.fillna(method='ffill')
</code>```

Body:
I have an excel file which lists basketball teams and the players on each team. The first row for a new team states the team name in column 0 and a player on that team in column 1. The next row simply has a player on that team in column 1 (nothing in column 0 as the team is implied from the last stated team). This is repeated for every team.

Warriors    Stephen Curry
-           Klay Thompson
-           Kevin Durant
Clippers    Chris Paul
-           Blake Griffen
-           JJ Redick
Raptors     Kyle Lowry
-           Demar Derozan

I'm importing the data into a pandas dataframe and counting the number of players on each team.

import pandas as pd
df = read_excel('data.xlsx')
print(df)

     Team        Player
0    Warriors    Stephen Curry
1    NaN         Klay Thompson
2    NaN         Kevin Durant
3    Clippers    Chris Paul
4    NaN         Blake Griffen
5    NaN         JJ Redick
6    Raptors     Kyle Lowry
7    NaN         Demar Derozan

Is there anyway I can replace NaN with the appropriate team name (I know I just need to fill in the empty spots in the excel file but it looks much cleaner if I handle this on the import or via pandas). I imagine I need to iterate through the dataframe, store the team name if it's not NaN and replace NaN with the currently stored team name until a new team arises.

If you don't know basketball, my dataframe should look like this when all is said and done:

     Team        Player
0    Warriors    Stephen Curry
1    Warriors    Klay Thompson
2    Warriors    Kevin Durant
3    Clippers    Chris Paul
4    Clippers    Blake Griffen
5    Clippers    JJ Redick
6    Raptors     Kyle Lowry
7    Raptors     Demar Derozan

Body:
You can do this using the fillna() method on the dataframe. The method='ffill' tells it to fill forward with the last valid value.

df.fillna(method='ffill')


问:
Golang goroutine endless loop memory leak
I have encountered strange (as for a man who is new to golang) behaviour of my goroutine:

```<code>go func(...) {
  for {
    buffer := make([]byte, 1024)
     ...
  }
}
</code>```

It slowly eats RAM. I understand that it is caused by calling make in an endless loop; it just allocates new memory every time. But i don't quite get why this construction:

```<code>  var buffer []byte
  for {
    buffer = make([]byte, 1024)
     ...
    }
  }
</code>```

..works well, while the first one doesn't. Shouldn't garbage collector detect that memory which old buf was pointing at is unreachable in both cases? And maybe there are some other similar traps that a go-newbie should know?

Also, if i will return this goroutine, will leaked memory be freed?

UPD: full memory leaking routine code:

```<code>go func(dataChannel chan []byte, errorChannel chan error) {
  for {
    buf := make([]byte, 1024)
    _, err := conn.Read(buf)
    if err != nil {
      errorChannel<- err
      break
    }
    dataChannel<- buf
  }
} (dataChannel, errorChannel)
</code>```

答: Thanks to JimB and his advice to set enviroment var GODEBUG=gctrace=1, i discovered that i had no env var GOGC set in my system, because of which garbage collector wasn't functioning at all. Setting it to default value was everything that i needed.

Body:
I have encountered strange (as for a man who is new to golang) behaviour of my goroutine:

go func(...) {
  for {
    buffer := make([]byte, 1024)
     ...
  }
}

It slowly eats RAM. I understand that it is caused by calling make in an endless loop; it just allocates new memory every time. But i don't quite get why this construction:

  var buffer []byte
  for {
    buffer = make([]byte, 1024)
     ...
    }
  }

..works well, while the first one doesn't. Shouldn't garbage collector detect that memory which old buf was pointing at is unreachable in both cases? And maybe there are some other similar traps that a go-newbie should know?

Also, if i will return this goroutine, will leaked memory be freed?

UPD: full memory leaking routine code:

go func(dataChannel chan []byte, errorChannel chan error) {
  for {
    buf := make([]byte, 1024)
    _, err := conn.Read(buf)
    if err != nil {
      errorChannel<- err
      break
    }
    dataChannel<- buf
  }
} (dataChannel, errorChannel)


问:
How can i view the MVC Object Model graphically
This page explains MVC result types, in part, by showing a graphic tree of that part of the object model. What tool was used to render that graphic?</p>

答: Add a Class Diagram item to your Visual Studio 2010 project in and drop your classes onto it.</p>

ContentLicense: CC BY-SA 2.5


问:
Address a text field created in Flash from an external class
How can I address a text field created in Flash (lets say its instance name is mytextfield) from an external class?</p>

答:
I don't mean to sound patronizing, I just answering this way in case anyone else may need this information. First if you're working within actionscript 3, When you create a text box you need to make sure that you Embed… the font, unless the characters familie's name begins with an underscore, as in _sans. Second from within the Font Embedding dialogue, you want to make sure you select the Character ranges: option and select the glyphs you're going to need. Not embedding is a mistake many of my students make, even though you may have the actionscript setup right, without the embedded characters nothing will show up.

If it's a click event you want, from within the MovieClip that modifies the field created mytextfield outside itself, the actionscript would looklike this:

```<code>this.addEventListener(MouseEvent.CLICK, clickEvent);

function clickEvent(event: MouseEvent): void {

    Object(this.parent).mytextfield.text = "hello world"; // Relative
}
</code>```

or this will work too:

```<code>this.addEventListener(MouseEvent.CLICK, clickEvent);

function clickEvent(event: MouseEvent): void {

    Object(root).mytextfield.text = "hello world"; // Absolute

}
</code>```

For those of you who are new to all of this, you need to remember that the text box only receives text information. That means that if you're using any type of a number, you'll have to convert it into a string. This will do the job, String().

```<code>this.addEventListener(MouseEvent.CLICK, clickEvent);

function clickEvent(event: MouseEvent): void {

    Object(root).mytextfield.text = String(123); // Absolute

}
</code>```

Hope that helps.

Body:
I don't mean to sound patronizing, I just answering this way in case anyone else may need this information. First if you're working within actionscript 3, When you create a text box you need to make sure that you Embed… the font, unless the characters familie's name begins with an underscore, as in _sans. Second from within the Font Embedding dialogue, you want to make sure you select the Character ranges: option and select the glyphs you're going to need. Not embedding is a mistake many of my students make, even though you may have the actionscript setup right, without the embedded characters nothing will show up.

If it's a click event you want, from within the MovieClip that modifies the field created mytextfield outside itself, the actionscript would looklike this:

this.addEventListener(MouseEvent.CLICK, clickEvent);

function clickEvent(event: MouseEvent): void {

    Object(this.parent).mytextfield.text = "hello world"; // Relative
}

or this will work too:

this.addEventListener(MouseEvent.CLICK, clickEvent);

function clickEvent(event: MouseEvent): void {

    Object(root).mytextfield.text = "hello world"; // Absolute

}

For those of you who are new to all of this, you need to remember that the text box only receives text information. That means that if you're using any type of a number, you'll have to convert it into a string. This will do the job, String().

this.addEventListener(MouseEvent.CLICK, clickEvent);

function clickEvent(event: MouseEvent): void {

    Object(root).mytextfield.text = String(123); // Absolute

}

Hope that helps.


问:
Razor - Converting Json result from controller to a complex object
i have a partial view "_SearchPanel" that has year list dropdown, a classes multiselect control, (some other drop downs - ommitted) and a search button.

I want that when i change selection in year list drop down, only my classes list is refreshed/updated, and not the whole partial view on page.

So i use a JsonResult action in my controller (as opposed to the first time load)

```<code> public JsonResult BindClasses(int yearId)
    {
        ClassRepository repClass = new ClassRepository("name=ge");
        YearRepository repYear = new YearRepository("name=ge");

        var dataClass = repClass.GetClassesByYear(yearId);
        var groupedClassOptions = dataClass.GroupBy(x => x.grade).Select(x => new OptionGroupVM()
        {
            GroupName = "Grade " + x.Key.ToString(),
            Options = x.Select(y => new OptionVM()
            {
                Value = y.classID.ToString(),
                Text = y.classname
            })
        });

        return Json(groupedClassOptions);

    }
</code>```

My javascript

```<code>var dropDownYear = $('#ddlYear');
    dropDownYear.change(function(){
        $("#classList").load(url, {yearId: $(this).val()}, function(result){

            setOptions($('#classList'), @Html.Raw(Json.Encode(new List<int>(){})), result);
        });

    });
</code>```

now the problem is this result is not considered as an object as was the first time (onpageload) here:

```<code>jQuery(function ($) {
   setOptions($('#classList'), @Html.Raw(Json.Encode(Model.SelectedClasses)), @Html.Raw(Json.Encode(Model.ClassOptions)));
 }
</code>```

How do i correct/cast it to be considered as Model.ClassOptions(type: GroupOptionsVM List) object instead of a Json

What I have tried

```<code>    var url = '@Url.Action("BindClasses", "Maps")';
    var dropDownYear = $('#ddlYear');
    dropDownYear.change(function(){
        $("#classList").load(url, {yearId: $(this).val()}, function(result){
            @{var x = new List<OptionGroupVM>();}
            x = result;
            setOptions($('#classList'), @Html.Raw(Json.Encode(new List<int>(){})), x);

        });

    });
</code>```

this gives me some syntax errors!!

UPDATE

[Referring to the previous question Stephen linked in comments]
Since i had to do it for two dropdown lists with slight difference i had created setOptions function in my script

```<code>function setOptions(listBox, selected, groups) {

    // Generate options
    createGroupedOptions(listBox, selected, groups);

    // Attach plug-in
    listBox.multiselect({ enableClickableOptGroups: true, onChange: function(){
        var selectedClassItems = this.$select.val();

    } });

}

function createGroupedOptions(element, selected, groups) {

    for (var i = 0; i < groups.length; i++) {
        var group = groups[i];
        var groupElement = $('<optgroup></optgroup>').attr('label', group.GroupName);
        for (var j = 0; j < group.Options.length; j++) {
            var option = group.Options[j];
            var optionElement = $('<option></option>').val(option.Value).text(option.Text);
            if (selected) {
                if (selected.toString().indexOf(option.Value) >= 0) {
                    optionElement.attr('selected', 'selected')
                }
            } else {
                if (option.IsSelected) {
                    optionElement.attr('selected', 'selected')
                }
            }

            $(groupElement).append(optionElement);
        }
        $(element).append(groupElement);
    }

}
</code>```

CALLING setOptions function

```<code>setOptions($('#classList'), @Html.Raw(Json.Encode(Model.SelectedClasses)), @Html.Raw(Json.Encode(Model.ClassOptions)));
    setOptions($('#indicatorList'), @Html.Raw(Json.Encode(Model.SelectedIndicators)), @Html.Raw(Json.Encode(Model.IndicatorOptions)));
</code>```

答:
Your returning json, so using .load() makes no sense (you would typically use that when the method your calling returns a partial view).

Change your script to create the <optgroup> and <option> elements based on your data your method returns

```<code>var url = '@Url.Action("BindClasses", "Maps")';
var dropDownYear = $('#ddlYear');
dropDownYear.change(function() {
    $.post(url, { yearId: $(this).val() }, function(data) {
        $.each(data, function(index, item) {
            var group = item.GroupName;
            // use the above to build your <optgroup> element
            $.each(item.Options, function(index, item) {
                var value = item.Value;
                var text = item.Text;
                // use the above to build your <option> elements and append to the <optgroup> element
            });
            // append the <optgroup> to the <select id="classList"> element
        });
    });
});
</code>```

Note the details of the code for generating the elements are in the answer to your previous question

Body:
i have a partial view "_SearchPanel" that has year list dropdown, a classes multiselect control, (some other drop downs - ommitted) and a search button.

I want that when i change selection in year list drop down, only my classes list is refreshed/updated, and not the whole partial view on page.

So i use a JsonResult action in my controller (as opposed to the first time load)

 public JsonResult BindClasses(int yearId)
    {
        ClassRepository repClass = new ClassRepository("name=ge");
        YearRepository repYear = new YearRepository("name=ge");

        var dataClass = repClass.GetClassesByYear(yearId);
        var groupedClassOptions = dataClass.GroupBy(x => x.grade).Select(x => new OptionGroupVM()
        {
            GroupName = "Grade " + x.Key.ToString(),
            Options = x.Select(y => new OptionVM()
            {
                Value = y.classID.ToString(),
                Text = y.classname
            })
        });

        return Json(groupedClassOptions);

    }

My javascript

var dropDownYear = $('#ddlYear');
    dropDownYear.change(function(){
        $("#classList").load(url, {yearId: $(this).val()}, function(result){

            setOptions($('#classList'), @Html.Raw(Json.Encode(new List<int>(){})), result);
        });

    });

now the problem is this result is not considered as an object as was the first time (onpageload) here:

jQuery(function ($) {
   setOptions($('#classList'), @Html.Raw(Json.Encode(Model.SelectedClasses)), @Html.Raw(Json.Encode(Model.ClassOptions)));
 }

How do i correct/cast it to be considered as Model.ClassOptions(type: GroupOptionsVM List) object instead of a Json

What I have tried

    var url = '@Url.Action("BindClasses", "Maps")';
    var dropDownYear = $('#ddlYear');
    dropDownYear.change(function(){
        $("#classList").load(url, {yearId: $(this).val()}, function(result){
            @{var x = new List<OptionGroupVM>();}
            x = result;
            setOptions($('#classList'), @Html.Raw(Json.Encode(new List<int>(){})), x);

        });

    });

this gives me some syntax errors!!

UPDATE

[Referring to the previous question Stephen linked in comments]
Since i had to do it for two dropdown lists with slight difference i had created setOptions function in my script

function setOptions(listBox, selected, groups) {

    // Generate options
    createGroupedOptions(listBox, selected, groups);

    // Attach plug-in
    listBox.multiselect({ enableClickableOptGroups: true, onChange: function(){
        var selectedClassItems = this.$select.val();

    } });

}

function createGroupedOptions(element, selected, groups) {

    for (var i = 0; i < groups.length; i++) {
        var group = groups[i];
        var groupElement = $('<optgroup></optgroup>').attr('label', group.GroupName);
        for (var j = 0; j < group.Options.length; j++) {
            var option = group.Options[j];
            var optionElement = $('<option></option>').val(option.Value).text(option.Text);
            if (selected) {
                if (selected.toString().indexOf(option.Value) >= 0) {
                    optionElement.attr('selected', 'selected')
                }
            } else {
                if (option.IsSelected) {
                    optionElement.attr('selected', 'selected')
                }
            }

            $(groupElement).append(optionElement);
        }
        $(element).append(groupElement);
    }

}

CALLING setOptions function

setOptions($('#classList'), @Html.Raw(Json.Encode(Model.SelectedClasses)), @Html.Raw(Json.Encode(Model.ClassOptions)));
    setOptions($('#indicatorList'), @Html.Raw(Json.Encode(Model.SelectedIndicators)), @Html.Raw(Json.Encode(Model.IndicatorOptions)));

Body:
Your returning json, so using .load() makes no sense (you would typically use that when the method your calling returns a partial view).

Change your script to create the <optgroup> and <option> elements based on your data your method returns

var url = '@Url.Action("BindClasses", "Maps")';
var dropDownYear = $('#ddlYear');
dropDownYear.change(function() {
    $.post(url, { yearId: $(this).val() }, function(data) {
        $.each(data, function(index, item) {
            var group = item.GroupName;
            // use the above to build your <optgroup> element
            $.each(item.Options, function(index, item) {
                var value = item.Value;
                var text = item.Text;
                // use the above to build your <option> elements and append to the <optgroup> element
            });
            // append the <optgroup> to the <select id="classList"> element
        });
    });
});

Note the details of the code for generating the elements are in the answer to your previous question


问:
Pip error - could not find a version that satisfies the requirement junos-eznc
Ansible requires Python junos-eznc module:

junos-eznc >= 1.2.2 is required but does not appear to be installed.

It can be installed using pip install junos-eznc

However, when running sudo pip install junos-eznc - I get this:

```<code>Collecting junos-eznc
/usr/lib/python2.6/site-packages/pip/_vendor/requests/packages/urllib3/connection.py:279: SystemTimeWarning: System time is way off (before 2014-01-01). This will probably lead to SSL verification errors
  SystemTimeWarning
/usr/lib/python2.6/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.
  SNIMissingWarning
/usr/lib/python2.6/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
  Could not fetch URL https://pypi.python.org/simple/junos-eznc/: There was a problem confirming the ssl certificate: [Errno 1] _ssl.c:492: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed - skipping
  Could not find a version that satisfies the requirement junos-eznc (from versions: )
No matching distribution found for junos-eznc
</code>```

Can anyone point me in the right direction?

I did find this article: https://github.com/Homebrew/legacy-homebrew/issues/41253

I tried renaming my files and still no luck:

```<code>]$ls
ca-bundle999.crt  ca-bundle999.trust.crt  ca-bundle.jks  exim.pem  localhost.crt  make-dummy-cert  Makefile  renew-dummy-cert
</code>```

答:
The warning message you get is:

System time is way off (before 2014-01-01). This will probably lead to SSL verification errors

And you indeed get the SSL verification error:

certificate verify failed

Solution: change the system date to current.

You also get two warnings (likely non-critical) with a suggestion to upgrade your Python:

You can upgrade to a newer version of Python to solve this.

Solution: upgrade the Python.

Body:
Ansible requires Python junos-eznc module:

junos-eznc >= 1.2.2 is required but does not appear to be installed.

It can be installed using pip install junos-eznc

However, when running sudo pip install junos-eznc - I get this:

Collecting junos-eznc
/usr/lib/python2.6/site-packages/pip/_vendor/requests/packages/urllib3/connection.py:279: SystemTimeWarning: System time is way off (before 2014-01-01). This will probably lead to SSL verification errors
  SystemTimeWarning
/usr/lib/python2.6/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.
  SNIMissingWarning
/usr/lib/python2.6/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
  Could not fetch URL https://pypi.python.org/simple/junos-eznc/: There was a problem confirming the ssl certificate: [Errno 1] _ssl.c:492: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed - skipping
  Could not find a version that satisfies the requirement junos-eznc (from versions: )
No matching distribution found for junos-eznc

Can anyone point me in the right direction?

I did find this article: https://github.com/Homebrew/legacy-homebrew/issues/41253

I tried renaming my files and still no luck:

]$ls
ca-bundle999.crt  ca-bundle999.trust.crt  ca-bundle.jks  exim.pem  localhost.crt  make-dummy-cert  Makefile  renew-dummy-cert


问:
pushing data from an object to a spreadsheet in google scripts
I have grabbed data from my source spreadsheet and placed it into an array of objects that contain name : value pairs for each row in the spreadsheet.

The name comes from the header row in my spreadsheet, and the values come from each following row.

I am then looping through the name and value pairs in the objects and modifying them before they go into the target spreadsheet.

This is what the data looks like in my debugger:

```<code>objectData[29] | Array | [{id:1001, name:"John", cats:"3"}, {id:1002, name:"Shelley", cats:"9"}...]
</code>```

I would like to take the data in this object and place it in the target spreadsheet with the condition that the object names match the column names in the spreadsheet, and the object values are placed on a new row underneath the matching columns.

I'm really new to scripting and am having a horrendous time figuring out how to do this.

答:
This and much more available at https://gist.github.com/mhawksey/1442370

```<code>// setRowsData fills in one row of data per object defined in the objects Array.
// For every Column, it checks if data objects define a value for it.
// Arguments:
//   - sheet: the Sheet Object where the data will be written
//   - objects: an Array of Objects, each of which contains data for a row
//   - optHeadersRange: a Range of cells where the column headers are defined. This
//     defaults to the entire first row in sheet.
//   - optFirstDataRowIndex: index of the first row where data should be written. This
//     defaults to the row immediately below the headers.
function setRowsData(sheet, objects, optHeadersRange, optFirstDataRowIndex) {
  var headersRange = optHeadersRange || sheet.getRange(1, 1, 1, sheet.getMaxColumns());
  var firstDataRowIndex = optFirstDataRowIndex || headersRange.getRowIndex() + 1;
  var headers = normalizeHeaders(headersRange.getValues()[0]);

  var data = [];
  for (var i = 0; i < objects.length; ++i) {
    var values = []
    for (j = 0; j < headers.length; ++j) {
      var header = headers[j];
      values.push(header.length > 0 && objects[i][header] ? objects[i][header] : "");
    }
    data.push(values);
  }
  var destinationRange = sheet.getRange(firstDataRowIndex, headersRange.getColumnIndex(),
                                        objects.length, headers.length);
  destinationRange.setValues(data);
}
</code>```

Edit: I noticed a function used above was not included

```<code>// Returns an Array of normalized Strings.
// Arguments:
//   - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
  var keys = [];
  for (var i = 0; i < headers.length; ++i) {
    var key = normalizeHeader(headers[i]);
    if (key.length > 0) {
      keys.push(key);
    }
  }
  return keys;
}

// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
//   - header: string to normalize
// Examples:
//   "First Name" -> "firstName"
//   "Market Cap (millions) -> "marketCapMillions
//   "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
  var key = "";
  var upperCase = false;
  for (var i = 0; i < header.length; ++i) {
    var letter = header[i];
    if (letter == " " && key.length > 0) {
      upperCase = true;
      continue;
    }
    //if (!isAlnum(letter)) {
    //  continue;
    //}
    if (key.length == 0 && isDigit(letter)) {
      continue; // first character must be a letter
    }
    if (upperCase) {
      upperCase = false;
      key += letter.toUpperCase();
    } else {
      key += letter.toLowerCase();
    }
  }
  return key;
}
</code>```

the link at the top of answer includes code for procedures that you have already accomplished. Seeing how others attain the same goal is often very enlightening.

Body:
I have grabbed data from my source spreadsheet and placed it into an array of objects that contain name : value pairs for each row in the spreadsheet.

The name comes from the header row in my spreadsheet, and the values come from each following row.

I am then looping through the name and value pairs in the objects and modifying them before they go into the target spreadsheet.

This is what the data looks like in my debugger:

objectData[29] | Array | [{id:1001, name:"John", cats:"3"}, {id:1002, name:"Shelley", cats:"9"}...]

I would like to take the data in this object and place it in the target spreadsheet with the condition that the object names match the column names in the spreadsheet, and the object values are placed on a new row underneath the matching columns.

I'm really new to scripting and am having a horrendous time figuring out how to do this.

Body:
This and much more available at https://gist.github.com/mhawksey/1442370

// setRowsData fills in one row of data per object defined in the objects Array.
// For every Column, it checks if data objects define a value for it.
// Arguments:
//   - sheet: the Sheet Object where the data will be written
//   - objects: an Array of Objects, each of which contains data for a row
//   - optHeadersRange: a Range of cells where the column headers are defined. This
//     defaults to the entire first row in sheet.
//   - optFirstDataRowIndex: index of the first row where data should be written. This
//     defaults to the row immediately below the headers.
function setRowsData(sheet, objects, optHeadersRange, optFirstDataRowIndex) {
  var headersRange = optHeadersRange || sheet.getRange(1, 1, 1, sheet.getMaxColumns());
  var firstDataRowIndex = optFirstDataRowIndex || headersRange.getRowIndex() + 1;
  var headers = normalizeHeaders(headersRange.getValues()[0]);

  var data = [];
  for (var i = 0; i < objects.length; ++i) {
    var values = []
    for (j = 0; j < headers.length; ++j) {
      var header = headers[j];
      values.push(header.length > 0 && objects[i][header] ? objects[i][header] : "");
    }
    data.push(values);
  }
  var destinationRange = sheet.getRange(firstDataRowIndex, headersRange.getColumnIndex(),
                                        objects.length, headers.length);
  destinationRange.setValues(data);
}

Edit: I noticed a function used above was not included

// Returns an Array of normalized Strings.
// Arguments:
//   - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
  var keys = [];
  for (var i = 0; i < headers.length; ++i) {
    var key = normalizeHeader(headers[i]);
    if (key.length > 0) {
      keys.push(key);
    }
  }
  return keys;
}

// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
//   - header: string to normalize
// Examples:
//   "First Name" -> "firstName"
//   "Market Cap (millions) -> "marketCapMillions
//   "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
  var key = "";
  var upperCase = false;
  for (var i = 0; i < header.length; ++i) {
    var letter = header[i];
    if (letter == " " && key.length > 0) {
      upperCase = true;
      continue;
    }
    //if (!isAlnum(letter)) {
    //  continue;
    //}
    if (key.length == 0 && isDigit(letter)) {
      continue; // first character must be a letter
    }
    if (upperCase) {
      upperCase = false;
      key += letter.toUpperCase();
    } else {
      key += letter.toLowerCase();
    }
  }
  return key;
}

the link at the top of answer includes code for procedures that you have already accomplished. Seeing how others attain the same goal is often very enlightening.


问:
How to send ACK message to client from server using NetMQ
I am using NetMQ to send messages from many clients to a server which receives the messages and processes them. If I use the pub/sub pattern, I can (ab)use the subscriber socket and use it for the server and clients will be the publishers (the opposite flow, isn't it?). However, I cannot send an acknowledge message to the clients.

If I use the REQ/RESP pattern, I can use the response socket for the server and even send an acknowledge message which can be received by the client. However, if the server misses the message from client, I cannot resend the message (after waiting for a timespan), because I receive an exception

Req.XSend - cannot send another request

-- even after disconnecting the client socket and closing it (it seams that the server socket keeps track of it).

And finally, based on the documentation, I'm not sure if the Dealer/Router is the right pattern to use. As I'm pretty sure that I'm stuck in a very common situation, is there any pattern to implement this scenario using NetMQ?

答:
You are stuck in a very common problem, typically called "Reliable Request-Reply" in 0MQ parlance.

There are several approaches described in the guide, the first is the "lazy pirate". In it you use a REQ/RESP socket pair as described (though REQ/ROUTER would work just as well, and probably better for more than one client). The solution is to dispose of the socket if your ACK times out and create a new one.

The guide does note that swapping a DEALER for the REQ would solve the problem, but adds having to keep track of the envelope yourself. Unless you need async send/receive on the client side for some other reason, I would follow their advice and stick with REQ/ROUTER.

A sample implementation of this pattern can be found on GitHub: https://github.com/NetMQ/Samples/tree/master/src/Pirate%20Pattern


问:
Entity Framework : Value cannot be null. Parameter name: type
When I execute update-database command, it shows this error message

System.ArgumentNullException: Value cannot be null.

  Parameter name: type

at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)

  at System.Activator.CreateInstance(Type type, Object[] args)

  at System.Data.Entity.Migrations.Extensions.ProjectExtensions.GetProjectTypes(Project project, Int32 shellVersion)

  at System.Data.Entity.Migrations.Extensions.ProjectExtensions.IsWebSiteProject(Project project)

  at System.Data.Entity.Migrations.Extensions.ProjectExtensions.GetTargetDir(Project project)

  at System.Data.Entity.Migrations.MigrationsDomainCommand.GetFacade(String configurationTypeName, Boolean useContextWorkingDirectory)

  at System.Data.Entity.Migrations.AddMigrationCommand.Execute(String name, Boolean force, Boolean ignoreChanges)

  at System.Data.Entity.Migrations.AddMigrationCommand.<>c__DisplayClass2.<.ctor>b__0()

  at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)

Value cannot be null.

  Parameter name: type"?

答:
Solution: For me solution was as easy as restarting visual studio.

Senario: I have solution like this:

I changed startup project from Host to the UI.Web project which contains web.config  and then running the update-database command but it gave me the Value cannot be null. exception until I restart visual studio and rerun the  update-database command. This time it behaved normally.


问:
What's the best practice to speed-up query performance?
I have a query which is taking 80 secs for 100 records joining 3 tables which is very bad performance,I am trying to figure out options to retrieve data much quickly?
I am going to use this query in my ASP.net web application and return an object with the corresponding fields.

Following is what I can think of?

1.Is there a better way to write this query?

2.If I split up the queries ,how-could-i-avoid-using-a-mysql-query-in-a-while-loop-in-php

```<code>select distinct spb.software_product_build,spb.date_created,spb.date_announced,ts.suite_name,ssr.MTBF,ssr.CPTH,ssr.TotalProductCrashes,ssr.TotalUniqueCrashes

from software_product_builds spb
inner join software_products sp on spb.software_product_id=sp.id
inner join sp_default_variant spd on   spb.variant_id=spd.default_variant_id
left join bit_sanity_results bsr on bsr.software_product_build_id=spb.software_product_build_id
left join test_suites ts on bsr.test_suite_id=ts.id
left join sns_sanity_results ssr on ssr.software_product_build_id=spb.software_product_build_id
where sp.software_product='XXXX.LA.0.1' order by spb.software_product_build_id desc limit 100
</code>```

答:
You might like my presentation, How to Design Indexes, Really, or the video of me presenting it.

I can't tell only from reading your query what indexes you might already have defined, or what the relationships between your tables are. So it's a bit difficult to make the correct recommendation.

But for example, if you have a table spb and it's joining to table sp, for each row of spb it'll do a lookup to find the matching rows in sp. Having an index in sp will help that lookup.

```<code>from software_product_builds spb
inner join software_products sp
  on spb.software_product_id=sp.id
where sp.software_product='XXXX.LA.0.1'
</code>```

In this case, you also have a constant lookup on the software_product column. So you can reduce the lookup to the subset of those matching rows.

```<code>ALTER TABLE software_products ADD INDEX (software_product, id);
</code>```

This index will help reduce the search down to one row of that table. MySQL may even then decide to reverse the directory of the join because looking up one row in sp and then joining to the matching rows in spb might be the most efficient way.

On the other hand, you have ORDER BY spb.software_product_build_id so MySQL might prefer to use an index on that column so it can scan in index order instead of sorting the result. It can't do that unless it accesses the spb table first in the join order. So make sure you have an index:

```<code>ALTER TABLE software_product_builds ADD INDEX (software_product_build_id);
</code>```

Then let MySQL figure out the most efficient path itself. It picks the best choice surprisingly often.

Likewise for other joins, you'd want to index the column that will be used for the lookups.

```<code>ALTER TABLE sp_default_variant ADD INDEX (default_variant_id);
ALTER TABLE bit_sanity_results ADD INDEX (software_product_build_id);
-- ALTER TABLE test_suites ADD INDEX (id);
ALTER TABLE sns_sanity_results ADD INDEX (software_product_build_id);
</code>```

I commented out the one for test_suites because I assume its id column is the primary key, and that's already indexed implicitly. If the other cases already have indexes or if they are the primary key of the respective table, then skip creating new indexes.

Body:
I have a query which is taking 80 secs for 100 records joining 3 tables which is very bad performance,I am trying to figure out options to retrieve data much quickly?
I am going to use this query in my ASP.net web application and return an object with the corresponding fields.

Following is what I can think of?

1.Is there a better way to write this query?

2.If I split up the queries ,how-could-i-avoid-using-a-mysql-query-in-a-while-loop-in-php

select distinct spb.software_product_build,spb.date_created,spb.date_announced,ts.suite_name,ssr.MTBF,ssr.CPTH,ssr.TotalProductCrashes,ssr.TotalUniqueCrashes

from software_product_builds spb
inner join software_products sp on spb.software_product_id=sp.id
inner join sp_default_variant spd on   spb.variant_id=spd.default_variant_id
left join bit_sanity_results bsr on bsr.software_product_build_id=spb.software_product_build_id
left join test_suites ts on bsr.test_suite_id=ts.id
left join sns_sanity_results ssr on ssr.software_product_build_id=spb.software_product_build_id
where sp.software_product='XXXX.LA.0.1' order by spb.software_product_build_id desc limit 100

Body:
You might like my presentation, How to Design Indexes, Really, or the video of me presenting it.

I can't tell only from reading your query what indexes you might already have defined, or what the relationships between your tables are. So it's a bit difficult to make the correct recommendation.

But for example, if you have a table spb and it's joining to table sp, for each row of spb it'll do a lookup to find the matching rows in sp. Having an index in sp will help that lookup.

from software_product_builds spb
inner join software_products sp
  on spb.software_product_id=sp.id
where sp.software_product='XXXX.LA.0.1'

In this case, you also have a constant lookup on the software_product column. So you can reduce the lookup to the subset of those matching rows.

ALTER TABLE software_products ADD INDEX (software_product, id);

This index will help reduce the search down to one row of that table. MySQL may even then decide to reverse the directory of the join because looking up one row in sp and then joining to the matching rows in spb might be the most efficient way.

On the other hand, you have ORDER BY spb.software_product_build_id so MySQL might prefer to use an index on that column so it can scan in index order instead of sorting the result. It can't do that unless it accesses the spb table first in the join order. So make sure you have an index:

ALTER TABLE software_product_builds ADD INDEX (software_product_build_id);

Then let MySQL figure out the most efficient path itself. It picks the best choice surprisingly often.

Likewise for other joins, you'd want to index the column that will be used for the lookups.

ALTER TABLE sp_default_variant ADD INDEX (default_variant_id);
ALTER TABLE bit_sanity_results ADD INDEX (software_product_build_id);
-- ALTER TABLE test_suites ADD INDEX (id);
ALTER TABLE sns_sanity_results ADD INDEX (software_product_build_id);

I commented out the one for test_suites because I assume its id column is the primary key, and that's already indexed implicitly. If the other cases already have indexes or if they are the primary key of the respective table, then skip creating new indexes.


问:
fnding boundries of browser
Is there any way to find boundary of browser

actually I am showing a div popup. It's working fine but it not showing properly when it comes at boundaries.

so i want to change position of div at boundary.

答: window.innerWidth and window.innerHeight hold the physical dimensions of viewable space. You can then use the left, top, width and height CSS properties to see if an element is inside this boundary.

Title: fnding boundries of browser


问:
Not able to see the Storefront toolkit on the custom isml rendered in the storefront
I am not able to see the Storefront toolkit on the isml rendered in the storefront. It is there on the sitegenesis landing page. But when I supply my pipeline name and start node name in the URL, then the corresponding isml mentioned in the pipeline is rendered, but without the storefront toolkit. Do we have to do some extra configuration? </p>

答: It is possible that your custom template uses a content-type other than text/html. If I recall correctly only templates that set their content type to text/html will receive the storefront toolkit. (text/html is the default)</p>


问:
MonoGame 3.5 solution build error when try to compile code
When i compile the code the solution does not build, this is default code result. I am using vs 2013 professional edition.

答: Open the content pipeline for your project. It seems like you have some content that is broken. I've seen this happen with spritefonts in the past.</p>


问:
Initiating NSManagedObjectContext gives fatal error?
I am working on the last leg of my app and this seems to be the last portion I'm having issue with. Fingers crossed for that, anyway.

I have CoreData all set up and ready to be displayed in a table (hopefully, I can't really view it in a table yet to verify).

The issue I'm having right now is that when the views that implement CoreData load, there is a fatal error that occurs when it initiates my NSManagedObjectContext. Please note that I use two separate ViewControllers to get data in addition to the TableViewController, therefore I have declared a total of 3 NSManagedContextObjects in my app - which I'm not sure if that's the issue or not. The line that is causing it is in my viewDidLoad function. See the code below.

```<code>override func viewDidLoad() {
        super.viewDidLoad()

        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    }
</code>```

I'm not entirely sure how to tackle this, for I was following a tutorial for the whole process.

EDIT: I am going to add all the code that is affected by CoreData so maybe it'll help the problem be solved.

Here is a screenshot of my core data model

AppDelegate

```<code>import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    return true
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    //self.saveContext()
}

// MARK: - Core Data Stack
lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
     */
    let container = NSPersistentContainer(name: "RSDB_1_0_COREDATA")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}
</code>```

}

First View Controller

```<code>let newInfo = GeneralInfo(context:managedObjectContext1)
        newInfo.courseNumber = studCourse
        newInfo.scenarioNumber = studScen

        do {
            try self.managedObjectContext1.save()
        }catch {
            print("Could not save data \(error.localizedDescription)")
        }

        performSegue(withIdentifier: "segue3", sender: self)
</code>```

Different View Controller

```<code> let newEvaluation = GeneralEvaluation(context:managedObjectContext)
        newEvaluation.idScore = String(ID)
        newEvaluation.washScore = String(WASH)
        newEvaluation.totalScore = String(total)

        do {
            try self.managedObjectContext.save()
        }catch {
            print("Could not save data \(error.localizedDescription)")
        }

        performSegue(withIdentifier: "segue4", sender: self)
</code>```

TableViewController

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TheTableViewCell

   let info = courseInfo[indexPath.row]
   let score = scores[indexPath.row]

    cell.CLASS.text = info.courseNumber
    cell.SCENARIO.text = info.scenarioNumber

    cell.WASH.text = score.washScore
    cell.ID.text = score.idScore
    cell.TOTAL.text = score.totalScore
</code>```

答:
It would be helpful to see the text of the error message, and the stack trace.

You could start by breaking down that chain of calls, to narrow down where you're crashing.

```<code>let appDelegate = (UIApplication.shared.delegate as! AppDelegate)
let container = appDelegate.persistentContainer
managedObjectContext = container.viewContext
</code>```

Is your stack (persistent container/persistent store coordinator/managed object model/managed object context instantiated before you load the view controller? It appears not. Since you crash so early, I'm going out on a limb and guessing that you have a spelling error or name mismatch somewhere (a filename that doesn't match what's in your defining code). Or perhaps your MOM is not included as a resource in your bundle?

Body:
I am working on the last leg of my app and this seems to be the last portion I'm having issue with. Fingers crossed for that, anyway.

I have CoreData all set up and ready to be displayed in a table (hopefully, I can't really view it in a table yet to verify).

The issue I'm having right now is that when the views that implement CoreData load, there is a fatal error that occurs when it initiates my NSManagedObjectContext. Please note that I use two separate ViewControllers to get data in addition to the TableViewController, therefore I have declared a total of 3 NSManagedContextObjects in my app - which I'm not sure if that's the issue or not. The line that is causing it is in my viewDidLoad function. See the code below.

override func viewDidLoad() {
        super.viewDidLoad()

        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    }

I'm not entirely sure how to tackle this, for I was following a tutorial for the whole process.

EDIT: I am going to add all the code that is affected by CoreData so maybe it'll help the problem be solved.

Here is a screenshot of my core data model

AppDelegate

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    return true
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    //self.saveContext()
}

// MARK: - Core Data Stack
lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
     */
    let container = NSPersistentContainer(name: "RSDB_1_0_COREDATA")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

}

First View Controller

let newInfo = GeneralInfo(context:managedObjectContext1)
        newInfo.courseNumber = studCourse
        newInfo.scenarioNumber = studScen

        do {
            try self.managedObjectContext1.save()
        }catch {
            print("Could not save data \(error.localizedDescription)")
        }

        performSegue(withIdentifier: "segue3", sender: self)

Different View Controller

 let newEvaluation = GeneralEvaluation(context:managedObjectContext)
        newEvaluation.idScore = String(ID)
        newEvaluation.washScore = String(WASH)
        newEvaluation.totalScore = String(total)

        do {
            try self.managedObjectContext.save()
        }catch {
            print("Could not save data \(error.localizedDescription)")
        }

        performSegue(withIdentifier: "segue4", sender: self)

TableViewController

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TheTableViewCell

   let info = courseInfo[indexPath.row]
   let score = scores[indexPath.row]

    cell.CLASS.text = info.courseNumber
    cell.SCENARIO.text = info.scenarioNumber

    cell.WASH.text = score.washScore
    cell.ID.text = score.idScore
    cell.TOTAL.text = score.totalScore

Body:
It would be helpful to see the text of the error message, and the stack trace.

You could start by breaking down that chain of calls, to narrow down where you're crashing.

let appDelegate = (UIApplication.shared.delegate as! AppDelegate)
let container = appDelegate.persistentContainer
managedObjectContext = container.viewContext

Is your stack (persistent container/persistent store coordinator/managed object model/managed object context instantiated before you load the view controller? It appears not. Since you crash so early, I'm going out on a limb and guessing that you have a spelling error or name mismatch somewhere (a filename that doesn't match what's in your defining code). Or perhaps your MOM is not included as a resource in your bundle?


问:
Unwrap a div in react, something similar to jQuery unwrap method
I am using React JSX. I have a div with className="shadow" as shown below.

```<code><div className="main">
  <div className="shadow" style={{backgroundColor: "#FFFFFF"}}>
    <div id="wrapper">
      Hello
    </div>
  </div>
</div>
</code>```

Based on a certain condition being true or false, I want to remove the div with className="shadow", but want to keep every div including the div with id="wrapper" intact. Something like unwrap() method of jQuery.
Something to the effect of what is written below, but without so many lines of code.

```<code>  if ( currentPage==="login") {
   <div className="main">
     <div id="wrapper">
       Hello
     </div>
   </div>
}
else {
    <div className="main">
  <div className="shadow" style={{backgroundColor: "#FFFFFF"}}>
    <div id="wrapper">
      Hello
    </div>
  </div>
</div>
}
</code>```

I checked React.js: Wrapping one component into another and How to pass in a react component into another react component to transclude the first component's content?, but didn't get what I am looking for.

答:
This is a great use case for Higher Order Components!

```<code>const HOC = (currentPage, Shadow, Wrapper) => (
  () => <div className="main">
    {
      currentPage === 'login'
        ? <Shadow {...this.props} />
        : <Shadow {...this.props}><Wrapper {...this.props}>{this.props.children}</Wrapper></Shadow>
    }
  </div>
)
</code>```

Usage:

```<code>render () {
  const Shadow = props => <div className="shadow" style={{backgroundColor: '#FFFFFF'}}>{props.children}</div>
  const Wrapper = props => <div id="wrapper">Hello</div>

  const Example = HOC(
    currentPage,
    Shadow,
    Wrapper
  )

  return (
    <Example />
  )
}
</code>```

Update:

To render the children of <Wrapper />, use {this.props.children} and use the class syntax in HOC:

```<code>const HOC = (currentPage, Shadow, Wrapper) => (
  class extends Component {
    render () {
      return (
        <div className="main">
          {
            currentPage === 'login'
              ? <Shadow />
              : <Shadow><Wrapper>{this.props.children}</Wrapper></Shadow>
          }
        </div>
      )
    }
  }
)
</code>```

If you needed to capture props on <Shadow /> and <Wrapper />, then do something like the following.  Note: I don't think you can pass props into normal DOM elements like
 tags. But if they were other components with a Capital starting letter, then I believe passing props through with {...this.props} would work nicely.

```<code>const HOC = (currentPage, Shadow, Wrapper) => (
  class extends Component {
    render () {
      return (
        <div className="main">
          {
            currentPage === 'login'
              ? <Shadow {...this.props} />
              : <Shadow {...this.props}><Wrapper {...this.props}>{this.props.children}</Wrapper></Shadow>
          }
        </div>
      )
    }
  }
)
</code>```

Body:
I am using React JSX. I have a div with className="shadow" as shown below.

      Hello

Based on a certain condition being true or false, I want to remove the div with className="shadow", but want to keep every div including the div with id="wrapper" intact. Something like unwrap() method of jQuery.
Something to the effect of what is written below, but without so many lines of code.

  if ( currentPage==="login") {

       Hello

}
else {

      Hello

}

I checked React.js: Wrapping one component into another and How to pass in a react component into another react component to transclude the first component's content?, but didn't get what I am looking for.

Body:
This is a great use case for Higher Order Components!

const HOC = (currentPage, Shadow, Wrapper) => (
  () => <div className="main">
    {
      currentPage === 'login'
        ? <Shadow {...this.props} />
        : <Shadow {...this.props}><Wrapper {...this.props}>{this.props.children}</Wrapper></Shadow>
    }
  </div>
)

Usage:

render () {
  const Shadow = props => <div className="shadow" style={{backgroundColor: '#FFFFFF'}}>{props.children}</div>
  const Wrapper = props => <div id="wrapper">Hello</div>

  const Example = HOC(
    currentPage,
    Shadow,
    Wrapper
  )

  return (
    <Example />
  )
}

Update:

To render the children of <Wrapper />, use {this.props.children} and use the class syntax in HOC:

const HOC = (currentPage, Shadow, Wrapper) => (
  class extends Component {
    render () {
      return (
        <div className="main">
          {
            currentPage === 'login'
              ? <Shadow />
              : <Shadow><Wrapper>{this.props.children}</Wrapper></Shadow>
          }
        </div>
      )
    }
  }
)

If you needed to capture props on <Shadow /> and <Wrapper />, then do something like the following.  Note: I don't think you can pass props into normal DOM elements like <div> tags. But if they were other components with a Capital starting letter, then I believe passing props through with {...this.props} would work nicely.

const HOC = (currentPage, Shadow, Wrapper) => (
  class extends Component {
    render () {
      return (
        <div className="main">
          {
            currentPage === 'login'
              ? <Shadow {...this.props} />
              : <Shadow {...this.props}><Wrapper {...this.props}>{this.props.children}</Wrapper></Shadow>
          }
        </div>
      )
    }
  }
)


问:
Metric and Imperial internal representation
I want to use metric and Imperial distance units in an application. One way of doing this is tagging a number with the unit. I don't want to go this route.

I want to use one internal representation that can exactly hold imperial down to 1/64 of an inch and 0.2mm. I have come up with 8128 RSU (really small units) that is divisible by 64 and 254, which does what I want.

This is close to 2^13, and it has got me wondering if there is a more optimal way of doing this?

Any ideas?

答:
To avoid rounding errors and programming confusion, my advise will be to use internally one unit. So you can do the conversion on the outside:

gui

import/export

possibly database, but better leave that to the internal unit unless you are forced to work with that database.

In the past, several projects have failed because of unit confusion.


问:
how to get specific column's value after using filter
I have used TableRowsorter to filter some rows out from myJtable. Is there a way I can take all the values from a column and store it in arraylist after the filter from the Jtable.   </p>

答:
Conceptually, something like this...

```<code>// Apply filter...
int col = ...; // Column you're interested in
List values = new ArrayList(table.getRowCount());
for (int row = 0; row < table.getRowCount(); row++) {
    values.add(table.getValueAt(row, col));
}
</code>```

will work.

Because JTable is a representation of the filtered (and sorted) data, you can just walk through it to get the values it's presenting

Body:
Conceptually, something like this...

// Apply filter...
int col = ...; // Column you're interested in
List values = new ArrayList(table.getRowCount());
for (int row = 0; row < table.getRowCount(); row++) {
    values.add(table.getValueAt(row, col));
}

will work.

Because JTable is a representation of the filtered (and sorted) data, you can just walk through it to get the values it's presenting


问:
Need help using a while statement and getting the math right
I'm still very new to coding.  My teacher is very hard to understand so I need online help.  For this, I need to find the value in a savings account after months of compounding interest. I know that my math is wrong but I don't know how to fix this, and I've never written a while statement.  Please help me out.

From my prompt:

"Suppose you save $100 each month into the savings account and the
  annual interest rate is 5%.   So, the monthly interest rate is 0.05/12
  = 0.00417.   After the first month, the value in the account becomes 100* (1 + 0.00417) = $100.417    After the second month, the value in
  the account becomes (100 + 100.417) * (1 + 0.00417) = $201.252 After
  the third month, the value in the account becomes
         (100 + 201.252) * (1 + 0.00417) = $302.507 and so on."

```<code>double initialSavings;
System.out.print("How much money would you like to save each month? $");
initialSavings = userInput.nextDouble();

double annualInterest;
System.out.print("What is the annual interest rate for your savings account? (Example, 2.5) ");
annualInterest = userInput.nextDouble();

int months;
System.out.print("How many months would you like to keep saving? ");
months = userInput.nextInt();

double monthlyInterest;
monthlyInterest = annualInterest / 12;

int count = 1;

while (count <= months) {

count++;

double result;

result = initialSavings * count * (1 + monthlyInterest);

}

System.out.println("You will have $"+ result "after "+ months "months.");
}
}
</code>```

答:
result should be out of the loop and your result value should carry over into each calculation.  This is why the result variable is assigned to itself thus compounding your initial investment as well as the additional 100 invested each month.

```<code>var result = 0.0;
while (count <= months) {
    result = (result + savingsAmount) * (1 + monthlyInterest);
    count++;
}
</code>```

Body:
I'm still very new to coding.  My teacher is very hard to understand so I need online help.  For this, I need to find the value in a savings account after months of compounding interest. I know that my math is wrong but I don't know how to fix this, and I've never written a while statement.  Please help me out.

From my prompt:

"Suppose you save $100 each month into the savings account and the
  annual interest rate is 5%.   So, the monthly interest rate is 0.05/12
  = 0.00417.   After the first month, the value in the account becomes 100* (1 + 0.00417) = $100.417    After the second month, the value in
  the account becomes (100 + 100.417) * (1 + 0.00417) = $201.252 After
  the third month, the value in the account becomes
         (100 + 201.252) * (1 + 0.00417) = $302.507 and so on."

double initialSavings;
System.out.print("How much money would you like to save each month? $");
initialSavings = userInput.nextDouble();

double annualInterest;
System.out.print("What is the annual interest rate for your savings account? (Example, 2.5) ");
annualInterest = userInput.nextDouble();

int months;
System.out.print("How many months would you like to keep saving? ");
months = userInput.nextInt();

double monthlyInterest;
monthlyInterest = annualInterest / 12;

int count = 1;

while (count <= months) {

count++;

double result;

result = initialSavings * count * (1 + monthlyInterest);

}

System.out.println("You will have $"+ result "after "+ months "months.");
}
}

Body:
result should be out of the loop and your result value should carry over into each calculation.  This is why the result variable is assigned to itself thus compounding your initial investment as well as the additional 100 invested each month.

var result = 0.0;
while (count <= months) {
    result = (result + savingsAmount) * (1 + monthlyInterest);
    count++;
}


问:
Clojure.java.jdbc return type for datetime changes based on query structure
I have a Korma based software stack that constructs fairly complex queries against a MySQL database.  I noticed that when I am querying for datetime columns, the type that I get back from the Korma query changes depending on the syntax of the SQL query being generated.  I've traced this down to the level of clojure.java.jdbc/query.  If the form of the query is like this:

```<code>select modified from docs order by modified desc limit 10
</code>```

then I get back maps corresponding to each database row in which :modified is a java.sql.Timestamp.  However, sometimes our query generator generates more complex union queries, such that we need to apply an order by ... limit ... constraint to the final result of the union.  Korma does this by wrapping the query in parentheses.  Even with only a single subquery--i.e., a simple parenthesized select--so long as we add an "outer" order by ..., the type of :modified changes.

```<code>(select modified from docs order by modified desc limit 10) order by modified desc
</code>```

In this case, clojure.java.jdbc/query returns :modified values as strings.  Some of our higher level code isn't expecting this, and gets exceptions.

We're using a fork of Korma, which is using an old (0.3.7) version of clojure.java.jdbc.  I can't tell if the culprit is clojure.java.jdbc or java.jdbc or MySQL.  Anyone seen this and have ideas on how to fix it?

答:
Moving to the latest jdbc in a similar situation changed several other things for us and was a decidedly "non-trvial" task. I would suggest getting off of a korma fork soon and then debugging this.

For us the changes focused around what korma returned on update calls changed between the verions of the backing jdbc. It was well worth getting current even though it's a moderately painful process.

Getting current with jdbc will give you fresh new problems!
best of luck with this :-) These things tend to be fairly specific to the DB server you are using.

Other options for you is to have a policy of aways specifying an order-by parameter or building a library to coerce the strings into dates. Both of these have some long term technical dept problems.

Body:
I have a Korma based software stack that constructs fairly complex queries against a MySQL database.  I noticed that when I am querying for datetime columns, the type that I get back from the Korma query changes depending on the syntax of the SQL query being generated.  I've traced this down to the level of clojure.java.jdbc/query.  If the form of the query is like this:

select modified from docs order by modified desc limit 10

then I get back maps corresponding to each database row in which :modified is a java.sql.Timestamp.  However, sometimes our query generator generates more complex union queries, such that we need to apply an order by ... limit ... constraint to the final result of the union.  Korma does this by wrapping the query in parentheses.  Even with only a single subquery--i.e., a simple parenthesized select--so long as we add an "outer" order by ..., the type of :modified changes.

(select modified from docs order by modified desc limit 10) order by modified desc

In this case, clojure.java.jdbc/query returns :modified values as strings.  Some of our higher level code isn't expecting this, and gets exceptions.

We're using a fork of Korma, which is using an old (0.3.7) version of clojure.java.jdbc.  I can't tell if the culprit is clojure.java.jdbc or java.jdbc or MySQL.  Anyone seen this and have ideas on how to fix it?


问:
Android Media Player play/pause Button
In my project, I am playing music file in android media player by using the following code

```<code>MediaPlayer mPlayer = MediaPlayer.create(MyActivity.this, R.raw.myfile);
mPlayer.start();
</code>```

the above is coded in the onclick of the play button.
I want to pause the playback by clicking the same button again.ie) single button for play/pause.
How shall i do this.

答:
public class MainActivity extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
</code>```

//the song was previously saved in the raw folder. The name of the song is mylife (it's an mp3 file)
        final MediaPlayer mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.mylife);

```<code>    //      Play song
    Button playButton = (Button) findViewById(R.id.play);
    playButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            mMediaPlayer.start(); // no need to call prepare(); create() does that for you
        }
    });
    //      Pause song
    Button pauseButton = (Button) findViewById(R.id.pause);
    pauseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            mMediaPlayer.pause();
        }
    });

    //      Stop song - when you stop a song, you can't play it again. First you need to prepare it.

    Button stopButton = (Button) findViewById(R.id.stop);
    stopButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            mMediaPlayer.stop();
            mMediaPlayer.prepareAsync();
        }
    });

}
</code>```

}

Title: Android Media Player play/pause Button

Body:
In my project, I am playing music file in android media player by using the following code

MediaPlayer mPlayer = MediaPlayer.create(MyActivity.this, R.raw.myfile);
mPlayer.start();

the above is coded in the onclick of the play button.
I want to pause the playback by clicking the same button again.ie) single button for play/pause.
How shall i do this.

Body:
public class MainActivity extends AppCompatActivity {

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

//the song was previously saved in the raw folder. The name of the song is mylife (it's an mp3 file)
        final MediaPlayer mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.mylife);

    //      Play song
    Button playButton = (Button) findViewById(R.id.play);
    playButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            mMediaPlayer.start(); // no need to call prepare(); create() does that for you
        }
    });
    //      Pause song
    Button pauseButton = (Button) findViewById(R.id.pause);
    pauseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            mMediaPlayer.pause();
        }
    });

    //      Stop song - when you stop a song, you can't play it again. First you need to prepare it.

    Button stopButton = (Button) findViewById(R.id.stop);
    stopButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            mMediaPlayer.stop();
            mMediaPlayer.prepareAsync();
        }
    });

}

}


问:
nUnit Assert.Throws TestCase attribute
I have a test method like this: </p>

```<code>[TestCase(16486, "BobBank2.site16486.1", "16486.1")]
[TestCase(16441, "BobBank2.site16441.1", "16441.1")]
[TestCase(16443, "BobBank2.site16443.1", "16443.1")]
public async Task CheckUserAccountLinkStatusTest(int providerId, string username, string userKey)
</code>```

<p>I need to make sure that the first case (16486) throws an error, always. Is it possible to modify the TestCase attribute to do this? </p>

答:
While the @Connel.O'Donnell solution works, I'd suggest to:

Avoid conditional logic in unit tests.

By having if-statements in your unit tests, it's easier to have a bug.

It's more difficult to read and maintain the test with the logic branched.

Here is the Stack Overflow topic: Why should you avoid conditional logic in unit tests and how?

Separate tests that throws exception from those which doesn't throw one.

So, your new, separated test for asserting exception should more or less look like:

```<code>[TestCase(16486, "BobBank2.site16486.1", "16486.1")]
public async Task CheckUserAccountLinkStatusTest_ThrowsException(int providerId, string username, string userKey)
{
    // ...
    Assert.That(() => { /* ... */  }, Throws.Exception);
}
</code>```

Title: nUnit Assert.Throws TestCase attribute

Body:
I have a test method like this:

[TestCase(16486, "BobBank2.site16486.1", "16486.1")]
[TestCase(16441, "BobBank2.site16441.1", "16441.1")]
[TestCase(16443, "BobBank2.site16443.1", "16443.1")]
public async Task CheckUserAccountLinkStatusTest(int providerId, string username, string userKey)

I need to make sure that the first case (16486) throws an error, always. Is it possible to modify the TestCase attribute to do this?

Body:
While the @Connel.O'Donnell solution works, I'd suggest to:

Avoid conditional logic in unit tests.

By having if-statements in your unit tests, it's easier to have a bug.

It's more difficult to read and maintain the test with the logic branched.

Here is the Stack Overflow topic: Why should you avoid conditional logic in unit tests and how?

Separate tests that throws exception from those which doesn't throw one.

So, your new, separated test for asserting exception should more or less look like:

[TestCase(16486, "BobBank2.site16486.1", "16486.1")]
public async Task CheckUserAccountLinkStatusTest_ThrowsException(int providerId, string username, string userKey)
{
    // ...
    Assert.That(() => { /* ... */  }, Throws.Exception);
}