text:
Q: Query join with a single table SQL hi guys i have problem to product a query in SQL Server.
I have a table with this records
+-------+--------------+------+
|field 1|field 2       |field3|
+-------+--------------+------+
|B395   |B.U. 2013     |1002  |
+-------+--------------+------+
|B395   |LOCATION 2013 |      |
+-------+--------------+------+
|B395   |MATERIALI 2013|3304  |
+-------+--------------+------+
|B395   |REVENUES 2013 |2202  |
+-------+--------------+------+
|B396   |B.U. 2013     |1002  |
+-------+--------------+------+
|B396   |LOCATION 2013 |      |
+-------+--------------+------+
|B396   |MATERIALI 2013|3304  |
+-------+--------------+------+
|B396   |REVENUES 2013 |2202  |
+-------+--------------+------+

i would like a query that return like this
+------+--------------+-------------+-------------------+------------------+
|Field1|field2        |field3       |field4             |field5            |
+------+--------------+-------------+-------------------+------------------+
|B395  |B.U. 2013 1002|LOCATION 2013|MATERIALI 2013 3304|REVENUES 2013 2202|
+------+--------------+-------------+-------------------+------------------+
|B396  |B.U. 2013 1002|LOCATION 2013|MATERIALI 2013 3304|REVENUES 2013 2202|
+------+--------------+-------------+-------------------+------------------+

i could do it with left join??
thanks a lot

A: You've not made it particularly clear what you are trying to do however looking at your data I believe something like the following will work:
SELECT
    [field 1] = bu.[field 1]
    ,[field 2] = bu.[field 2] + ' ' + bu.[field 3]
    ,[field 3] = loc.[field 2]
    ,[field 4] = mat.[field 2] + ' ' + mat.[field 3]
    ,[field 5] = rev.[field 2] + ' ' + rev.[field 3]
FROM
    tableName bu
    LEFT JOIN tableName loc ON loc.[field 1] = bu.[field 1]
    LEFT JOIN tableName mat ON mat.[field 1] = bu.[field 1]
    LEFT JOIN tableName rev ON rev.[field 1] = bu.[field 1]
WHERE
    LEFT(bu.[field 1],4) = 'B.U.'
    AND LEFT(loc.[field 1],8) = 'LOCATION'
    AND LEFT(loc.[field 1],9) = 'MATERIALI'
    AND LEFT(loc.[field 1],8) = 'REVENUES'

I am assuming that the fields in the resulting table are composites of Field 2 and Field 3, changing the LEFT JOIN's to be INNER JOIN's would mean that all columns are required. The above also requires the B.U. entry to be there before populating, but again you could change the joining where necessary.

A: I try to use your query with my database field name but the result is 0 record,but without the
where conditions i have this result:

B395  B.U. 2013 1002  B.U. 2013 1002  B.U. 2013 1002
B395  B.U. 2013 1002  B.U. 2013 1002  B.U. 2013 1002
B395  B.U. 2013 1002  B.U. 2013 1002  B.U. 2013 1002
B395  B.U. 2013 1002  B.U. 2013 1002  B.U. 2013 1002
B395  B.U. 2013 1002  B.U. 2013 1002  LOCATION 2013
B395  B.U. 2013 1002  B.U. 2013 1002  LOCATION 2013
B395  B.U. 2013 1002  B.U. 2013 1002  LOCATION 2013
B395  B.U. 2013 1002  B.U. 2013 1002  LOCATION 2013
B395  B.U. 2013 1002  B.U. 2013 1002  MATERIALI 2013 3304
B395  B.U. 2013 1002  B.U. 2013 1002  MATERIALI 2013 3304
B395  B.U. 2013 1002  B.U. 2013 1002  MATERIALI 2013 3304
B395  B.U. 2013 1002  B.U. 2013 1002  MATERIALI 2013 3304
B395  B.U. 2013 1002  B.U. 2013 1002  REVENUES 2013 2202
B395  B.U. 2013 1002  B.U. 2013 1002  REVENUES 2013 2202
B395  B.U. 2013 1002  B.U. 2013 1002  REVENUES 2013 2202
B395  B.U. 2013 1002  B.U. 2013 1002  REVENUES 2013 2202
B395  B.U. 2013 1002  LOCATION 2013   B.U. 2013 1002
B395  B.U. 2013 1002  LOCATION 2013   B.U. 2013 1002
B395  B.U. 2013 1002  LOCATION 2013   B.U. 2013 1002
B395  B.U. 2013 1002  LOCATION 2013   B.U. 2013 1002
B395  B.U. 2013 1002  LOCATION 2013   LOCATION 2013
B395  B.U. 2013 1002  LOCATION 2013   LOCATION 2013
B395  B.U. 2013 1002  LOCATION 2013   LOCATION 2013
B395  B.U. 2013 1002  LOCATION 2013   LOCATION 2013
B395  B.U. 2013 1002  LOCATION 2013   MATERIALI 2013 3304
B395  B.U. 2013 1002  LOCATION 2013   MATERIALI 2013 3304
B395  B.U. 2013 1002  LOCATION 2013   MATERIALI 2013 3304
B395  B.U. 2013 1002  LOCATION 2013   MATERIALI 2013 3304
B395  B.U. 2013 1002  LOCATION 2013   REVENUES 2013 2202
B395  B.U. 2013 1002  LOCATION 2013   REVENUES 2013 2202
B395  B.U. 2013 1002  LOCATION 2013   REVENUES 2013 2202
B395  B.U. 2013 1002  LOCATION 2013   REVENUES 2013 2202
B395  B.U. 2013 1002  MATERIALI 2013 3304 B.U. 2013 1002
B395  B.U. 2013 1002  MATERIALI 2013 3304 B.U. 2013 1002
B395  B.U. 2013 1002  MATERIALI 2013 3304 B.U. 2013 1002
B395  B.U. 2013 1002  MATERIALI 2013 3304 B.U. 2013 1002
B395  B.U. 2013 1002  MATERIALI 2013 3304 LOCATION 2013
B395  B.U. 2013 1002  MATERIALI 2013 3304 LOCATION 2013
B395  B.U. 2013 1002  MATERIALI 2013 3304 LOCATION 2013
B395  B.U. 2013 1002  MATERIALI 2013 3304 LOCATION 2013
B395  B.U. 2013 1002  MATERIALI 2013 3304 MATERIALI 2013 3304
B395  B.U. 2013 1002  MATERIALI 2013 3304 MATERIALI 2013 3304
B395  B.U. 2013 1002  MATERIALI 2013 3304 MATERIALI 2013 3304
B395  B.U. 2013 1002  MATERIALI 2013 3304 MATERIALI 2013 3304
B395  B.U. 2013 1002  MATERIALI 2013 3304 REVENUES 2013 2202
B395  B.U. 2013 1002  MATERIALI 2013 3304 REVENUES 2013 2202
B395  B.U. 2013 1002  MATERIALI 2013 3304 REVENUES 2013 2202
B395  B.U. 2013 1002  MATERIALI 2013 3304 REVENUES 2013 2202
B395  B.U. 2013 1002  REVENUES 2013 2202  B.U. 2013 1002
B395  B.U. 2013 1002  REVENUES 2013 2202  B.U. 2013 1002
B395  B.U. 2013 1002  REVENUES 2013 2202  B.U. 2013 1002
B395  B.U. 2013 1002  REVENUES 2013 2202  B.U. 2013 1002
B395  B.U. 2013 1002  REVENUES 2013 2202  LOCATION 2013
B395  B.U. 2013 1002  REVENUES 2013 2202  LOCATION 2013
B395  B.U. 2013 1002  REVENUES 2013 2202  LOCATION 2013
B395  B.U. 2013 1002  REVENUES 2013 2202  LOCATION 2013
B395  B.U. 2013 1002  REVENUES 2013 2202  MATERIALI 2013 3304
B395  B.U. 2013 1002  REVENUES 2013 2202  MATERIALI 2013 3304
B395  B.U. 2013 1002  REVENUES 2013 2202  MATERIALI 2013 3304
B395  B.U. 2013 1002  REVENUES 2013 2202  MATERIALI 2013 3304
B395  B.U. 2013 1002  REVENUES 2013 2202  REVENUES 2013 2202
B395  B.U. 2013 1002  REVENUES 2013 2202  REVENUES 2013 2202
B395  B.U. 2013 1002  REVENUES 2013 2202  REVENUES 2013 2202
B395  B.U. 2013 1002  REVENUES 2013 2202  REVENUES 2013 2202
B395  LOCATION 2013   B.U. 2013 1002  B.U. 2013 1002
B395  LOCATION 2013   B.U. 2013 1002  B.U. 2013 1002
B395  LOCATION 2013   B.U. 2013 1002  B.U. 2013 1002
B395  LOCATION 2013   B.U. 2013 1002  B.U. 2013 1002
B395  LOCATION 2013   B.U. 2013 1002  LOCATION 2013
B395  LOCATION 2013   B.U. 2013 1002  LOCATION 2013
B395  LOCATION 2013   B.U. 2013 1002  LOCATION 2013
B395  LOCATION 2013   B.U. 2013 1002  LOCATION 2013
B395  LOCATION 2013   B.U. 2013 1002  MATERIALI 2013 3304
B395  LOCATION 2013   B.U. 2013 1002  MATERIALI 2013 3304
B395  LOCATION 2013   B.U. 2013 1002  MATERIALI 2013 3304
B395  LOCATION 2013   B.U. 2013 1002  MATERIALI 2013 3304
B395  LOCATION 2013   B.U. 2013 1002  REVENUES 2013 2202
B395  LOCATION 2013   B.U. 2013 1002  REVENUES 2013 2202
B395  LOCATION 2013   B.U. 2013 1002  REVENUES 2013 2202
B395  LOCATION 2013   B.U. 2013 1002  REVENUES 2013 2202
B395  LOCATION 2013   LOCATION 2013   B.U. 2013 1002
B395  LOCATION 2013   LOCATION 2013   B.U. 2013 1002
B395  LOCATION 2013   LOCATION 2013   B.U. 2013 1002
B395  LOCATION 2013   LOCATION 2013   B.U. 2013 1002
B395  LOCATION 2013   LOCATION 2013   LOCATION 2013
B395  LOCATION 2013   LOCATION 2013   LOCATION 2013
B395  LOCATION 2013   LOCATION 2013   LOCATION 2013
B395  LOCATION 2013   LOCATION 2013   LOCATION 2013
B395  LOCATION 2013   LOCATION 2013   MATERIALI 2013 3304
B395  LOCATION 2013   LOCATION 2013   MATERIALI 2013 3304
B395  LOCATION 2013   LOCATION 2013   MATERIALI 2013 3304
B395  LOCATION 2013   LOCATION 2013   MATERIALI 2013 3304
B395  LOCATION 2013   LOCATION 2013   REVENUES 2013 2202
B395  LOCATION 2013   LOCATION 2013   REVENUES 2013 2202
B395  LOCATION 2013   LOCATION 2013   REVENUES 2013 2202
B395  LOCATION 2013   LOCATION 2013   REVENUES 2013 2202
B395  LOCATION 2013   MATERIALI 2013 3304 B.U. 2013 1002
B395  LOCATION 2013   MATERIALI 2013 3304 B.U. 2013 1002
B395  LOCATION 2013   MATERIALI 2013 3304 B.U. 2013 1002
B395  LOCATION 2013   MATERIALI 2013 3304 B.U. 2013 1002
B395  LOCATION 2013   MATERIALI 2013 3304 LOCATION 2013
B395  LOCATION 2013   MATERIALI 2013 3304 LOCATION 2013
B395  LOCATION 2013   MATERIALI 2013 3304 LOCATION 2013
B395  LOCATION 2013   MATERIALI 2013 3304 LOCATION 2013
B395  LOCATION 2013   MATERIALI 2013 3304 MATERIALI 2013 3304
B395  LOCATION 2013   MATERIALI 2013 3304 MATERIALI 2013 3304
B395  LOCATION 2013   MATERIALI 2013 3304 MATERIALI 2013 3304
B395  LOCATION 2013   MATERIALI 2013 3304 MATERIALI 2013 3304
B395  LOCATION 2013   MATERIALI 2013 3304 REVENUES 2013 2202
B395  LOCATION 2013   MATERIALI 2013 3304 REVENUES 2013 2202
B395  LOCATION 2013   MATERIALI 2013 3304 REVENUES 2013 2202
B395  LOCATION 2013   MATERIALI 2013 3304 REVENUES 2013 2202
B395  LOCATION 2013   REVENUES 2013 2202  B.U. 2013 1002
B395  LOCATION 2013   REVENUES 2013 2202  B.U. 2013 1002
B395  LOCATION 2013   REVENUES 2013 2202  B.U. 2013 1002
B395  LOCATION 2013   REVENUES 2013 2202  B.U. 2013 1002
B395  LOCATION 2013   REVENUES 2013 2202  LOCATION 2013
B395  LOCATION 2013   REVENUES 2013 2202  LOCATION 2013
B395  LOCATION 2013   REVENUES 2013 2202  LOCATION 2013
B395  LOCATION 2013   REVENUES 2013 2202  LOCATION 2013
B395  LOCATION 2013   REVENUES 2013 2202  MATERIALI 2013 3304
B395  LOCATION 2013   REVENUES 2013 2202  MATERIALI 2013 3304
B395  LOCATION 2013   REVENUES 2013 2202  MATERIALI 2013 3304
B395  LOCATION 2013   REVENUES 2013 2202  MATERIALI 2013 3304
B395  LOCATION 2013   REVENUES 2013 2202  REVENUES 2013 2202
B395  LOCATION 2013   REVENUES 2013 2202  REVENUES 2013 2202
B395  LOCATION 2013   REVENUES 2013 2202  REVENUES 2013 2202
B395  LOCATION 2013   REVENUES 2013 2202  REVENUES 2013 2202
B395  MATERIALI 2013 3304 B.U. 2013 1002  B.U. 2013 1002
B395  MATERIALI 2013 3304 B.U. 2013 1002  B.U. 2013 1002
B395  MATERIALI 2013 3304 B.U. 2013 1002  B.U. 2013 1002
B395  MATERIALI 2013 3304 B.U. 2013 1002  B.U. 2013 1002
B395  MATERIALI 2013 3304 B.U. 2013 1002  LOCATION 2013
B395  MATERIALI 2013 3304 B.U. 2013 1002  LOCATION 2013
B395  MATERIALI 2013 3304 B.U. 2013 1002  LOCATION 2013
B395  MATERIALI 2013 3304 B.U. 2013 1002  LOCATION 2013
B395  MATERIALI 2013 3304 B.U. 2013 1002  MATERIALI 2013 3304
B395  MATERIALI 2013 3304 B.U. 2013 1002  MATERIALI 2013 3304
B395  MATERIALI 2013 3304 B.U. 2013 1002  MATERIALI 2013 3304
B395  MATERIALI 2013 3304 B.U. 2013 1002  MATERIALI 2013 3304
B395  MATERIALI 2013 3304 B.U. 2013 1002  REVENUES 2013 2202
B395  MATERIALI 2013 3304 B.U. 2013 1002  REVENUES 2013 2202
B395  MATERIALI 2013 3304 B.U. 2013 1002  REVENUES 2013 2202
B395  MATERIALI 2013 3304 B.U. 2013 1002  REVENUES 2013 2202
B395  MATERIALI 2013 3304 LOCATION 2013   B.U. 2013 1002
B395  MATERIALI 2013 3304 LOCATION 2013   B.U. 2013 1002
B395  MATERIALI 2013 3304 LOCATION 2013   B.U. 2013 1002
B395  MATERIALI 2013 3304 LOCATION 2013   B.U. 2013 1002
B395  MATERIALI 2013 3304 LOCATION 2013   LOCATION 2013
B395  MATERIALI 2013 3304 LOCATION 2013   LOCATION 2013
B395  MATERIALI 2013 3304 LOCATION 2013   LOCATION 2013
B395  MATERIALI 2013 3304 LOCATION 2013   LOCATION 2013
B395  MATERIALI 2013 3304 LOCATION 2013   MATERIALI 2013 3304
B395  MATERIALI 2013 3304 LOCATION 2013   MATERIALI 2013 3304
B395  MATERIALI 2013 3304 LOCATION 2013   MATERIALI 2013 3304
B395  MATERIALI 2013 3304 LOCATION 2013   MATERIALI 2013 3304
B395  MATERIALI 2013 3304 LOCATION 2013   REVENUES 2013 2202
B395  MATERIALI 2013 3304 LOCATION 2013   REVENUES 2013 2202
B395  MATERIALI 2013 3304 LOCATION 2013   REVENUES 2013 2202
B395  MATERIALI 2013 3304 LOCATION 2013   REVENUES 2013 2202
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 B.U. 2013 1002
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 B.U. 2013 1002
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 B.U. 2013 1002
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 B.U. 2013 1002
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 LOCATION 2013
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 LOCATION 2013
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 LOCATION 2013
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 LOCATION 2013
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 MATERIALI 2013 3304
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 MATERIALI 2013 3304
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 MATERIALI 2013 3304
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 MATERIALI 2013 3304
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 REVENUES 2013 2202
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 REVENUES 2013 2202
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 REVENUES 2013 2202
B395  MATERIALI 2013 3304 MATERIALI 2013 3304 REVENUES 2013 2202
B395  MATERIALI 2013 3304 REVENUES 2013 2202  B.U. 2013 1002
B395  MATERIALI 2013 3304 REVENUES 2013 2202  B.U. 2013 1002
B395  MATERIALI 2013 3304 REVENUES 2013 2202  B.U. 2013 1002
B395  MATERIALI 2013 3304 REVENUES 2013 2202  B.U. 2013 1002
B395  MATERIALI 2013 3304 REVENUES 2013 2202  LOCATION 2013
B395  MATERIALI 2013 3304 REVENUES 2013 2202  LOCATION 2013
B395  MATERIALI 2013 3304 REVENUES 2013 2202  LOCATION 2013
B395  MATERIALI 2013 3304 REVENUES 2013 2202  LOCATION 2013
B395  MATERIALI 2013 3304 REVENUES 2013 2202  MATERIALI 2013 3304
B395  MATERIALI 2013 3304 REVENUES 2013 2202  MATERIALI 2013 3304
B395  MATERIALI 2013 3304 REVENUES 2013 2202  MATERIALI 2013 3304
B395  MATERIALI 2013 3304 REVENUES 2013 2202  MATERIALI 2013 3304
B395  MATERIALI 2013 3304 REVENUES 2013 2202  REVENUES 2013 2202
B395  MATERIALI 2013 3304 REVENUES 2013 2202  REVENUES 2013 2202
B395  MATERIALI 2013 3304 REVENUES 2013 2202  REVENUES 2013 2202
B395  MATERIALI 2013 3304 REVENUES 2013 2202  REVENUES 2013 2202
B395  REVENUES 2013 2202  B.U. 2013 1002  B.U. 2013 1002
B395  REVENUES 2013 2202  B.U. 2013 1002  B.U. 2013 1002
B395  REVENUES 2013 2202  B.U. 2013 1002  B.U. 2013 1002
B395  REVENUES 2013 2202  B.U. 2013 1002  B.U. 2013 1002
B395  REVENUES 2013 2202  B.U. 2013 1002  LOCATION 2013
B395  REVENUES 2013 2202  B.U. 2013 1002  LOCATION 2013
B395  REVENUES 2013 2202  B.U. 2013 1002  LOCATION 2013
B395  REVENUES 2013 2202  B.U. 2013 1002  LOCATION 2013
B395  REVENUES 2013 2202  B.U. 2013 1002  MATERIALI 2013 3304
B395  REVENUES 2013 2202  B.U. 2013 1002  MATERIALI 2013 3304
B395  REVENUES 2013 2202  B.U. 2013 1002  MATERIALI 2013 3304
B395  REVENUES 2013 2202  B.U. 2013 1002  MATERIALI 2013 3304
B395  REVENUES 2013 2202  B.U. 2013 1002  REVENUES 2013 2202
B395  REVENUES 2013 2202  B.U. 2013 1002  REVENUES 2013 2202
B395  REVENUES 2013 2202  B.U. 2013 1002  REVENUES 2013 2202
B395  REVENUES 2013 2202  B.U. 2013 1002  REVENUES 2013 2202
B395  REVENUES 2013 2202  LOCATION 2013   B.U. 2013 1002
B395  REVENUES 2013 2202  LOCATION 2013   B.U. 2013 1002
B395  REVENUES 2013 2202  LOCATION 2013   B.U. 2013 1002
B395  REVENUES 2013 2202  LOCATION 2013   B.U. 2013 1002
B395  REVENUES 2013 2202  LOCATION 2013   LOCATION 2013
B395  REVENUES 2013 2202  LOCATION 2013   LOCATION 2013
B395  REVENUES 2013 2202  LOCATION 2013   LOCATION 2013
B395  REVENUES 2013 2202  LOCATION 2013   LOCATION 2013
B395  REVENUES 2013 2202  LOCATION 2013   MATERIALI 2013 3304
B395  REVENUES 2013 2202  LOCATION 2013   MATERIALI 2013 3304
B395  REVENUES 2013 2202  LOCATION 2013   MATERIALI 2013 3304
B395  REVENUES 2013 2202  LOCATION 2013   MATERIALI 2013 3304
B395  REVENUES 2013 2202  LOCATION 2013   REVENUES 2013 2202
B395  REVENUES 2013 2202  LOCATION 2013   REVENUES 2013 2202
B395  REVENUES 2013 2202  LOCATION 2013   REVENUES 2013 2202
B395  REVENUES 2013 2202  LOCATION 2013   REVENUES 2013 2202
B395  REVENUES 2013 2202  MATERIALI 2013 3304 B.U. 2013 1002
B395  REVENUES 2013 2202  MATERIALI 2013 3304 B.U. 2013 1002
B395  REVENUES 2013 2202  MATERIALI 2013 3304 B.U. 2013 1002
B395  REVENUES 2013 2202  MATERIALI 2013 3304 B.U. 2013 1002
B395  REVENUES 2013 2202  MATERIALI 2013 3304 LOCATION 2013
B395  REVENUES 2013 2202  MATERIALI 2013 3304 LOCATION 2013
B395  REVENUES 2013 2202  MATERIALI 2013 3304 LOCATION 2013
B395  REVENUES 2013 2202  MATERIALI 2013 3304 LOCATION 2013
B395  REVENUES 2013 2202  MATERIALI 2013 3304 MATERIALI 2013 3304
B395  REVENUES 2013 2202  MATERIALI 2013 3304 MATERIALI 2013 3304
B395  REVENUES 2013 2202  MATERIALI 2013 3304 MATERIALI 2013 3304
B395  REVENUES 2013 2202  MATERIALI 2013 3304 MATERIALI 2013 3304
B395  REVENUES 2013 2202  MATERIALI 2013 3304 REVENUES 2013 2202
B395  REVENUES 2013 2202  MATERIALI 2013 3304 REVENUES 2013 2202
B395  REVENUES 2013 2202  MATERIALI 2013 3304 REVENUES 2013 2202
B395  REVENUES 2013 2202  MATERIALI 2013 3304 REVENUES 2013 2202
B395  REVENUES 2013 2202  REVENUES 2013 2202  B.U. 2013 1002
B395  REVENUES 2013 2202  REVENUES 2013 2202  B.U. 2013 1002
B395  REVENUES 2013 2202  REVENUES 2013 2202  B.U. 2013 1002
B395  REVENUES 2013 2202  REVENUES 2013 2202  B.U. 2013 1002
B395  REVENUES 2013 2202  REVENUES 2013 2202  LOCATION 2013
B395  REVENUES 2013 2202  REVENUES 2013 2202  LOCATION 2013
B395  REVENUES 2013 2202  REVENUES 2013 2202  LOCATION 2013
B395  REVENUES 2013 2202  REVENUES 2013 2202  LOCATION 2013
B395  REVENUES 2013 2202  REVENUES 2013 2202  MATERIALI 2013 3304
B395  REVENUES 2013 2202  REVENUES 2013 2202  MATERIALI 2013 3304
B395  REVENUES 2013 2202  REVENUES 2013 2202  MATERIALI 2013 3304
B395  REVENUES 2013 2202  REVENUES 2013 2202  MATERIALI 2013 3304
B395  REVENUES 2013 2202  REVENUES 2013 2202  REVENUES 2013 2202
B395  REVENUES 2013 2202  REVENUES 2013 2202  REVENUES 2013 2202
B395  REVENUES 2013 2202  REVENUES 2013 2202  REVENUES 2013 2202
B395  REVENUES 2013 2202  REVENUES 2013 2202  REVENUES 2013 2202

query
SELECT
[field 1] = bu.[No_]
    ,[field 2] = bu.[Dimension Code] + ' ' + bu.[Dimension Value Code]
    ,[field 4] = mat.[Dimension Code] + ' ' + mat.[Dimension Value Code]
    ,[field 5] = rev.[Dimension Code] + ' ' + rev.[Dimension Value Code]
FROM
    dbo.[Zoom InProgress$Default Dimension] bu
    LEFT JOIN dbo.[Zoom InProgress$Default Dimension] loc ON loc.[No_] = bu.[No_]
    LEFT JOIN dbo.[Zoom InProgress$Default Dimension] mat ON mat.[No_] = bu.[No_]
    LEFT JOIN dbo.[Zoom InProgress$Default Dimension] rev ON rev.[No_] = bu.[No_

]


text:
Q: Page of connection in PHP/Mysql I just finished coding my login page, and I have these problems showing up, do you have any idea?

[Tue Mar  9 22:55:11 2021] PHP Notice:  Undefined variable: rounds in /home/swan/Epitech/Tweet_academie/html/connexion.php on line 28
[Tue Mar  9 22:55:11 2021] PHP Notice:  Undefined variable: sfopdgijtsposrigjsotij in /home/swan/Epitech/Tweet_academie/html/connexion.php on line 28

[Tue Mar  9 22:55:11 2021] PHP Warning:  PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '='swan.marin@gmail.com' AND password='$65I6KH/.1F1w'' at line 1 in /home/swan/Epitech/Tweet_academie/db/connexiondb.php on line 37
[Tue Mar  9 22:55:11 2021] PHP Notice:  Trying to access array offset on value of type bool in /home/swan/Epitech/Tweet_academie/html/connexion.php on line 32

<html>

<?php
session_start();
include('../db/connexiondb.php'); // Fichier PHP contenant la connexion à votre BDD

// S'il y a une session alors on ne retourne plus sur cette page
if (isset($_SESSION['id']))
{
header('Location: index.php');
    exit;
}

// Si la variable "$_Post" contient des informations alors on les traitres
if(!empty($_POST))
{
extract($_POST);
$valid = true;

    if (isset($_POST['connexion']))
    {
        $email = htmlentities(strtolower(trim($email)));
        $mdp = trim($mdp);

        // On fait une requête pour savoir si le couple mail / mot de passe existe bien
        $req = $DB->query("SELECT * FROM users WHERE email=? AND password=?",
        array($email, crypt($mdp, "$6$rounds=5000$sfopdgijtsposrigjsotij$")));
        $req = $req->fetch();

        // Si on a pas de résultat alors c'est qu'il n'y a pas d'utilisateur correspondant au couple mail / mot de passe
        if ($req['id'] == "")
        {
            $valid = false;
            $er_email = "Le mail ou le mot de passe est incorrecte";
        }

        // S'il y a un résultat alors on va charger la SESSION de l'utilisateur en utilisateur les variables $_SESSION

        if ($valid)
        {
            $_SESSION['id'] = $req['id'];
            $_SESSION['name'] = $req['name'];
            $_SESSION['email'] = $req['email'];

            header('Location:  index.php');
            exit;
        }
    }
}
?>

A: Line 28, check if you're receiving any value.
print_r($req);

it's probably an error in the sql command.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How would I create a handle manager in Rust? pub struct Storage<T>{
    vec: Vec<T>
}
impl<T: Clone> Storage<T>{
    pub fn new() -> Storage<T>{
        Storage{vec: Vec::new()}
    }
    pub fn get<'r>(&'r self, h: &Handle<T>)-> &'r T{
        let index = h.id;
        &self.vec[index]
    }
    pub fn set(&mut self, h: &Handle<T>, t: T){
        let index = h.id;
        self.vec[index] = t;
    }
    pub fn create(&mut self, t: T) -> Handle<T>{
        self.vec.push(t);
        Handle{id: self.vec.len()-1}
    }
}
struct Handle<T>{
    id: uint
}

I am currently trying to create a handle system in Rust and I have some problems. The code above is a simple example of what I want to achieve.
The code works but has one weakness.
let mut s1 = Storage<uint>::new();
let mut s2 = Storage<uint>::new();
let handle1 = s1.create(5);
s1.get(handle1); // works
s2.get(handle1); // unsafe

I would like to associate a handle with a specific storage like this
//Pseudo code
struct Handle<T>{
    id: uint,
    storage: &Storage<T>
}
impl<T> Handle<T>{
   pub fn get(&self) -> &T;
}

The problem is that Rust doesn't allow this. If I would do that and create a handle with the reference of a Storage I wouldn't be allowed to mutate the Storage anymore.
I could implement something similar with a channel but then I would have to clone T every time.
How would I express this in Rust?

A: The simplest way to model this is to use a phantom type parameter on Storage which acts as a unique ID, like so:
use std::kinds::marker;

pub struct Storage<Id, T> {
    marker: marker::InvariantType<Id>,
    vec: Vec<T>
}

impl<Id, T> Storage<Id, T> {
    pub fn new() -> Storage<Id, T>{
        Storage {
            marker: marker::InvariantType,
            vec: Vec::new()
        }
    }

    pub fn get<'r>(&'r self, h: &Handle<Id, T>) -> &'r T {
        let index = h.id;
        &self.vec[index]
    }

    pub fn set(&mut self, h: &Handle<Id, T>, t: T) {
        let index = h.id;
        self.vec[index] = t;
    }

    pub fn create(&mut self, t: T) -> Handle<Id, T> {
        self.vec.push(t);
        Handle {
            marker: marker::InvariantLifetime,
            id: self.vec.len() - 1
        }
    }
}

pub struct Handle<Id, T> {
    id: uint,
    marker: marker::InvariantType<Id>
}

fn main() {
    struct A; struct B;
    let mut s1 = Storage::<A, uint>::new();
    let s2 = Storage::<B, uint>::new();

    let handle1 = s1.create(5);
    s1.get(&handle1);

    s2.get(&handle1); // won't compile, since A != B
}

This solves your problem in the simplest case, but has some downsides. Mainly, it depends on the use to define and use all of these different phantom types and to prove that they are unique. It doesn't prevent bad behavior on the user's part where they can use the same phantom type for multiple Storage instances. In today's Rust, however, this is the best we can do.
An alternative solution that doesn't work today for reasons I'll get in to later, but might work later, uses lifetimes as anonymous id types. This code uses the InvariantLifetime marker, which removes all sub typing relationships with other lifetimes for the lifetime it uses.
Here is the same system, rewritten to use InvariantLifetime instead of InvariantType:
use std::kinds::marker;

pub struct Storage<'id, T> {
    marker: marker::InvariantLifetime<'id>,
    vec: Vec<T>
}

impl<'id, T> Storage<'id, T> {
    pub fn new() -> Storage<'id, T>{
        Storage {
            marker: marker::InvariantLifetime,
            vec: Vec::new()
        }
    }

    pub fn get<'r>(&'r self, h: &Handle<'id, T>) -> &'r T {
        let index = h.id;
        &self.vec[index]
    }

    pub fn set(&mut self, h: &Handle<'id, T>, t: T) {
        let index = h.id;
        self.vec[index] = t;
    }

    pub fn create(&mut self, t: T) -> Handle<'id, T> {
        self.vec.push(t);
        Handle {
            marker: marker::InvariantLifetime,
            id: self.vec.len() - 1
        }
    }
}

pub struct Handle<'id, T> {
    id: uint,
    marker: marker::InvariantLifetime<'id>
}

fn main() {
    let mut s1 = Storage::<uint>::new();
    let s2 = Storage::<uint>::new();

    let handle1 = s1.create(5);
    s1.get(&handle1);

    // In theory this won't compile, since the lifetime of s2
    // is *slightly* shorter than the lifetime of s1.
    //
    // However, this is not how the compiler works, and as of today
    // s2 gets the same lifetime as s1 (since they can be borrowed for the same period)
    // and this (unfortunately) compiles without error.
    s2.get(&handle1);
}

In a hypothetical future, the assignment of lifetimes may change and we may grow a better mechanism for this sort of tagging. However, for now, the best way to accomplish this is with phantom types.


text:
Q: Selecting message language in gcc and g++ I use gcc/g++ on Linux and since my install is in Spanish (my native language), gcc prints warnings and errors in Spanish. I would rather read them in English for two reasons:

*

*English messages are far easier to google.

*Spanish translations are more or less horrible.

Any help?

A: To change the gcc translations to English, to must set the environment variable LANG to English:
$ export LANG=en
add it to your .profile file and it will always be in English

A: The end of the GCC manpage contains an overview of its locale environment variables:

*

*LANG

*LC_CTYPE

*LC_MESSAGES

*LC_ALL

  These environment variables control the way that GCC uses localization information that allow GCC to work with different national conventions.  GCC inspects the locale categories LC_CTYPE and LC_MESSAGES if it has been configured to do so. These locale categories can be set to any value supported by your installation.  A typical value is en_GB.UTF-8 for English in the United Kingdom encoded in UTF-8.
The LC_CTYPE environment variable specifies character classification.  GCC uses it to determine the character boundaries in a string; this is needed for some multibyte encodings that contain quote and escape characters that would otherwise be interpreted as a string end or escape.
The LC_MESSAGES environment variable specifies the language to use in diagnostic messages.
If the LC_ALL environment variable is set, it overrides the value of LC_CTYPE and LC_MESSAGES; otherwise, LC_CTYPE and LC_MESSAGES default to the value of the LANG environment variable.  If none of these variables are set, GCC defaults to traditional C English behavior.

I do this:
LC_MESSAGES=C gcc-command-here

A: Try to change the LANG environment variable: http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Environment-Variables.html#Environment-Variables.


text:
Q: Сохранение фокуса выделенного элемента ListView Есть следующий код. В listview добавляются процессы. Данный метод вызывается каждые 3 секунды с помощью таймера. Как сделать так, чтобы после обновления фокус оставался на выделенном элементе, если он ещё есть и положение скролла сохранялось?
 private void UpdateProcessList()
        {
            listView1.Items.Clear();
            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
            {
                try
                {
                    int index = listView1.Items.Add(p.ProcessName).Index;
                    listView1.Items[index].SubItems.Add(p.Id.ToString());
                    listView1.Items[index].SubItems.Add(p.StartTime.ToShortTimeString());
                    long temp = p.WorkingSet64 / 1024;
                    listView1.Items[index].SubItems.Add(temp.ToString()+" КБ");
                }
                catch { }
            }
        }

A: Сразу же находится это:
private void FocusAndSelectItem(int itemIndex)
{
    Dispatcher.BeginInvoke(
        new FocusAndSelectItemDelegate(TryFocusAndSelectItem),
        DispatcherPriority.ApplicationIdle,
        itemIndex);
}

// Убеждаемся, что айтем находится в видимой области, выделяем его и устанавливаем фокус.
private void TryFocusAndSelectItem(int itemIndex)
{
    ListViewItem lvi = myListView.Items.GetItemAt(itemIndex) as ListViewItem;
    if (lvi != null)
    {
        myListView.ScrollIntoView(lvi);
        lvi.IsSelected = true;
        Keyboard.Focus(lvi);
    }
}

private delegate void FocusAndSelectItemDelegate(int itemIndex);

A: В общем-то основная проблема в данном случае в методе  Clear(), который и сбрасывает этот самый фокус, так как элемент-то удаляется. Я бы лучше посоветовал не перезаполнять весь список, а обновлять его, т.е. после выполнения GetProcesses() проходить по списку и смотреть, а что осталось, а что удалилось. Если же на удалённом элементе стоит фокус, то тут уже логика другая, либо, мол, извиняй, пользователь, нет такого процесса, выбирай другой, либо перемещать курсор на следующий/предыдущий пункт.


text:
Q: How to set an image vertical align but align left horizontally? I need to set a welcome section like the following:

I have set an absolute position just for the image, but I cannot make the image keeps horizontally align with the other column. Any ideas?
My code:
.img-welcome{
    position: absolute;
    top:10%;
    right: 0;
    bottom: 0;
    margin: auto;
    align-items: center;
    display: flex;
    height: max-content;
}

.container-relative{
    position: relative;
    height: 100%;
    padding-bottom: 50px;

}

Combine all your credit cards in one place

We alow you to connect diferent bank cards, in one system, in which you will have the opportunity to manage to financial data and track the statistics of your costs.

                Get Started

A: You can use flexbox to easily achieve this.
You just need a container and the two sides:

body {
  background-image: linear-gradient(to right, #00b795 , #0092a2);
  height: 100vh;
  margin: 0;
  padding: 0;
}

.container {
  height: 100%;
  display: flex;
  align-items: center;
}

.container > div {
  flex: 50%;
}

.left {
  padding: 20px;
  font-family: Arial, Helvetica, sans-serif;
  color: white;
  display: flex;
  flex-direction: column;
}

.right img {
  height: 80vh;
  width: 100%;
}

    Combine all your credit cards in one place

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laborum architecto repellendus deserunt ex quo impedit in blanditiis facere, nisi quos, excepturi doloribus fuga expedita amet.


text:
Q: Long delay in receiving some messages Yesterday morning I received a series of messages (some personal, others of account validation) that were 36 hours old, while during this time I continued to exchange without any particular problem.
Likewise today, in the middle of an important conversation, I stopped receiving messages, I tried an online service to send an SMS to my number and I didn't receive it. After restarting the phone, the online service works but I still haven't received the messages from earlier.
I can't afford to wait several days waiting.
How to what messages I haven't received yet and how to prevent it from happening again?
Note. I was under iOS 14 Beta 4, I deleted the developer profile to see if I could go back to iOS 13 but now it just says "iOS 14.0, your software is up to date".


text:
Q: jQuery: Bind 2 events and execute only one I have a table where, when I click on a cell, the cell turns editable.
If I change the content of the cell, I want to execute an AJAX request to save the data to the database, only if:

*

*Focus out of the cell

*Press enter key

The problem is that the event is executed twice if I press "Enter" and once if I focusout of the cell; and I think I know why: enter keypress qualifies as focusout as well. This is the code:
$(document).on('focusout keypress', '.row_data', function(event){..}

I tried to limit that inside the event:
if ( (event.type === "keypress" && event.which === 13) || (event.type === "focusout" && event.which !== 13) ) {...}

but unfortunately, it will not work.
Any idea why this is failing? Any idea how i can make it work?
Thanks in advance!

A: How about adding a flag to see if this event has already fired before firing again?
$(document).on('focusout keypress', '.row_data', function(event){
    if ($(this).data('has-event-fired') {
        // Event already fired! Reset our flag and bail!
        $(this).data('has-event-fired', false);
        return;
    }

    // First time we're firing here. Set our flag and fire event as normal.
    $(this).data('has-event-fired', true);

    // Rest of event handler
}

That should force your event to only fire once per action, and will reset itself after both events fire. It could get wonky if only one event manages to fire, though, but it's worth a try.

A: try adding event.stopPropagation(); to your callback function and then only listen to focusout
$('td').on('focusout', '.row_data', function(event){
    event.stopPropagation();
}

A: event.preventDefault() can stop controlling this default behavior and you can check condition accordingly.


text: Q: Error "nothing to be done for x86_64_def" when trying to configure kernel I am learning device drivers development from the book by John Madieu. The book tells me to run the command make x86_64_def to configure the kernel, but when I enter that in to the terminal, an error message shows up, saying nothing to be done for x86_64_def. The x86_64_def file is located in linux/arch/x86/config.


text:
Q: CSS: Leaflet markers borders stay displayed as undesirable effect After have changed marker icon (same as original, just colorized), borders are still displayed under Firefox, not from Chromium :

This CSS code has no effect:
border: none; / border: 0;
overflow: hidden;

An idea to force hide this undesirable effect?

A: In fact, this effect has added by an outside element: .leaflet-pane.leaflet-shadow-pane ; no rule applied on .leaflet-pane.leaflet-marker-pane that contain markers.
Code inspection has been not easy: element to hide
Solved by simple display: none; rule on this element .leaflet-pane.leaflet-shadow-pane: you can see

A: Seems rather like the "border" you see is actually the placeholder for a broken image.
Typically if your custom Marker icon's shadow is missing (e.g. you forgot to change its default value, while not providing the default shadow image asset)
This would also explain the different behaviour between browsers, since each of them hints for broken image differently.


text:
Q: 403 and 404 error on AJAX with code that has worked elsewhere So I have no idea what the issue could be with this code... because I have it working on another site I created. The idea is simple. Add an event listener on a button, then when it is pressed, the user is asked if they really want to delete the row, then AJAX POSTs that data to my server, which does the rest of the heavy lifting. But, when I press delete I'm getting a 403 error and what is weirder, up in the url bar, I'm seeing what looks like an HTML 4.01 page, and it says in the following in the URL bar:
The link on the
referring
page seems to be wrong or outdated. Please inform the author of
that page

Even though, if you put that into the browser bar, it gets to it just fine. Here is my AJAX/JavaScript code:
var delBut = table.getElementsByTagName("button");
for (var i = 0; i < delBut.length; i++) {
    var but = delBut[i];
    but.addEventListener("click", function() {
        var really = confirm("Are you sure you want to delete this entry? This cannot be undone.");
        if (really) {
            var table = but.parentElement.parentElement.parentElement.parentElement.getElementsByTagName("input").location.value.charAt(0);
            switch(table){
                case 'h': table = "logins"; break;
                case 'n': table = "network"; break;
                case 'p': table = "passwords"; break;
            }
        var ID = but.parentElement.parentElement.id
        var loc = but.parentElement.parentElement.parentElement.parentElement.getElementsByTagName("input").location.value;
        console.log(table, ID, loc);
        var ajax = new XMLHttpRequest();
        ajax.open("post", "../internalPages/index.php?action=deleteEntry", true);
        ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajax.send('table=' + encodeURIComponent(table) + '&ID=' + encodeURIComponent(ID) + '&loc=' + encodeURIComponent(loc));
        ajax.onload = function() {
            window.location = ajax.responseText.trim();
        }
    }
    }, false);
}

By the way, I've console.loged the variables and they are all getting captured correctly. And here is the PHP code:
case "deleteEntry":
    $location = filter_input(INPUT_POST, "loc", FILTER_SANITIZE_STRING);
    $ID = filter_input(INPUT_POST, "ID", FILTER_SANITIZE_NUMBER_INT);
    $table = filter_input(INPUT_POST, "table", FILTER_SANITIZE_STRING);
    if (empty($ID) || empty($table)){
        $message = "
There was an application error. Please try again.
";
        $_SESSION['message'] = $message;
        if ($location !== "home"){
            echo "/afton/internalPages/index.php?action=$location";
        } else {
            echo "/afton/index.php?action=$location";
        }
        exit;
    } switch($table) {
        case "passwords": $table = "passwords"; break;
        case "network": $table = "network"; break;
        case "logins": $table = "logins"; break;
        default:
            $message = "
There was an application error. Please refresh the page and try again.
";
            $_SESSION['message'] = $message;
        if ($location !== "home"){
            echo "/afton/internalPages/index.php?action=$location";
        } else {
            echo "/afton/index.php?action=$location";
        }
        exit;
        break;
    }
    $result = deleteEntry($ID, $table);
    if ($result === 1) {
        $message = "
The entry was successfully deleted from the database
";
        $_SESSION['message'] = $message;
        if ($location !== "home"){
            echo "/afton/internalPages/index.php?action=$location";
        } else {
            echo "/afton/index.php?action=$location";
        }
        exit;
    } else {
        $message = "
Nothing was deleted from the database
";
        $_SESSION['message'] = $message;
        if ($location !== "home"){
            echo "/afton/internalPages/index.php?action=$location";
        } else {
            echo "/afton/index.php?action = $location";
        }
        exit;
    }
break;

A: EDIT: Seems like I guessed wrong... According to newer comments.
Looking at your PHP you have something like echo "/afton/internalPages/index.php?action=$location";} and echo "/afton/index.php?action=$location"; that makes me assume the pages are served at http://localhost/afton/
The problem is that on your ajax, you are trying to reach ../internalPages/index.php?action=deleteEntry the ../ will make the browser move up one directory level, so if the page is served at http://localhost/afton/, it will translate to http://localhost/internalPages/index.php?action=deleteEntry.
You got 2 options, just remove the ../ or keep using absolute URLs like in your PHP, that would give /afton/internalPages/index.php?action=deleteEntry

A: Well if anyone needs a good humbling.......it was me. I had the directory "internalPages" spelled "interalPages" on my server. You were all right, feel free to use all the I told-you-sos that you would like.


text:
Q: Is there a way to consciously freeze an Android phone for some time from within an application? I am trying to build an application that will, upon user's consent, freeze the phone for some time during which period the user can't really close the application or move out to another. Is there a way to do this?

A: You can not "freeze" the phone, but there is a way to block usage:
you can create a full screen overlay.
Here is a random sample from the internet.
This requires a special permission, and may be seen as a malware behavior so your app may not be allow in the Google Play Store.
And you have to be very careful with this, since if you do not remove it in time the user will be forced to reboot the phone.


text:
Q: Where is Data Source=MvcMovie.db? https://learn.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/model?view=aspnetcore-2.2&tabs=visual-studio-code
I am trying the Visual Studio Code following the above tutorial to create Razor Pages which I did manage to run successfully to perform CRUD for Movie model. What puzzle is me when I look at the appsettings.json, it has
"ConnectionStrings": {
    "MovieContext": "Data Source=MvcMovie.db"
My question is, where is my database of the above configuration? It looks very different from my Visual Studio Community IDE. I understand one is xml and another is JSON. But this JSON data source didn't specify which sql instance name?

A: In the startup class, you will see in the method ConfigureServices something like this
services.AddDbContext<RazorPagesMovieContext>(options =>
    options.UseSqlite(
        // This is one way to get your connection from the appsettings.json
        // the result of this call is: "Data Source=MvcMovie.db"
        Configuration.GetConnectionString("MovieContext"))
    );


text:
Q: Julia: Override method to add functionality I would like to extend an abstract type's method in a concrete type.
I can do it with a new method but this introduces more complexity:
abstract type AbstractTask end
function complete(task::AbstractTask)
    complete_concrete_task(task)
    println("Done!")
end

struct Task <: AbstractTask
    name::String
end
complete_concrete_task(task::Task) = println(task.name)

coding = Task("coding")
complete(coding)

In Python, I would use the super operator. Is there an equivalent in Julia?
Thanks in advance!

A: I would say that using dispatch the way you did introduces much less cognitive complexity than a call to super.  But you can use invoke select methods of supertypes:
julia> abstract type AbstractTask end

julia> function complete(task::AbstractTask)
           println("Done!")
       end
complete (generic function with 1 method)

julia> struct Task <: AbstractTask
           name::String
       end

julia> complete(task::Task) = (println(task.name); invoke(complete, Tuple{AbstractTask}, task))
complete (generic function with 2 methods)

julia> coding = Task("coding")
Task("coding")

julia> complete(coding)
coding
Done!

Of course this requires you not to forget to add it to every subtype method, which is the additional complexity I mean.
The good thing is that invoke with a constant type parameter will be compiled away (or so I have read), so there's not even overhead from dispatch.


text:
Q: Can I enable hiding the dock on my MacBook monitor only? When at home I use my 13" MacBook Pro hooked up to an 27" external monitor. When working on my 27" screen I prefer to have a visible dock at all times. I have enough screen real estate to afford this luxury.
When I'm on the road working on my 13" screen I prefer to automatically hide the dock as it really gets in the way when screen real estate is limited.
I now manually switch between enabling and disabling hiding (using ⌥⌘D) but I would prefer this to happen automatically. Can I enable hiding the dock on my MacBook monitor and disable hiding the dock on my external monitor?

A: I was able to use the previously suggested ControlPlane app along with some simple shell scripts to get this working.
First, I created a context for having my Thunderbolt Display plugged in ("Desk"), and one that negated that choice ("Lap"). Next, I made two simple shell scripts to toggle the autohide setting and restart the Dock. I put them in a .controlplane directory in my home folder.
~/.controlplane/dock-hiding-on.sh
defaults write com.apple.dock autohide -bool true && killall Dock
~/.controlplane/dock-hiding-off.sh
defaults write com.apple.dock autohide -bool false && killall Dock
I then set those files to be executable.
Lastly, I set the correct script to run for the appropriate ControlPlane context. (Note: I had to show hidden files in the dialog with "⌘+⇧+.")

A: Applications like Sidekick or ControlPlane allow you to change settings (network, desktop picture, custom terminal actions) based on location evidences (geolocation, attached devices...etc).
I'm sure you will be able to use one of those to detect you are at your desk with your 27" plugged in and run a command disabling auto-hide.


text:
Q: NaN in excel cell generating error when reading with pandas: ValueError: cannot convert float NaN to integer I was able to identify the issue but not the solution when using:
pd.read_excel(file, sheet_name)

ValueError: cannot convert float NaN to integer

Problem is that I have a column full of numbers with decimal cases (floats) and in some rows I have "NaN" and that is causing the error, but do not really know how to solve it.
Ideas?


text:
Q: How to make sure Application takes latest change in Nuget package on each build? I am using continuous integration  to build my nuget project.It builds my application and drops nuget package to Artifactory. The nuget package is then referenced by other applications.
Each time I make changes to nuget package and Jenkins builds it,
How do I make sure the client application's Jenkins build is referring latest change from the source nuget package.

A: You need to choose appropriate strategy for dependency resolution.
Please, kindly inspect this article from MSFT.
It explains in great details what options are. In your case you might be satisfied with having highest major version for your dependency to make sure you have Jenkins build to pull the latest dependencies. Overall, everything depends on multiple things like what your versioning schema is, what kind of manifest you use (csproj file, packages.config or custom manifest), how many Nuget feeds your have, how do you want to protect other projects from breaking changes and so on...
If you use csproj file to control your dependencies, you can specify version constraints via PackageReference property:
<ItemGroup>
    <!-- ... -->
    <PackageReference Include="Contoso.Utility.UsefulStuff" Version="3.6.*" />
    <!-- ... -->
</ItemGroup>

If you use Nuget to install dependency for your projects, you can specify how you want to resolve the version. For example, to pull the latest version for package myPackage, you can do this:
nuget install myPackage -DependencyVersion Highest


text:
Q: Random Segmentation Fault - Raspberry Pi, C++, MySQL I'm having an issue with segmentation faults crashing my c++ program. I've narrowed it down to executing mysql queries. If I remove the query it never crashes but when it does run the query it may work 5 times in a row and crash or it might go 20 times before a segmentation fault, it's very random.
This is the code to connect.
MYSQL *conn;
void connectMysql(){

    const char *server = "localhost";
    const char *user = "root";
    const char *password = "myPpassword";
    const char *database = "myDatabase";

    conn = mysql_init(NULL);

    /* Connect to database */
    if (!mysql_real_connect(conn, server,
        user, password, database, 0, NULL, 0)) {
        fprintf(stderr, "%s\n", mysql_error(conn));
        exit(1);
    }
}

Then I do this to run my queries. It'll happen with other queries as well.
connectMysql();
std::string query = "UPDATE settings SET tempFormat = '" + to_string(tempFormat) + "'";
std::cout << query << std::endl;  // print string to terminal
mysql_query(conn, query.c_str());
std::cout << "done" << std::endl;  // print done to terminal
mysql_close(conn);

Using std::cout to write to terminal it looks like it's happening with mysql_query function. I print the query string to terminal and that always looks good going into mysql_query even when it crashes. When it does crash I never see the "done" printed to terminal so it doesn't make it that far.
I've just recently discovered this as I don't save to database that often so not exactly sure what c++ mysql library I'm using but this is what I use to install it.
sudo apt-get install libmariadb-dev-compat libmariadb-dev -y

Thanks


text:
Q: Amount in words should come automatically after total amount In my application I have fields like tax_1_amount, tax_2_amount, tax_3_amount, invoice_amount and total_invoice_amount. When the total invoice amount is calculated then the amount_in_words field should be automatically updated by the total amount in words. Total amount is calculated as follows:
@total_tax_amount = @invoice.tax_1_amount + @invoice.tax_2_amount + @invoice.tax_3_amount
@total_amount = @total_tax_amount + @invoice.invoice_amount

Can anyone tell me if there is any generator or any gem for that. Or what code shall I write for that.

A: You need to
include ActionView::Helpers::NumberHelper

if trying to use anywhere other than a view.

A: I'm not sure if I understood but check this links
http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_human
or
https://github.com/bcarrere/currency-in-words


text:
Q: PHP/Oracle: Time representation Disclaimer: I'm fully aware that the best way to represent date/times is either Unix timestamps or PHP's DateTime class and Oracle's DATE data type.
With that out of the way, I'm wondering what the most appropriate data types are (in PHP, as well as Oracle) for storing just time data.  I'm not interested in storing a date component; only the time.
For example, say I had an employee entity, for which I wanted to store his/her typical work schedule.  This employee might work 8:00am - 5:00pm.  There are no date components to these times, so what should be used to store them and represent them?
Options I have considered:

*

*As strings, with a standard format (likely 24-hour HH:MM:SS+Z).

*As numbers in the range 0 <= n < 24, with fractional parts representing minutes/seconds (not able to store timezone info?).

*As PHP DateTime and Oracle DATE with normalized/unused date component, such as 0001-01-01.

*Same as above, only using Unix timestamps instead (PHP integer and Oracle TIMESTAMP).

Currently I'm using #3 above, but it sort of irks me that it seems like I'm misusing these data types.  However, it provides the best usability as far as I can tell.  Comparisons and sorts all work as expected in both PHP and Unix, timezone data can be maintained, and there's not really any special manipulation needed for displaying the data.
Am I overlooking anything, or is there a more appropriate way?

A: If you don't need the date at all, then what you need is the interval day data type. I haven't had the need to actually use that, but the following should work:
interval day(0) to second(6)

A: The option you use (3) is the best one.
Oracle has the following types for storing times and dates:

*

*date

*timestamp (with (local) time zone)

*interval year to month

*interval day to second

Interval data types are not an option for you, because you care when to start and when you finish. You could possibly use one date and one interval but this just seems inconsistent to me, as you still have one "incorrect" date.
All the other options you mentioned need more work on your side and probably also lead to decreased performance compared to the native date type.
More information on oracle date types: http://docs.oracle.com/cd/B19306_01/server.102/b14225/ch4datetime.htm#i1005946

A: I think that the most correct answer to this question is totally dependant on what you are planning to do with the data. If you are planning to do all your work in PHP and nothing in the database, the best way to store the data will be whatever is easiest for you to get the data in a format that assists you with what you are doing in PHP. That might indeed be storing them as strings. That may sound ghastly to a DBA, but you have to remember that the database is there to serve your application. On the other hand, if you are doing a lot of comparisons in the database with some fancy queries, be sure to store everything in the database in a format that makes your queries the most efficient.
If you are doing tasks like heavy loads calculating hours worked, converting into a decimal format may make things easier for calculations before a final conversion back to hours:minutes. A simple function can be written to convert a decimal to and fro when you are getting data from the database, convert it to decimal, do all your calculations, then run it back through to convert back into a time format.
Using unix timestamps is handy when you are calculating dates, probably not so much when you are calculating times though. While there seem to be some positives using this, such as very easily adding a timestamp to a timestamp, I have found that having to convert everything into timestamps to calculations is pesky and annoying, so I would steer clear of this scenario.
So, to sum up:

*

*If you want to easily store, but not manipulate data, strings can be
an effective method. They are easy to read and verify. For anything
else, choose something else.

*Calculating as numbers makes for super easy calculations. Convert
the time/date to a decimal, do all your heavy hiting, then revert to
a real time format and store.

*Both PHP's Datetime and Oracle's Date are handy, and there are some
fantastic functions built into oracle and PHP to manipulate the
data, but even the best functions can be more difficult then adding
some decimals together. I think that storing the data in the
database in a date format is probably a safe idea - especially if
you want to do calculations based on the columns within a query.
What you plan to do with them inside PHP will determine how you use
them.

*I would rule option four out right off the bat.

Edit: I just had an interesting chat with a friend about time types. Another thing you should be aware of is that sometimes time based objects can cause more problems than they solve. He was looking into an application where we track delivery dates and times. The data was in fact stored in datetime objects, but here is the catch: truck delivery times are set for a particular day and a delivery window. An acceptable delivery is either on time, or up to an hour after the time. This caused some havoc when a truck was to arrive at 11:30pm and turned up 45 minutes later. While still within the acceptable window, it was showing up as being the next day. Another issue was at a distribution center which actually works on a 4:00AM starting 24 hour day. Setting up times worked for the staff - and consolidating it to payments revolving around a normal date proved quite a headache.


text:
Q: How to check if a page is displaying a specific  tag What is the best way to determine if a page on a website is REALLY displaying a specific img tag like this <img src=http://domain.com/img.jpg>?   A simple string comparison is easy to fool using http comments <!-- -->.  Even if the html tag exists it could be deleted with JavaScript.  It could also be obscured by placing an image over it using CSS.    Do you know of a solid method of detecting the img tag dispute these obscuring attacks listed?   Do you know of another method of obscuring the image?   Python code to detect the image would be ideal,  but if you know of a good tactic or method that will earn you a +1 from me.

A: The only surefire way I can think of is to render the page and check. It is simple to strip comments etc. But if scripts are involved, it is not possible to have a general solution that will not amount to executing them (I believe this is the first time I ever invoked Church's theorem...).

A: I don't think you can ever be sure. First, you're not even sure the program will stop.
Aside from that, consider the following scenarios. Your <img> can be added, removed or get obscured using JavaScript, CSS and/or server-side:

*

*randomly.

*at specific times.

*to a certain part of the world.

*according to differences and bugs between browsers.

Google is facing a similar problem - people are hiding search keywords in hidden text and links to get a better rank. Their solution is to penalize sites with hidden text. They get away with it because they're Google; people depend on them for traffic.
As for you, you can't do much better than to ask nicely...

A: You could place a script anywhere that processes the request, counts the view and delivers the image like this:
http://yourhost.com/imageprocess?image=media/foo/bar.jpg
Then you can be sure that the image was loaded. If if was viewed, you of course can't be sure, however.


text:
Q: Implement picture file on the right side of the graph like a "legend" (in tooltip picture file implementation is possible, but need it as a legend) is it possible to implement a picture on the right side next to a graph tile? Like a legend?
I just found out how to implement a picture in the tooltip with the help of the HoloViz bokeh documentation. But I want a picture file as a "legend" for the graph. The tooltip picture file is of course only shown when the mouse hovers over a data point.
Thank in advance.
Best regards


text:
Q: Access TextView and Progressbar in Recyclerview from IntentService I am having a recyclerview which has a TextView (progresstxt) and a Progressbar (downloadprogress) as part of the inflated items.
I need to know how I can access the TextView and Progressbar in the SimpleAdapter from the IntentService so I can update their values?
I am trying to achieve this with a BroadcastReceiver but it doesn`t work, the TextView and Progressbar are not being updated.
Thank you in advance.
I access the TextView and Progressbar through onBindViewHolder.
public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.SimpleViewHolder> implements FollowRedirectsCallback {

private final Context mContext;
private String recievedStr;
private int receivedProg;

private MyBroadcastReceiver myBroadcastReceiver;
private MyBroadcastReceiver_Update myBroadcastReceiver_Update;

public static class SimpleViewHolder extends RecyclerView.ViewHolder {
        public final TextView title, progresstxt;
        public ProgressBar downloadprogress;

        public SimpleViewHolder(View view) {
            super(view);
            title = (TextView) view.findViewById(R.id.simple_text);
            progresstxt = (TextView) view.findViewById(R.id.progress_text);
            downloadprogress = (ProgressBar) view.findViewById(R.id.progressdownload);
        }
    ...
public class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            recievedStr = intent.getStringExtra(MoService.EXTRA_KEY_UPDATE);
            //progresstxt.setText(result); ?
            //how to access the TextView in onBindViewHolder?
        }
    }

public class MyBroadcastReceiver_Update extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        receivedProg = intent.getIntExtra(MoService.EXTRA_KEY_UPDATE_PROGRESS, 0);
        //downloadprogress.setProgress(update); ?
        //how to access the Progressbar in onBindViewHolder?

    }
}

...

@Override
    public void onBindViewHolder(final SimpleViewHolder holder, final int position) {
      //
        myBroadcastReceiver = new MyBroadcastReceiver();
        myBroadcastReceiver_Update = new MyBroadcastReceiver_Update();

        //register BroadcastReceiver
        IntentFilter intentFilter = new IntentFilter(MoService.ACTION_MyIntentService);
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        mContext.registerReceiver(myBroadcastReceiver, intentFilter);

        IntentFilter intentFilter_update = new IntentFilter(MoService.ACTION_MyUpdate);
        intentFilter_update.addCategory(Intent.CATEGORY_DEFAULT);
        mContext.registerReceiver(myBroadcastReceiver_Update, intentFilter_update);

      //
        holder.progresstxt.setText(recievedStr);
        holder.downloadprogress.setProgress(receivedProg);
        holder.progresstxt.setVisibility(View.VISIBLE);
        holder.downloadprogress.setVisibility(View.VISIBLE);

      //
    }

    mContext.unregisterReceiver(myBroadcastReceiver);
    mContext.unregisterReceiver(myBroadcastReceiver_Update);
}

Through a IntentService (MoService) several file operations are done and I want to access/update the TextView and Progressbar from this IntentService.
public class MoService extends IntentService {

public static final String ACTION_MyIntentService = "com.sample.RESPONSE";
    public static final String ACTION_MyUpdate = "com.sample.UPDATE";
    public static final String EXTRA_KEY_UPDATE = "EXTRA_UPDATE";
    public static final String EXTRA_KEY_UPDATE_PROGRESS = "EXTRA_UPDATE_PROGRESS";
    String message;
    int mProgress;
..
public MoService() {
        super("MyService");
    }

    @Override
    public void onCreate() {
        context = this;
        super.onCreate();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
    //
        Intent intentUpdate = new Intent();
        intentUpdate.setAction(ACTION_MyUpdate);
        intentUpdate.addCategory(Intent.CATEGORY_DEFAULT);
        intentUpdate.putExtra(EXTRA_KEY_UPDATE, message);
        sendBroadcast(intentUpdate);
    //
    }

class MyDownloadDownloadStatusListener implements DownloadStatusListener {
        @Override
        public void onDownloadComplete(DownloadRequest request) {
           message = "Status: completed...";
           mProgress = 0;
           progresstxt.setVisibility(View.GONE);
           downloadprogress.setVisibility(View.GONE);
..
  }
}

A: There are a couple of issues with the code. You should not create a new Receiver in your onBindViewHolder method.
There should be a single receiver which updates the Item list used by your adapter and call notifyDataSetChanged on the adapter.
Hope it helps


text:
Q: How can I fix a package does not exist error I am wondering what I can do to get rid of this error : java:4: error: package professorCode does not exist.
I have attached my code and I am using packages that have already been given to me to implement. I am confused because I have the professor code packages downloaded.  My code is here below:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import professorCode.AbstractFileMonitor;
import professorCode.FileTextReader;
import professorCode.FileTextWriter;

public class FileManager extends AbstractFileMonitor implements FileTextReader, FileTextWriter {
    String filePath;

    public FileManager(String filePath) {
        super(filePath);
    }

    public String readText(String path) throws IOException {
        return new String(Files.readAllBytes(Paths.get(path)));
    }

    public Set<String> getAllLines(String path) throws IOException {
        String allText = this.readText(path);
        Set<String> stringArrayList = new HashSet();
        String[] var4 = allText.split("\n");
        int var5 = var4.length;

        for(int var6 = 0; var6 < var5; ++var6) {
            String line = var4[var6];
            stringArrayList.add(line.trim());
        }

        return stringArrayList;
    }

    public String getLastLine(String path) throws IOException {
        String[] segments = this.readText(path).split("\n");

        for(int i = segments.length - 1; i > -1; --i) {
            String clean = segments[i].trim();
            if (!clean.isEmpty()) {
                return clean;
            }
        }

        return "";
    }

    public void writeToFile(String string, String path) throws IOException, IllegalArgumentException {
        String clean = string.trim();
        if (clean.isEmpty()) {
            throw new IllegalArgumentException();
        } else {
            BufferedWriter out = new BufferedWriter(new FileWriter(path, true));
            out.write(string + "\n");
            out.close();
        }
    }

    public void setFilePath(String path) {
        if (path != null && !path.trim().isEmpty()) {
            this.filePath = path;
        } else {
            throw new IllegalArgumentException();
        }
    }

    public String getFilePath() throws IllegalStateException {
        if (this.filePath == null) {
            throw new IllegalStateException();
        } else {
            return this.filePath;
        }
    }
}

Thank you


text:
Q: IntelliJ plugin handle on cmd action (go to declaration) For a custom IntelliJ plugin I am trying to write a handler that is invoked when the user uses the "cmd" key (or "control" in windows) and clicks in the value of an XML tag (which usually triggers a "go to declaration" or "show usages") in regular java code. In the tutorials I have found samples for creating a plugin that handles a click to an entry in the menu bar, but I need a handler for that one specific action.
Does IntelliJ support handling that event and execute a custom action? Thank you for your help in advance.


text:
Q: How do I send a module to a Powershell Start-Job? I send in a module to Start-Job but it seems to be empty.
Why isn't it filled with my start method?
$m = New-Module -ScriptBlock{
        function start(){
            "started"
        };
    } -AsCustomObject

$m.start()

Start-Job -ScriptBlock{
    $module = $args[0]
    "<argsO:$module>"

} -ArgumentList $m

I run the above and then:
PS C:\temp> job 510 | Receive-Job -Keep

to get:
<argsO:>

Alas, the $module seems to be empty.

A: Your $module variable is being populated, it just doesn't produce any output. You can check by putting $module | gm inside your Start-Job and you will see that it is a PSCustomObject:
Start-Job -ScriptBlock{
    $module = $args[0]
    $module | gm

} -ArgumentList $m

Get-Job | Wait-Job | Receive-Job

Unfortunately what you're trying to do won't work because the object gets deserialized when its passed as an argument and as a result it loses its methods, so attempting to call .start() within the job returns:

[Deserialized.System.Management.Automation.PSCustomObject] does not
  contain a method named 'start'.


text:
Q: LINQPad SQLite numeric value cast A table in sqlite file has a INTEGER column and a REAL column.
When I use LinqPad IQ driver to connect to this file, the data context is made with a Int32? field and a Single? field.
But the real data in the sqlite table are Int64? and double?, so InvalidCastException are thrown when I try to query the data.
Is there a way I can work around this problem?

A: The problem with SQLite is that the column types are just a suggestion. In other words, users can put anything they like into any column, regardless of its type. This plays havoc with ORMs or queries that rely on static typing.


text:
Q: Store tooltip for a control in C#.net IDE: Microsoft Visual Studio 2010
Platform: C#.Net
Hi,
    I am trying to store the tooltip for a control in a variable, but didn't achieve any result for that yet. Any suggestions?
Here is the code I have tried so far,
var tooltip = new ToolTip();
           var tool1 =  tooltip.GetToolTip(HCp10);
           MessageBox.Show(tool1);

A: If you really need to know the tooltip for a control, you could set the control's tag to the tooltip
Control c = new Control();
ToolTip t = new ToolTip();
c.Tag = t;

Tooltip t = (ToolTip)c.Tag;


text:
Q: How can I print a board using a two dimensional array? I want to print a 5x5 board for a game, at the moment I can only print 5 lines while populating the array. My board currently looks like this:

Which is technically a 2 row 5 columns board.
This is the output I expect:

The problem is that I need a 5x5 version of that same board but it only prints 5 lines (which is the size of the array).
I've tried changing the for loop many times but nothing has worked so far
This is my code:
    //
    // Created by renan on 31/08/2019.
    //

    #include <iomanip>
    #include <iostream>
    #include "Board.h"

    void Board::displayBoard() {
        for (int row = 0; row < ROWS; row++) {          //ROWS and COLS
    are integers with value 5
                for (int col = 0; col < COLS; col++) {
                    board[row][col] = ' ';

                    if (row % 2 == 0) {
                        cout << " ---";
                    } else {
                        if (col == 0) {
                            cout << "|";
                        }
                        if(board[row][col] == ' '){
                            cout << setw(4) << "|";
                        } else {
                            cout << setw(1) << board[row][col] << " |";
                        }
                    }
                }
                cout << endl;

        }

    }

Board.h
    #include <iostream>
    using namespace std;

    class Board {
    private:
        static const int ROWS = 11;
        static const int COLS = 5;
        char board[ROWS][COLS];
    public:
        void displayBoard();

    };

A: I corrected and simplified your code a bit. Hope it will help you to understand what was wrong with your code.
void drawHorizontalSeparater() {
    for (int i = 0; i < 5; i++) {
        cout << " ---";
    }
    cout << endl;
}

void drawSeparatedValues(int row) {
    cout << "|";

    for (int col = 0; col < 5; col++) {
        board[row][col] = ' ';

        cout << " " << board[row][col] << " |";
    }
    cout << endl;
}

void displayBoard() {
    drawHorizontalSeparater();
    for (int row = 0; row < 5; row++) {
        drawSeparatedValues(row);
        drawHorizontalSeparater();
    }
}

Result:
 --- --- --- --- ---

|   |   |   |   |   |

 --- --- --- --- ---

|   |   |   |   |   |

 --- --- --- --- ---

|   |   |   |   |   |

 --- --- --- --- ---

|   |   |   |   |   |

 --- --- --- --- ---

|   |   |   |   |   |

 --- --- --- --- ---


text:
Q: Java OutOfMemoryException unable to create new native thread I have a server written in jav running at 100MB of RAM or so on startup(info gotten from viewing the process explorer). However, when a client connects to it to transfer a big file, the RAM usage goes up until around 160MB or so and I got the error below. I have tried setting -Xmx128m, -Xmx256m, -Xmx512m, -Xmx1024m to no avail. What should I do to prevent this from happening. This only happens when a client tries to get a big file from the server
java.lang.OutOfMemoryError: unable to create new native thread
java.lang.Thread.start0(Native Method)
java.lang.Thread.start(Unknown Source)
com.sun.jndi.ldap.Connection.<init>(Unknown Source)
com.sun.jndi.ldap.LdapClient.<init>(Unknown Source)
com.sun.jndi.ldap.LdapClient.getInstance(Unknown Source)
com.sun.jndi.ldap.LdapCtx.connect(Unknown Source)
com.sun.jndi.ldap.LdapCtx.<init>(Unknown Source)
com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(Unknown Source)
com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(Unknown Source)
com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(Unknown Source)
com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(Unknown Source)
javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
javax.naming.InitialContext.init(Unknown Source)
javax.naming.ldap.InitialLdapContext.<init>(Unknown Source)

A: The problem is that you are unable to create another thread. Often this is because you cannot allocate more stack space, but there is often an OS limitation in 32-bit OSes which set this limit lower.
How many threads do you have when you get this error?
You can print
System.out.println("thread.count=" + Thread.getAllStackTraces().size());

BTW: Increasing the heap size can reduce the amount of virtual memory free to create stack space for new threads. (This is only a problem on 32-bit JVMs) This doesn't appear to be your problem, but it can be surprising that in this case, the first thing to try is to reduce your heap space.


text:
Q: Customized CollectionViewGroup and ListCollectionView but when add a new item to listbox, it does now work I want to add a new property to CollectionViewGroup
So I reference the article:
Custom CollectionViewType does not support multiple selection using shift key
when click button to add new item
collection add success(default count=9, add one, total count=10),

but listbox does not show the new item group.
maybe something miss to implement.
please help me, or give me the keyword to google.
Thank you.
[Window1.xaml]
<Window.Resources>
    <CollectionViewSource x:Key="EmployeesSource" Source="{Binding Employees}" CollectionViewType="local:EmployeeCollectionView">

        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="HireDate"/>
        </CollectionViewSource.GroupDescriptions>

    </CollectionViewSource>

    <DataTemplate x:Key="EmployeeTemplate">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding FirstName}" />
            <TextBlock Text="{Binding LastName}" />
        </StackPanel>
    </DataTemplate>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50"/>
        <RowDefinition Height="*"/>

    </Grid.RowDefinitions>

    <StackPanel Grid.Row="0">
        <Button Name="addItem" Width="50" Height="50" Content="AddItem"  HorizontalAlignment="Left" Click="addItem_Click"/>
    </StackPanel>

    <ListBox Grid.Row="1" ItemsSource="{Binding Source={StaticResource EmployeesSource}}"
     ItemTemplate="{StaticResource EmployeeTemplate}"
     SelectionMode="Extended">
        <ListBox.GroupStyle>
            <x:Static Member="GroupStyle.Default"/>
        </ListBox.GroupStyle>
    </ListBox>
</Grid>

[Window1.xaml.cs]
public partial class Window1 : Window
{

    public ObservableCollection<Employee> Employees { get; set; }

    public Window1()
    {
        InitializeComponent();

        Employees = new ObservableCollection<Employee>
        {
            new Employee { FirstName = "FirstName1", LastName = "LastName1", HireDate = new DateTime(1970, 1, 1) },
            new Employee { FirstName = "FirstName2", LastName = "LastName2", HireDate = new DateTime(1970, 1, 1) },
            new Employee { FirstName = "FirstName3", LastName = "LastName3", HireDate = new DateTime(1980, 1, 1) },
            new Employee { FirstName = "FirstName4", LastName = "LastName4", HireDate = new DateTime(1980, 1, 1) },
            new Employee { FirstName = "FirstName5", LastName = "LastName5", HireDate = new DateTime(1980, 1, 1) },
            new Employee { FirstName = "FirstName6", LastName = "LastName6", HireDate = new DateTime(1990, 1, 1) },
            new Employee { FirstName = "FirstName7", LastName = "LastName7", HireDate = new DateTime(1990, 1, 1) },
            new Employee { FirstName = "FirstName8", LastName = "LastName8", HireDate = new DateTime(1990, 1, 1) },
            new Employee { FirstName = "FirstName9", LastName = "LastName9", HireDate = new DateTime(1990, 1, 1) },
        };
        DataContext = this;
    }

    private void addItem_Click(object sender, RoutedEventArgs e)
    {
        //Employees add suceess(total count=10), but ui does not add the item(1983,1,1)
        Employees.Add(new Employee {
            FirstName = "FirstName10",
            LastName = "LastName10",
            HireDate = new DateTime(1983, 1, 1)
        });
    }
}

class EmployeeCollectionView : ListCollectionView
{
    private readonly IList<EmployeeCollectionViewGroup> _groups;
    public override ReadOnlyObservableCollection<object> Groups
    {
        get { return new ReadOnlyObservableCollection<object>(new ObservableCollection<object>(_groups)); }
    }

    public EmployeeCollectionView(IList list)
        : base(list)
    {
        _groups = list
             .OfType<Employee>()
            .GroupBy(x => x.HireDate)
            .Select(x => new EmployeeCollectionViewGroup(x.Key, x))
            .ToList();
    }

}

class EmployeeCollectionViewGroup : CollectionViewGroup
{
    public EmployeeCollectionViewGroup(object name, IEnumerable<object> protectedItems)
        : base(name)
    {
        foreach (var protectedItem in protectedItems)
            ProtectedItems.Add(protectedItem);
    }

    public override bool IsBottomLevel
    {
        get { return true; }
    }

    //i want to add a new property
    public bool IsDeleting { get; set; }
}

public class Employee : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string m_FirstName;
    public string FirstName
    {
        get { return m_FirstName; }
        set
        {
            m_FirstName = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
        }
    }

    private string m_LastName;
    public string LastName
    {
        get { return m_LastName; }
        set
        {
            m_LastName = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("LastName"));
        }
    }

    private DateTime m_HireDate;
    public DateTime HireDate
    {
        get { return m_HireDate; }
        set
        {
            m_HireDate = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("HireDate"));
        }
    }

}

A: Your code have binded ListBox ItemSource to property Groups of class EmployeeCollectionView, the type of that is ReadOnlyObservableCollection<object>, it is a readonly property. When you add a new employee, it can't notify UI to update.
You can try to change your ListBox tag to:
    <ListBox Grid.Row="1" ItemsSource="{Binding Employees}"
             ItemTemplate="{StaticResource EmployeeTemplate}"
             SelectionMode="Extended">
        <ListBox.GroupStyle>
            <x:Static Member="GroupStyle.Default"/>
        </ListBox.GroupStyle>
    </ListBox>

change ItemSource bind to Employees directly.
Hope that will help you:)


text:
Q: How to restrict user from navigating on click of tabs of navbar in angular? I have a navbar which I want to navigate through only next and back buttons, clicking directly on tabs must be restricted. Below is my code which I tried but they are not working as expected,

                    Profile Details

                    Education & Experience

                    Services Offerings

                    Availability & Fees

                    Listing Details

CSS
.disabled{
    pointer-events: none;
}

With this approach, it's working partially, when I navigate through back and next buttons, the route is loading but the value isn't getting patched, I'll have to reload the page for the new value to get patched.
In approach 2, I have removed routerLink and routerLinkActive, but I want to show a different css for an active tab as below.

Better solution or suggestions are much appreciated.
Thanks in advance.

A: Test link

and writ a function
function preventRloute($event: MouseEvent) {
if (condition) {
    $event.stopPropagation();
    // your code...
    return;
}
// navigates
}


text:
Q: Why does show() only work for a split second? I am trying to have the list items appear on click. When I use the hide() method they start off hidden, but when I add the show() method, it only works for about a a millisecond. Not sure if it is because it always defaults back to the original setting? I basically just want to click the main list  in this case Main List and have the other two appear

$(function() {
  $('.sublist').hide();
  $(".mainlist").on('click', function() {
    $('.sublist').show();
  });
})

    Main List

      Sublist One

      Sublist Two

A: When you click the link the Whole page refreshes. This Means that your code runs Again:
$('.sublist').hide();

What you should do is prevent default behavior like this:
$(".mainlist").on('click', function(event) {
      $('.sublist').show();
      event.preventDefault();
    });

A: The problem is that your page is getting reloaded when you click those a elements, because of the href="" on them. So the divs start out hidden, then clicking shows them, but then the page refreshes and they're back to being hidden again (since that's their default state on a freshly-loaded page, thanks to the hide call in your page-ready callback).
If you don't want those links to be followed, prevent the default action when they're clicked via preventDefault (or return false) in a jQuery handler:
$(function() {
  $('.sublist').hide();
    $(".mainlist").on('click', function(e) {
      e.preventDefault();
      $('.sublist').show();
    });
})

Live Example:

$(function() {
  $('.sublist').hide();
    $(".mainlist").on('click', function(e) {
      e.preventDefault();
      $('.sublist').show();
    });
})

        Main List

          Sublist One

        Sublist Two

Alternately, there's a hack you can use: href="javascript:;", but it's preferable to make the links meaningful, and then use script to provide that meaning.

Separately: You can't have an li directly inside another li like that, you need another ul (or ol) in there. See those links for details.

A: There are two issues:
First, you have li elements nested directly inside li elements - if you want a "sub-list", you need to wrap the sub-items inside a ul (see modified code below).
Second, the link is being followed, which is causing the page to refresh.  If ALL you want to have happen is the sublist items to show, then you should use event.preventDefault on the event (see modified code below).

// no-conflict safe document ready
jQuery(function($) {
  $('.sublist').hide();
  // click event accepts one argument for the "event"
  $(".mainlist").on('click', function(e) {
    // prevent the default "click" action (which is to load the url the link points to)
    e.preventDefault();
    $('.sublist').show();
  });
})

    Main List

        Sublist One

        Sublist Two

A: Since you are using anchor a tag, and there is an empty href attribute, the default behavior should be to redirect the page on anchor click. The fix to this is to either use href="javascript:void(0)" or event.preventDefault() within the click callback

$(function() {
    $('.sublist').hide()
    $(".mainlist").on('click', function(e) {
      /* here, prevents redirection */
      if (e) { e.preventDefault() }
      $('.sublist').show()
    })
})

    Main List

      Sublist One

      Sublist Two

A: This part of your code :
$(".mainlist").on('click', function() {
  $('.sublist').show();
});

Is telling to show the list only during the click event.
Why not using the fadeIn() effects function instead ?

 $( "#appears" ).hide();
$( "#clickme" ).click(function() {
  $( "#appears" ).fadeIn( "slow", function() {
  });
});

    Click here

I'm a list


text:
Q: UPDATE/DELETE performance on partitioned table Hi I'm using table partitioning in my Postgres 9.3.
I've notice that the DELETE and UPDATE queries are much slower when I'm doing them via the parent table.
I see that the constraint_exclusion is working but it's around 10 times slower than deleting/updating directly the table.
Any reason why? Is the partition lookup so expensive??
I have over 300 partitions. Tables are partitioned by client_id.
directly
 (user@localhost:5432) [db01]  [*] # explain analyze delete from events_128 where datastream = 'API';
  Delete on events_128  (cost=0.42..4667.35 rows=13749 width=6) (actual time=55.394..55.394 rows=0 loops=1)
    ->  Index Scan using events_128_datastream on events_128  (cost=0.42..4667.35 rows=13749 width=6) (actual time=0.086..5.396 rows=13821 loops=1)
          Index Cond: ((datastream)::text = 'API'::text)
  Total runtime: 55.432 ms
 (4 rows)

 Time: 55.858 ms

 (user@localhost:5432) [db01]  [*] # delete from events_128 where datastream = 'API';
 DELETE 13821
 Time: 28.673 ms

via parent table
 (user@localhost:5432) [db01]  [*] # explain analyze delete from events where client_id = 128 and datastream = 'API';
  Delete on events  (cost=0.00..4701.72 rows=13750 width=6) (actual time=12.577..12.577 rows=0 loops=1)
    ->  Seq Scan on events  (cost=0.00..0.00 rows=1 width=6) (actual time=0.001..0.001 rows=0 loops=1)
          Filter: ((client_id = 128) AND ((datastream)::text = 'API'::text))
    ->  Index Scan using events_128_datastream on events_128  (cost=0.42..4701.72 rows=13749 width=6) (actual time=0.132..6.275 rows=13821 loops=1)
          Index Cond: ((datastream)::text = 'API'::text)
          Filter: (client_id = 128)
  Total runtime: 12.645 ms
 (7 rows)

 Time: 315.475 ms

 (user@localhost:5432) [db01]  [*] # delete from events where client_id = 128 and datastream = 'API';
 DELETE 13821
 Time: 264.968 ms

Table definitions:
                     Table "public.events"
(user@localhost:5432) [db01]  [] > \d events

        Column             |           Type           | Modifiers
-------------------------------+--------------------------+-----------
 id                            | bigint                   | not null
 actions                       | bigint                   |
 app_installs                  | bigint                   |
 dimensions                    | hstore                   |
 ... 20 more varchar or bigint or date
 datastream                    | character varying(255)   |
 datastream_type               | character varying(40)    |
Indexes:
    "events_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "fk_client_id" FOREIGN KEY (client_id) REFERENCES client(id)
Triggers:
    insert_events_trigger BEFORE INSERT ON events FOR EACH ROW EXECUTE PROCEDURE events_insert_trigger()
Number of child tables: 254 (Use \d+ to list them.)

(user@localhost:5432) [db01]  [] > \d events_128
                       Table "public.events_128"
        Column             |           Type           | Modifiers
-------------------------------+--------------------------+-----------
 id                            | bigint                   | not null
 actions                       | bigint                   |
 app_installs                  | bigint                   |
 dimensions                    | hstore                   |
 ... 20 more varchar or bigint or date
 datastream                    | character varying(255)   |
 datastream_type               | character varying(40)    |
Indexes:
    "events_128_unq_id" UNIQUE, btree (id)
    "events_128_channel" btree (channel)
    "events_128_client_id" btree (client_id)
    "events_128_datasource" btree (datasource)
    "events_128_datasource_class" btree (datasource_class)
    "events_128_datastream" btree (datastream)
    "events_128_datastream_type" btree (datastream_type)
    "events_128_rangeend" btree (rangeend)
    "events_128_rangestart" btree (rangestart)
Check constraints:
    "events_128_client_id_check" CHECK (client_id = 128)
Inherits: events


text:
Q: How to pick random values from dictionary and assign it to the list I have 2 dictionaries (filled by data imported from xml-spreadsheet with few nested foreach loops)
Example Excel-xml looks like this:

Dictionary<string, string> sheet3 = new Dictionary<string, string>();
Dictionary<string, List <KeyValuePair<string,string>>> sheet4 = new Dictionary
                                  <string, List<KeyValuePair<string,string>>>();

each of them contains:
sheet3.Add(situation, succession)
sheet4.Add(srcSituation, new List<KeyValuePair<string,string>>());
sheet4[srcSituation].Add(new KeyValuePair<string, string>(dstSituation, command));

In Sheet4 I can see some kind of "order". Sheet3 shows situation and what this situation feels, looks like. In Sheet4 I have order, You can see, that 1st is training, then it goes to hungry state, then hungry goes to being tired, after that, tired goes to awakening. Each of dstSituation has "command" need to be done between srcSituation and dstSituation in order for it to happen.
I want to pick random "dstSituation" from "sheet4" and write "command" into a txt file. Then look for "situation" == "dstSituation" and add "succession" string into the same txt file. Next I would start the whole thing again, but assuming that possible to pick dstSituation" is where "srcSituation" is only == to previously picked "dstSituation". And so on and so on..Purspose of this is, once I get more "situations" there will be more srcSituation->dstSituation and ofc in Sheet4 there will be much more same srcSituation going into different dstSituation. Imagine this as a map where there is no 1 route to achieve some goal, but there can be randomized route. I have no clue how to write it, cause it's mostly loops operating on dictionaries and lists and I have no clue how to construct proper syntax.

A: Try this code snippet.
......Codes before

Random rnd = new Random();
int randomValue = rnd.Next(0, sheet3.Count-1);
var result = sheet3.ElementAt(randomValue);
/*
 * Your code here
 */


text:
Q: How to get country code/name in the tail command result? I have asked this question about filtering out a LOG file
The LOG file is :
Jan  26 01:05:47 server54 kernel: [41s58.6w4335] INPUT:DROP: IN=eth4 OUT= MAC=d3:ss:43:23:23:43 SRC=1.1.1.1 DST=127.0.0.0 LEN=40 TOS=0x00 PREC=0x00 TTL=254 ID=65259 PROTO=TCP SPT=53252 DPT=22 WINDOW=14600 RES=0x00 RST URGP=0

The command is :
tail -f -n 2 /var/log/kern.log | grep 'INPUT' \
| sed -E 's/^([0-9a-zA-Z: ]*[0-9]{2}:[0-9]{2}:[0-9]{2}).* \
(SRC=[0-9.:]+).*(DST=[0-9.:]+).*$/\1 \2 \3/g'

and the output is :
Jan  26 01:05:47 SRC=1.1.1.1 DST=127.0.0.0

Now I need to feed the result to whois command to get the country(Name or Code) of Source IP address(SRC=) and it would give me a result like this :
Jan  26 01:05:47 SRC=1.1.1.1(US) DST=127.0.0.0(GH)

I just wonder if there is such a capability in that command(tail) or bash script to goes into two direction , I mean, After printing out the filtered LOG, it get the source ip address by another sed and remove the SRC= :
sed -E 's/^.*(SRC=[0-9.:]+).*$/\1/g'| \
 sed -e 's/SRC=//g' | whois ?!!!

and then feed it to whois command and return and add it it to printing result.
Or i have to go to another approach because after each pipe the previous result is gone.

A: Well, while it's possible to do such things using shell, awk and so, but using local MaxMind Database will give you better and more predictible performance. And using other languages like Perl or Python will give you more readable code, for example with Python:
import re
import fileinput
import geoip2.database

reader = geoip2.database.Reader('GeoLite2-City.mmdb')

for line in fileinput.input():
  # Extract source ip using Regexp
  src_ip_search = re.search("SRC=(\S+)", line)
  if src_ip_search is None:
    continue # Didn't find SRC record for some reason
  src_ip = src_ip_search.group(1)
  # Get ISO name of country for that ip from mmdb
  src_iso_code = reader.city(src_ip).country.iso_code
  print(re.sub("SRC=(\S+)", "SRC=\g<1>({})".format(src_iso_code), line)

A: You can do it for example with this script:
out=$(awk '/INPUT/ {print $1,$2,$3,$11,$12}' /var/log/kern.log)
sourcec=$(whois $(echo $out|awk -F'[ =]' '{print $5}')|awk '/Country:/ {print $2}')
targetc=$(whois $(echo $out|awk -F'[ =]' '{print $7}')|awk '/Country:/ {print $2}')


text:
Q: Groovy script to change all users to uppercase I'm trying to change all user names with in a magnolia application to uppercase since we are having case sensitivity issues with our login.
I wrote this groovy script, following an example used to reset passwords to "", to capture the users and change them uppercase but it appears the name property is not being set.
https://documentation.magnolia-cms.com/display/WIKI/Reset+all+passwords
import info.magnolia.jcr.util.NodeUtil
import info.magnolia.jcr.predicate.NodeTypePredicate
import info.magnolia.jcr.util.NodeTypes
session = ctx.getJCRSession("users")
users = NodeUtil.collectAllChildren(session.getNode("/public"), new NodeTypePredicate(NodeTypes.User.NAME))

users.each() {
    changedName = it.name.toUpperCase();
    it.setProperty("name", changedName)
    it.save();
    println "1 " + changedName;
    println "2 " + it.name;
}
session.save();

When I'm checking it.name it is return how they are stored in the mangolia, and not as all uppercase and they are also not being changed in the security app when looking at the username.

A: import info.magnolia.jcr.util.NodeUtil
import info.magnolia.jcr.predicate.NodeTypePredicate
import info.magnolia.jcr.util.NodeTypes

session = ctx.getJCRSession("users")
users = NodeUtil.collectAllChildren(session.getNode("/admin"), new NodeTypePredicate(NodeTypes.User.NAME))

users.each() {
    name = it.name
    changedName = it.name.toUpperCase();
    it.setProperty("name", changedName)
    it.setProperty("jcrName", changedName)
    it.save()

    NodeUtil.renameNode(it, changedName)
    it.getNode("acl_users").getNodes().each { node ->
        newPath = node.getProperty("path").getString().replace(name, changedName)
        node.setProperty("path", newPath)
        node.save()
    }
}
session.save()

Hey, maybe this is what u are looking for. You need to change the Node name and the jcrName in my Version I iterate over the acl_users Node and change the path of each. Hope this works for you.

A: IIRC there's 3 things you need to change.
name is one of them, then there's jcrName property and then you need to change the name of the node itself. At least if you want to see it in security app that way.
For the login itself, what you did should be already sufficient.

A: Try to use the setProperty method of PropertyUtil.
You have to extract all nodes that you need and then loops through them. Supposing that the variable node is the Node you want to change the name, do this:
String newName = StringUtils.upperCase(PropertyUtil.getString(node, "jcrName"));
PropertyUtil.setProperty(node, "jcrName", newName);

jcrName is the property you need to overwrite. Wrap the code into a try/catch block and here we go.
Hope it helps.


text: Q: Minimum requirements of self-answered question Are there any rules (or guidelines) for a Asking and Answering your own question? What are the minimum requirements a self-answered question needs to meet, or do you treat it just like a normal question (like this one)?


text:
Q: ArrayList with a variable number of arrays I need an arrayList that contains a variable number of arrays.
        ArrayList <int[]> aa = new ArrayList<int[]> ();
    int b = 1;
    int array [] = new int [5];

    while ( b == 1){

            for (int i=0; i < array.length; i++){
                array [i] = in.nextInt();
            }

        aa.add(array);
        System.out.println("If you want to insert another array, press 1");
        b = in.nextInt();

    }

logically this code does not work, because the array is overwritten every time and at the end the output is always the same... how can I solve my Problem? .. :)

A: Currently, as you correctly assessed, the contents of a single array get modified, but the same reference is added to your list over and over. If you move the line int array [] = new int [5]; into your while loop, the a new array will be created within each iteration, and no arrays will be overwritten.


text:
Q: Eccentricity in corona product I was studying about graph operation on wiki. Corona product of graphs $G_1$ and $G_2$, is the graph which is the disjoint union of one copy of $G_1$ and $|V_1|$ copies of $G_2$ ($|V_1|$ is the number of vertices of $G_1$) in which each vertex of the copy of $G_1$ is connected to all vertices of a separate copy of $G_2$.
After applying the result on few graphs, I came to this result that the eccentricity of every vertex is not same. For ex in the following example eccentricity is not same for all  vertices. Is there any theoretical way by which I can proof the same for any graphs? I tried by taking the contradiction as but no success. Can anybody help me here. I jus need a hint, not the full proof. Thanks for helping me $\ddot\smile$
Am I right in asking this question? Is there any graph for which ecc is same ?

Credit for this graph goes to the user https://math.stackexchange.com/users/26306/dtldarek.
$\ddot\smile$

A: If $G_1$ has only one vertex, it's possible for every vertex of the corona product to have the same eccentricity: take $G_2$ to be any complete graph. However, if $|V_1|\ge 2$, you're right. Pick $v_1\in V_1$ of maximal eccentricity $e$, and let $v_2\in V_1$ be such that $d(v_1,v_2)=e$. Show that the eccentricity of $v_1$ in the corona product is $e+1$. Then pick a vertex $u$ in the copy of $G_2$ attached to $v_1$, and show that the eccentricity of $u$ in the corona product is $e+2$.


text:
Q: Scaling socket.io broadcast I want to broadcast a 1Kb message with socket.io (node.js framework), every 3 seconds to a large number of users. What is the best way to scale it (1 user = 1 'listener' with socket.on('periodicMessage',callback) )?
There is no other CPU usage (one read of an external database which is filled by an other external module every 3 seconds), so i am trying to know if a simple heroku server can broadcast a message to 10 000, 100 000, 1 million or more users.

A: We have easily scaled to tens of thousands of 'listeners' on a single node.js process. I am not sure how many you actually can scale to, given that each socket is a file descriptor, and the plain vanilla kernel can have 65K fd's for each process, no more.
CPU would not be a problem. If at all, upload bandwidth would be (1KB * 50K users / 3 sec = 50M/3sec = 16MB/s upstream. I never measured Heroku, so don't know if they sustain this. I suppose they do, but maybe they limit you, since they are paying Amazon for this, after all).