text:
Q: Top 10 SQL Server performance bottlenecks What is the most common performance bottleneck that is not caused by the database structure?

A: table scan because:

*

*index does not exist

*stats out of date

*functions in where clause prevent usage

A: *

*Server - Like memory and storage
types.

*Network - Latency and bandwidth
issues.

*Indexing - not sure if you consider
this database structure

*Queries - Bad queries with join
issues that may cause full table
scans.

A: Physical.... Running out of memory and having to go to disk.

A: Let's see (in no particular order)

*

*Cursors

*non-sargable where clauses

*failure to index foreign key fields

*failure to index fields commonly used in the where clause

*correlated subqueries

*accidental cross joins causing the need to distinct the result set

*Badly performing code coming from ORMs

*Code that causes too many reads or is called more than once when it didn't need to be (I've seen applications that send the same code many times when they didn't need to or every time a page is opened)

*network pipe overloaded

*User defined functions causing row-by-row processing

*Parameter sniffing

*out of date statistics

*Union instead of union all

A: The Applying scalar function to each row in the result set
SELECT fn_EveluateSomeValue([ColumnName]) FROM LargeTable

A: Using cursors. For any database.

A: Using table data one row at a time instead of one table at a time (i.e. cursors).
Unnecessary (or badly designed) locks.
Logs logging things that don't need to be logged (Delete from table instead of Truncate table, etc.)
Having constraints on when bulk loading data.  Seriously slows down the insert.  Turn them off, load the data, then turn them back on.

A: Ditto ref cursors, also badly written client apps that get a huge recordset back then process it themselves because the developer didn't understand that sql was anything but a huge heap to hold data in.
Trying to do everything in one huge query instead of breaking it down into sensible steps.
Sometimes this will not give SQL a chance to correctly reduce the amount of index (hopefully !) pages that it has to look at.
Related to this, not understanding how to use temp tables to hand off manipulations prior to updating large indexed tables.
Not having indexes on joins or commonly queried fields.
Not including fields in indexes when you are always seeking and return the same value (for instance formatted name for an employee when you look up using EmployeeID) causing two actions instead of one.

A: Some low-hanging fruit:

*

*Scalar UDFs

*omitting text() in XPath queries

*missing columns in indices (causing key lookups)

*using cursors

*

*not using fast_forward when possible when cursors are necessary

*using JOIN when APPLY will do, or vice versa (test!)

A: Triggers can be a HUGE bottleneck (and headache) when you are processing large batches of commands.

A: If the I/O system in the server isn't up to the job, you can get latch contention on tempdb and this in turn can cause serious performance problems.

A: I tend to run into the following bottlenecks (in order of frequency):

*

*Missing or incorrect indices (resulting in table scans)

*Poorly written queries

*I/O contention

A: Having a poor my.cnf configuration can kill a server even with proper database design and indexing. Read:
http://www.mysqlperformanceblog.com/2006/09/29/what-to-tune-in-mysql-server-after-installation/
http://www.mysqlperformanceblog.com/2007/11/01/innodb-performance-optimization-basics/
http://www.mysqlperformanceblog.com/2007/11/03/choosing-innodb_buffer_pool_size/
http://www.mysqlperformanceblog.com/2007/08/18/how-fast-can-you-sort-data-with-mysql/
http://www.mysqlperformanceblog.com/2007/09/17/mysql-what-read_buffer_size-value-is-optimal/
http://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html
Helpful my.cnf analytical tool:
http://www.day32.com/MySQL/tuning-primer.sh

A: I've never managed to find much useful information on breaking up large queries, in Oracle it seems your advised more to keep everything together in one query rather than use temp tables. You can also get redo log issues if your temp table is holding a lot of data.
I'd like to know more/get some links?

A: faulty hardware. I had a server once where the hard drive had some sectors that it was having difficulty reading and we replacing it had a noticeable performance increase.

A: For us, adjusting the BIOS Settings and Power Plan settings resulted in solid ~2X faster times for queries that were CPU intensive (searching, duration about 5s).
1) BIOS Settings changed from "Performance Per Watt Optimized (DAPC)" to either "Performance" or "Performance Per Watt Optimized (OS)".  Both options seemed to perform similarly however the "OS" controlled one did not run the fan at max continuously.
2) The Windows power plan was changed from "Balanced" to "High performance".
This was discovered after upgrading the CPUs and seeing almost no improvement.
Command to check CPU speed from SQLServerCentral:
PS> gwmi -class win32_Processor | SELECT CurrentClockSpeed, MaxClockSpeed

Update 6/13/2017:  Warning:  That number may report Current = Max however Task Manager may show a a different (much lower) number.  Also the BIOS mode "Performance Per Watt Optimized (OS)" suddenly stopped working for us after some hardware changes.  The CPU was locked at 50% max frequency, regardless of load   Only "Performance" mode (loud fan mode) still achieved max CPU.  We must be missing a firmware/software patch.

A: Clauses to avoid (if possible) :

*

*DISTINCT / UNIQUE

*UNION

*GROUP BY

*ORDER BY


text:
Q: How to control lapack solver presion I'm trying to use Lapack ZHESV subroutine in Fortran to solve a linear system, but the precision seems not good.
Here is the code:
program main
implicit none

integer,parameter::N=4
integer::LDA=N,IPIV(N),LDB=N,LWORK=N*N,info,i
complex*16::A(N,N),B(N),work(N,N),X(N)

A=reshape( (/(1.,0.),(0.,0.),(0.,-6.94908E-13),(0.,-6.94908E-13),&
          &(0.,0.),(1.,0.0352595),(0.,-4.51893E-11),(0.,-4.51893E-11),&
          &(0.,-6.94908E-13),(0.,-4.51893E-11),(1.,0.0376938),(0.,0.),&
          &(0.,-6.94908E-13),(0.,-4.51893E-11),(0.,0.),(1.,0.0378932)/),shape(A))

A=TRANSPOSE(A)

B=(/(1.,0.),(0.,0.),(0.,6.94908E-13),(0.,6.94908E-13)/)
X=B

write(*,*) "--------------B----------------"
write(*,99999) B

CALL ZHESV('Upper',N,1,A,LDA,IPIV,X,N,WORK,LWORK,INFO)

write(*,*) "--------------x----------------"
write(*,99999) X
write(*,*) "-------------INFO--------------"
write(*,*) INFO

write(*,*) "-------------error-------------"
write(*,99999) matmul(A,X)-B

99999 FORMAT ((3X,4(' (',E15.8,',',E15.8,')',:)))
end program main

The outputs are
 --------------B----------------
    ( 0.10000000E+01, 0.00000000E+00) ( 0.00000000E+00, 0.00000000E+00) ( 0.00000000E+00, 0.69490800E-12) ( 0.00000000E+00, 0.69490800E-12)
 --------------x----------------
    ( 0.10000000E+01, 0.00000000E+00) ( 0.00000000E+00, 0.00000000E+00) ( 0.00000000E+00, 0.00000000E+00) ( 0.00000000E+00, 0.00000000E+00)
 -------------INFO--------------
           0
 -------------error-------------
    ( 0.00000000E+00, 0.00000000E+00) ( 0.00000000E+00, 0.00000000E+00) ( 0.00000000E+00,-0.13898160E-11) ( 0.00000000E+00,-0.13898160E-11)

The error is quite large compare to some element of B.
In contrary, I tried to solve this in Mathematica, and the error is quite small.
A.LinearSolve[A, B] - B

{0. + 0. I, 0. + 3.67342*10^-40 I, 4.13609*10^-34 + 0. I, 4.13609*10^-34 + 0. I}

So how can I control the precision of the Lapack solver to achieve the same precision of Mathematica's LinearSolver?

A: ZHESV computes the solution to a complex system of linear equations A * X = B, where A is an N-by-N Hermitian matrix and X and B are N-by-NRHS matrices.
But, your matrix A is not a Hermitian matrix.

A: Recall that, after the subroutine ZHESV call, X is no longer the initial value (define initially by B) but the solution to A*X=B. When you compute your error there, you are actually computing matmul(A, solution) - initial when you really want matmul(A, initial) - solution. Fixing this (i.e., swapping X and B in that line), I get
 -------------error-------------
(    0.00000E+00,    0.00000E+00)(    0.62805E-22,    0.00000E+00)(    0.00000E+00,    0.00000E+00)(    0.00000E+00,    0.00000E+00)

Pretty good error, if you ask me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: FIFO closing price with multiple products and people I have found the following solution to a problem I was trying to solve:
https://stackoverflow.com/a/26778468/1626443
I want to have a single query that returns me the FIFO price closing price per investor and isin.
The current query works, but I have to filter by the isin and investor (the top is the sample data):
CREATE TABLE #CustomerOrderTable (
    ID INTEGER NOT NULL,
    [investor] VARCHAR(255) NOT NULL,
    [isin] VARCHAR(255) NOT NULL,
    [datetime] DATETIME NOT NULL,
    [quantity] FLOAT NOT NULL,
    [price] FLOAT NOT NULL,
    [buysell] VARCHAR(255) NOT NULL,
    PRIMARY KEY (ID)
);
GO

INSERT INTO #CustomerOrderTable(ID, [investor],[isin],[datetime],[quantity],[price],[buysell]) VALUES (1,'GN0161162','DE6592028664','20180913',7,88,'Buy'),(2,'GN0969461','DE6592028664','20180924',4,452,'Buy'),(3,'GN0969461','DE7478496562','20180929',9,721,'Buy'),(4,'GN0429760','CH1486126118','20180929',9,451,'Buy'),(5,'GN0429760','GB9015779955','20181006',9,817,'Buy'),(6,'GN0969461','DE7478496562','20181013',8,433,'Buy'),(7,'GN0969461','GB9015779955','20181025',10,262,'Buy'),(8,'GN0161162','DE7478496562','20181108',7,278,'Buy'),(9,'GN0429760','GB9015779955','20181109',3,986,'Buy'),(10,'GN0161162','DE6592028664','20181114',1,556,'Buy'),(11,'GN0429760','DE7478496562','20181120',4,434,'Buy'),(12,'GN0429760','GB9015779955','20181121',3,764,'Buy'),(13,'GN0369359','GB9015779955','20181123',7,129,'Buy'),(14,'GN0429760','DE7478496562','20181205',2,686,'Buy'),(15,'GN0969461','DE6592028664','20181231',5,309,'Buy'),(16,'GN0161162','DE9805831979','20190108',3,540,'Buy'),(17,'GN0429760','CH1486126118','20190128',4,940,'Buy'),(18,'GN0429760','CH1486126118','20190131',10,652,'Buy'),(19,'GN0969461','DE7478496562','20190210',8,845,'Buy'),(20,'GN0969461','DE6592028664','20190213',2,981,'Buy'),(21,'GN0969461','DE9805831979','20190214',9,90,'Buy'),(22,'GN0369359','DE6592028664','20190227',7,518,'Buy'),(23,'GN0161162','GB9015779955','20190227',7,930,'Buy'),(24,'GN0429760','GB9015779955','20190312',8,301,'Buy'),(25,'GN0161162','GB9015779955','20190315',5,994,'Sell'),(26,'GN0969461','CH1486126118','20190329',8,928,'Buy'),(27,'GN0161162','DE7478496562','20190330',7,354,'Buy'),(28,'GN0369359','DE7478496562','20190423',1,928,'Buy'),(29,'GN0429760','DE6592028664','20190426',7,599,'Buy'),(30,'GN0161162','DE9805831979','20190428',5,283,'Buy'),(31,'GN0429760','DE9805831979','20190509',7,928,'Buy'),(32,'GN0429760','DE9805831979','20190510',9,954,'Buy'),(33,'GN0429760','CH1486126118','20190518',6,112,'Buy'),(34,'GN0369359','DE9805831979','20190520',8,304,'Buy'),(35,'GN0969461','DE6592028664','20190522',5,657,'Buy'),(36,'GN0161162','DE7478496562','20190526',5,127,'Buy'),(37,'GN0969461','CH1486126118','20190616',10,760,'Buy'),(38,'GN0429760','DE9805831979','20190618',10,659,'Buy'),(39,'GN0369359','DE7478496562','20190620',5,61,'Buy'),(40,'GN0369359','CH1486126118','20190704',5,50,'Buy'),(41,'GN0429760','DE9805831979','20190710',9,375,'Buy'),(42,'GN0969461','DE9805831979','20190722',5,999,'Buy'),(43,'GN0969461','DE6592028664','20190723',8,860,'Buy'),(44,'GN0161162','DE9805831979','20190723',8,80,'Buy'),(45,'GN0161162','GB9015779955','20190805',2,318,'Sell'),(46,'GN0429760','DE6592028664','20190809',6,505,'Buy'),(47,'GN0161162','GB9015779955','20190831',10,127,'Buy'),(48,'GN0429760','DE6592028664','20190831',7,9,'Buy'),(49,'GN0369359','CH1486126118','20190903',6,903,'Buy'),(50,'GN0429760','GB9015779955','20190913',6,430,'Buy'),(51,'GN0161162','DE6592028664','20190914',7,777,'Sell'),(52,'GN0429760','DE9805831979','20190915',5,372,'Buy'),(53,'GN0969461','DE6592028664','20190918',1,598,'Buy'),(54,'GN0429760','CH1486126118','20191018',2,894,'Buy'),(55,'GN0161162','CH1486126118','20191021',4,235,'Buy'),(56,'GN0969461','CH1486126118','20191031',1,427,'Buy'),(57,'GN0161162','DE9805831979','20191119',6,412,'Buy'),(58,'GN0969461','DE6592028664','20191205',2,769,'Sell'),(59,'GN0369359','DE9805831979','20191214',8,418,'Sell'),(60,'GN0429760','DE6592028664','20191219',6,420,'Buy'),(61,'GN0429760','DE7478496562','20191223',6,285,'Buy'),(62,'GN0429760','CH1486126118','20200101',5,106,'Buy'),(63,'GN0161162','GB9015779955','20200108',7,528,'Buy'),(64,'GN0429760','CH1486126118','20200116',7,531,'Buy'),(65,'GN0969461','DE6592028664','20200126',1,632,'Sell'),(66,'GN0429760','GB9015779955','20200129',6,21,'Buy'),(67,'GN0369359','GB9015779955','20200131',5,130,'Sell'),(68,'GN0161162','DE7478496562','20200212',10,222,'Sell'),(69,'GN0161162','CH1486126118','20200216',2,686,'Sell'),(70,'GN0969461','CH1486126118','20200219',10,546,'Buy'),(71,'GN0161162','CH1486126118','20200225',2,601,'Sell'),(72,'GN0369359','GB9015779955','20200305',4,722,'Buy'),(73,'GN0429760','CH1486126118','20200311',10,543,'Buy'),(74,'GN0369359','DE6592028664','20200314',4,145,'Buy'),(75,'GN0429760','DE6592028664','20200323',8,919,'Buy'),(76,'GN0429760','DE9805831979','20200401',1,4,'Buy'),(77,'GN0161162','CH1486126118','20200401',9,320,'Buy'),(78,'GN0429760','DE7478496562','20200406',2,46,'Buy'),(79,'GN0429760','CH1486126118','20200421',5,453,'Buy'),(80,'GN0969461','CH1486126118','20200425',8,150,'Buy'),(81,'GN0429760','DE7478496562','20200501',10,426,'Buy'),(82,'GN0369359','GB9015779955','20200511',4,514,'Buy'),(83,'GN0161162','DE6592028664','20200511',8,467,'Buy'),(84,'GN0969461','DE9805831979','20200518',1,517,'Buy'),(85,'GN0369359','DE6592028664','20200520',6,744,'Buy'),(86,'GN0161162','DE7478496562','20200602',7,567,'Sell'),(87,'GN0969461','CH1486126118','20200604',7,973,'Buy'),(88,'GN0369359','DE6592028664','20200605',2,39,'Sell'),(89,'GN0369359','GB9015779955','20200627',1,770,'Buy'),(90,'GN0369359','DE9805831979','20200709',3,918,'Buy'),(91,'GN0969461','CH1486126118','20200714',7,527,'Buy'),(92,'GN0161162','DE9805831979','20200725',9,281,'Buy'),(93,'GN0161162','GB9015779955','20200729',8,205,'Buy'),(94,'GN0969461','DE9805831979','20200730',5,682,'Buy'),(95,'GN0369359','GB9015779955','20200813',1,833,'Buy'),(96,'GN0161162','DE9805831979','20200816',9,914,'Sell'),(97,'GN0429760','DE7478496562','20200816',6,247,'Buy'),(98,'GN0969461','DE7478496562','20200828',8,822,'Buy'),(99,'GN0161162','DE6592028664','20200830',2,937,'Buy'),(100,'GN0161162','GB9015779955','20200905',5,858,'Buy');

DECLARE @isin nvarchar(12);
DECLARE @subaccount nvarchar(20);
SET @isin = 'GB9015779955';
SET @subaccount = 'GN0161162';

WITH UnitsCTE
AS
(
-- GET Total Units Left
    SELECT SUM(
            CASE buysell
            WHEN 'Buy' Then quantity
            When 'Sell' THEN -quantity
            ELSE quantity END) AS Units
    FROM #CustomerOrderTable
    WHERE investor = @subaccount AND isin = @isin
), PurchaseCTE
AS
(
-- Get only purchases in reverse order
    SELECT quantity, price, datetime, ROW_NUMBER() OVER (ORDER BY datetime DESC ) AS RN
    FROM #CustomerOrderTable
    WHERE buysell <> 'Sale' AND investor = @subaccount AND isin = @isin
),
UnitCost
AS
(
-- Recursive CTE to get number of units left at each price
    SELECT CASE WHEN quantity > unitsCTE.Units THEN unitsCTE.Units ELSE quantity END As quantity, price
    FROM PurchaseCTE
    CROSS APPLY unitsCTE
    WHERE RN = 1
    UNION ALL
    SELECT CASE WHEN P1.quantity > (unitsCTE.Units - (SELECT SUM(quantity) FROM PurchaseCTE P3 WHERE p3.RN < p1.RN))
            THEN    CASE WHEN (unitsCTE.Units - (SELECT SUM(quantity) FROM PurchaseCTE P3 WHERE p3.RN < p1.RN)) < 0 THEN 0
                        ELSE (unitsCTE.Units - (SELECT SUM(quantity) FROM PurchaseCTE P3 WHERE p3.RN < p1.RN)) END
            ELSE P1.quantity END,
            P1.price
    FROM PurchaseCTE P1
    INNER JOIN PurchaseCTE P2
        ON P1.RN = P2.RN + 1
    CROSS APPLY unitsCTE
)
SELECT SUM(quantity) Units, SUM(price * quantity) / SUM(quantity) AS UnitCost, SUM(quantity * price) AS TotalCost
FROM UnitCost
WHERE quantity > 0

DROP TABLE #CustomerOrderTable

The current output from the query above is:
+-------+----------+-----------+
| Units | UnitCost | TotalCost |
+-------+----------+-----------+
|    30 | 363.2    |     10896 |
+-------+----------+-----------+

I would want the following output:
+-----------+--------------+-------+-------------+-----------+
| investor  |     ISIN     | Units |  UnitCost   | TotalCost |
+-----------+--------------+-------+-------------+-----------+
| GN0161162 | DE6592028664 |    11 | 580.6363636 |      6387 |
| GN0161162 | DE7478496562 |     2 | 567         |      1134 |
| GN0161162 | DE9805831979 |    22 | 563.7727273 |     12403 |
| GN0161162 | GB9015779955 |    30 | 363.2       |     10896 |
| GN0161162 | CH1486126118 |     9 | 320         |      2880 |
| GN0369359 | GB9015779955 |    12 | 567.25      |      6807 |
| GN0369359 | DE6592028664 |    15 | 445.0666667 |      6676 |
| GN0369359 | DE7478496562 |     6 | 205.5       |      1233 |
| GN0369359 | DE9805831979 |     3 | 918         |      2754 |
| GN0369359 | CH1486126118 |    11 | 515.2727273 |      5668 |
| GN0429760 | CH1486126118 |    58 | 495.5344828 |     28741 |
| GN0429760 | GB9015779955 |    35 | 506.2       |     17717 |
| GN0429760 | DE7478496562 |    30 | 355.0666667 |     10652 |
| GN0429760 | DE6592028664 |    34 | 504.6470588 |     17158 |
| GN0429760 | DE9805831979 |    41 | 656.3658537 |     26911 |
| GN0969461 | DE6592028664 |    22 | 719.1818182 |     15822 |
| GN0969461 | DE7478496562 |    33 | 705.7272727 |     23289 |
| GN0969461 | GB9015779955 |    10 | 262         |      2620 |
| GN0969461 | DE9805831979 |    20 | 486.6       |      9732 |
| GN0969461 | CH1486126118 |    51 | 639.4313725 |     32611 |
+-----------+--------------+-------+-------------+-----------+

A: I will answer my own question, because I have made it work. I hope it will help people in the future:
CREATE TABLE #CustomerOrderTable (
    ID INTEGER NOT NULL,
    [investor] VARCHAR(255) NOT NULL,
    [isin] VARCHAR(255) NOT NULL,
    [datetime] DATETIME NOT NULL,
    [quantity] FLOAT NOT NULL,
    [price] FLOAT NOT NULL,
    [buysell] VARCHAR(255) NOT NULL,
    PRIMARY KEY (ID)
);
GO

INSERT INTO #CustomerOrderTable(ID, [investor],[isin],[datetime],[quantity],[price],[buysell]) VALUES (1,'GN0161162','DE6592028664','20180913',7,88,'Buy'),(2,'GN0969461','DE6592028664','20180924',4,452,'Buy'),(3,'GN0969461','DE7478496562','20180929',9,721,'Buy'),(4,'GN0429760','CH1486126118','20180929',9,451,'Buy'),(5,'GN0429760','GB9015779955','20181006',9,817,'Buy'),(6,'GN0969461','DE7478496562','20181013',8,433,'Buy'),(7,'GN0969461','GB9015779955','20181025',10,262,'Buy'),(8,'GN0161162','DE7478496562','20181108',7,278,'Buy'),(9,'GN0429760','GB9015779955','20181109',3,986,'Buy'),(10,'GN0161162','DE6592028664','20181114',1,556,'Buy'),(11,'GN0429760','DE7478496562','20181120',4,434,'Buy'),(12,'GN0429760','GB9015779955','20181121',3,764,'Buy'),(13,'GN0369359','GB9015779955','20181123',7,129,'Buy'),(14,'GN0429760','DE7478496562','20181205',2,686,'Buy'),(15,'GN0969461','DE6592028664','20181231',5,309,'Buy'),(16,'GN0161162','DE9805831979','20190108',3,540,'Buy'),(17,'GN0429760','CH1486126118','20190128',4,940,'Buy'),(18,'GN0429760','CH1486126118','20190131',10,652,'Buy'),(19,'GN0969461','DE7478496562','20190210',8,845,'Buy'),(20,'GN0969461','DE6592028664','20190213',2,981,'Buy'),(21,'GN0969461','DE9805831979','20190214',9,90,'Buy'),(22,'GN0369359','DE6592028664','20190227',7,518,'Buy'),(23,'GN0161162','GB9015779955','20190227',7,930,'Buy'),(24,'GN0429760','GB9015779955','20190312',8,301,'Buy'),(25,'GN0161162','GB9015779955','20190315',5,994,'Sell'),(26,'GN0969461','CH1486126118','20190329',8,928,'Buy'),(27,'GN0161162','DE7478496562','20190330',7,354,'Buy'),(28,'GN0369359','DE7478496562','20190423',1,928,'Buy'),(29,'GN0429760','DE6592028664','20190426',7,599,'Buy'),(30,'GN0161162','DE9805831979','20190428',5,283,'Buy'),(31,'GN0429760','DE9805831979','20190509',7,928,'Buy'),(32,'GN0429760','DE9805831979','20190510',9,954,'Buy'),(33,'GN0429760','CH1486126118','20190518',6,112,'Buy'),(34,'GN0369359','DE9805831979','20190520',8,304,'Buy'),(35,'GN0969461','DE6592028664','20190522',5,657,'Buy'),(36,'GN0161162','DE7478496562','20190526',5,127,'Buy'),(37,'GN0969461','CH1486126118','20190616',10,760,'Buy'),(38,'GN0429760','DE9805831979','20190618',10,659,'Buy'),(39,'GN0369359','DE7478496562','20190620',5,61,'Buy'),(40,'GN0369359','CH1486126118','20190704',5,50,'Buy'),(41,'GN0429760','DE9805831979','20190710',9,375,'Buy'),(42,'GN0969461','DE9805831979','20190722',5,999,'Buy'),(43,'GN0969461','DE6592028664','20190723',8,860,'Buy'),(44,'GN0161162','DE9805831979','20190723',8,80,'Buy'),(45,'GN0161162','GB9015779955','20190805',2,318,'Sell'),(46,'GN0429760','DE6592028664','20190809',6,505,'Buy'),(47,'GN0161162','GB9015779955','20190831',10,127,'Buy'),(48,'GN0429760','DE6592028664','20190831',7,9,'Buy'),(49,'GN0369359','CH1486126118','20190903',6,903,'Buy'),(50,'GN0429760','GB9015779955','20190913',6,430,'Buy'),(51,'GN0161162','DE6592028664','20190914',7,777,'Sell'),(52,'GN0429760','DE9805831979','20190915',5,372,'Buy'),(53,'GN0969461','DE6592028664','20190918',1,598,'Buy'),(54,'GN0429760','CH1486126118','20191018',2,894,'Buy'),(55,'GN0161162','CH1486126118','20191021',4,235,'Buy'),(56,'GN0969461','CH1486126118','20191031',1,427,'Buy'),(57,'GN0161162','DE9805831979','20191119',6,412,'Buy'),(58,'GN0969461','DE6592028664','20191205',2,769,'Sell'),(59,'GN0369359','DE9805831979','20191214',8,418,'Sell'),(60,'GN0429760','DE6592028664','20191219',6,420,'Buy'),(61,'GN0429760','DE7478496562','20191223',6,285,'Buy'),(62,'GN0429760','CH1486126118','20200101',5,106,'Buy'),(63,'GN0161162','GB9015779955','20200108',7,528,'Buy'),(64,'GN0429760','CH1486126118','20200116',7,531,'Buy'),(65,'GN0969461','DE6592028664','20200126',1,632,'Sell'),(66,'GN0429760','GB9015779955','20200129',6,21,'Buy'),(67,'GN0369359','GB9015779955','20200131',5,130,'Sell'),(68,'GN0161162','DE7478496562','20200212',10,222,'Sell'),(69,'GN0161162','CH1486126118','20200216',2,686,'Sell'),(70,'GN0969461','CH1486126118','20200219',10,546,'Buy'),(71,'GN0161162','CH1486126118','20200225',2,601,'Sell'),(72,'GN0369359','GB9015779955','20200305',4,722,'Buy'),(73,'GN0429760','CH1486126118','20200311',10,543,'Buy'),(74,'GN0369359','DE6592028664','20200314',4,145,'Buy'),(75,'GN0429760','DE6592028664','20200323',8,919,'Buy'),(76,'GN0429760','DE9805831979','20200401',1,4,'Buy'),(77,'GN0161162','CH1486126118','20200401',9,320,'Buy'),(78,'GN0429760','DE7478496562','20200406',2,46,'Buy'),(79,'GN0429760','CH1486126118','20200421',5,453,'Buy'),(80,'GN0969461','CH1486126118','20200425',8,150,'Buy'),(81,'GN0429760','DE7478496562','20200501',10,426,'Buy'),(82,'GN0369359','GB9015779955','20200511',4,514,'Buy'),(83,'GN0161162','DE6592028664','20200511',8,467,'Buy'),(84,'GN0969461','DE9805831979','20200518',1,517,'Buy'),(85,'GN0369359','DE6592028664','20200520',6,744,'Buy'),(86,'GN0161162','DE7478496562','20200602',7,567,'Sell'),(87,'GN0969461','CH1486126118','20200604',7,973,'Buy'),(88,'GN0369359','DE6592028664','20200605',2,39,'Sell'),(89,'GN0369359','GB9015779955','20200627',1,770,'Buy'),(90,'GN0369359','DE9805831979','20200709',3,918,'Buy'),(91,'GN0969461','CH1486126118','20200714',7,527,'Buy'),(92,'GN0161162','DE9805831979','20200725',9,281,'Buy'),(93,'GN0161162','GB9015779955','20200729',8,205,'Buy'),(94,'GN0969461','DE9805831979','20200730',5,682,'Buy'),(95,'GN0369359','GB9015779955','20200813',1,833,'Buy'),(96,'GN0161162','DE9805831979','20200816',9,914,'Sell'),(97,'GN0429760','DE7478496562','20200816',6,247,'Buy'),(98,'GN0969461','DE7478496562','20200828',8,822,'Buy'),(99,'GN0161162','DE6592028664','20200830',2,937,'Buy'),(100,'GN0161162','GB9015779955','20200905',5,858,'Buy');

;WITH UnitsCTE
AS
(
-- GET Total Units Left
    SELECT investor, isin, SUM(
            CASE buysell
            WHEN 'Buy' Then quantity
            When 'Sell' THEN -quantity
            ELSE quantity END) AS Units
    FROM #CustomerOrderTable
    GROUP BY investor, isin
), PurchaseCTE
AS
(
-- Get only purchases in reverse order
    SELECT quantity, price, investor, isin, datetime, ROW_NUMBER() OVER (PARTITION BY investor, isin ORDER BY datetime DESC ) AS RN
    FROM #CustomerOrderTable
    WHERE buysell <> 'Sale'
),
UnitCost
AS
(
-- Recursive CTE to get number of units left at each price
    SELECT CASE WHEN quantity > unitsCTE.Units THEN unitsCTE.Units ELSE quantity END As quantity, price, unitsCTE.investor, unitsCTE.isin
    FROM PurchaseCTE
    CROSS APPLY unitsCTE
    WHERE RN = 1
    AND unitsCTE.investor = PurchaseCTE.investor AND unitsCTE.isin = PurchaseCTE.isin
    UNION ALL
    SELECT CASE WHEN P1.quantity > (unitsCTE.Units - (SELECT SUM(quantity) FROM PurchaseCTE P3 WHERE p3.RN < p1.RN AND P1.investor = P3.investor AND P1.isin = P3.isin))
            THEN    CASE WHEN (unitsCTE.Units - (SELECT SUM(quantity) FROM PurchaseCTE P3 WHERE p3.RN < p1.RN AND P1.investor = P3.investor AND P1.isin = P3.isin)) < 0 THEN 0
                        ELSE (unitsCTE.Units - (SELECT SUM(quantity) FROM PurchaseCTE P3 WHERE p3.RN < p1.RN AND P1.investor = P3.investor AND P1.isin = P3.isin)) END
            ELSE P1.quantity END,
            P1.price, P1.investor, P1.isin
    FROM PurchaseCTE P1
    INNER JOIN PurchaseCTE P2
        ON P1.RN = P2.RN + 1 AND P1.investor = P2.investor AND P1.isin = P2.isin
    CROSS APPLY unitsCTE
    WHERE P1.investor = unitsCTE.investor AND P1.isin = unitsCTE.isin
)

SELECT investor, isin, SUM(quantity) Units, SUM(price * quantity) / SUM(quantity) AS UnitCost, SUM(quantity * price) AS TotalCost
FROM UnitCost
WHERE quantity > 0
GROUP BY investor, isin

DROP TABLE #CustomerOrderTable


text:
Q: What is powerful way to force a form to bring front? What is powerful way to force a form to bring front of all the other applications using windows c# application?

A: Set Form.TopMost to true

A: Here is the code that worked for me:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace LicenseManager {

  public static class WinApi {

    [DllImport( "user32.dll" )]
    static extern bool SetWindowPos( IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags );

    static private IntPtr HWND_TOPMOST = new IntPtr( -1 );

    private const uint SWP_NOSIZE = 0x0001;
    private const uint SWP_NOMOVE = 0x0002;

    static public void MakeTopMost( Form f ) {
      SetWindowPos( f.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE );
    }

  }
}

A: this.BringToFront();
It works good for me.

A: Powerfully force the user to click on your application window icon in the task-bar.

A: Use SetWindowsPos() api function

A: Some more information about this that may be useful. I used Charles Jenkins' answer to make my winforms app become topmost by calling the "MakeTopMost" function in the form.load event handler. I needed this function as my winforms app was launched by an MSI install and the Windows installer progress bar would show on top.
However, this then put the main form on top of other sub-forms that the main form wanted to show. To get around this I called my function MakeWindowNormal in the form.shown event handler to put the main form back as a normal window as it was now in front of the Windows installer progress bar as it had been loaded and activated (see http://msdn.microsoft.com/en-us/library/86faxx0d(v=vs.110).aspx for event order). This allows the sub-forms (and other windows if the user moves them) to now go in front of the main form.
static public void MakeWindowNormal(Form f)
{
    SetWindowPos(f.Handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}


text:
Q: How do I use NSURL in Swift in Xcode 6.1? What am I doing wrong? I am trying to use an api, but first I need to learn to do http stuff in swift.
I am using this code in the playground:
// Playground - noun: a place where people can play

// import Cocoa - this is commented out due to "No such module 'Cocoa'"
import XCPlayground

let url = NSURL(string: "http://stackoverflow.com")
let request = NSURLRequest(URL: url)

var waiting = true

NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.currentQueue() {
    response, maybeData, error in
    waiting = false
    if let data = maybeData {
        let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
        println(contents)
    } else {
        println(error.localizedDescription)
    }
    }

    while(waiting) {
    NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate())
    usleep(10)
}

and getting these errors in the console:
Playground execution failed: <EXPR>:12:11: error: use of unresolved identifier 'NSURL'
let url = NSURL(string: "http://www.stackoverflow.com")
          ^
<EXPR>:14:12: error: use of unresolved identifier 'NSURLSession'
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
           ^
<EXPR>:15:13: error: use of unresolved identifier 'NSString'
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
            ^
<EXPR>:15:44: error: use of unresolved identifier 'NSUTF8StringEncoding'
    println(NSString(data: data, encoding: NSUTF8StringEncoding))

A: You need to import Foundation framework to make those types available. So add following import line to your playground:
import Foundation


text:
Q: Trouble with VLOOKUP not finding data Col A has ItemID Col B has Model_Num Col C has a long list of Model_Num. In Col D I want to lookup the Model_Num of Col C and put the ItemID
item_id (colA)        model_num (colB)   to match (colC)  new data (colD)
--------              ----------         ---------        ---------
870834                FD021              KPA8A            14667122
16595156              S3TA03B            BW01B            #N/A
10752514              FD1424B            GM1500B          #N/A
10756167              SU03B              TA021            #N/A
14667130              KDAD               FD021            870834
14667122              KPA8A              FD021            870834

In the new data column (colD) I'm using the formula:
=VLOOKUP(C1,$A$1:$B$114,2,FALSE)

It's returning #N/A for everything though. Any help is appreciated.

A: You have a mistake in your VLOOKUP formula and/or the way your data is organized by column. VLOOKUP can not be used to look up values to the left of the lookup value in the VLOOKUP table - you would have to use an INDEX/MATCH function to do that - or you could just do this.
1) You could cut and insert your column A(item_iD) to the right of your current column B(model_num). Then adjust your VLOOKUP formula appropriately. (So basically your item_id and model_num columns are backwards currently).
If you want to keep your column order "as is" then you will need to use an INDEX/MATCH function which I can certainly provide:
=INDEX($A$1:$B$114,MATCH(C1,$B$1:$B$114,0),1)

Leave your data as is and put that in the top cell column D and then autofill down. It should give you what you want.
Good Luck.


text:
Q: JQuery Ajax loop delay i am trying to make a delay in my ajax data so the loop become a little bit slower !
and here is my code
$(document).ready(function (){
$('#button').click(function(){

 $('#hide').show();
 var data = $('#textarea').val();

 var arrayOfLines = data.split("\n");

 var track = JSON.stringify(arrayOfLines);
 var item = "";

 var lines = $('#textarea').val().split('\n');

here is the loop
 for (var i = 0; i < lines.length; i++) {
     item = lines[i];
            $.ajax({
            type: 'GET',
                url: 'cookie.php',
                dataType: 'html',
                data: 'data=' + item+'&cookie='+track,
                success: function(msg){
                    $('#results').append(msg);

                }

                });
 }

});

A: Using recursion, you could put in a function sendToServer and pass through the array lines, starting index 0. The function will run from 0 to lines.length. This way you won't DDOS your server :)
If you really need some kind of arbitrary delay, you can include a timeout on the sendToServer function call - in the example it is set to 5 seconds.
 var sendToServer = function(lines, index){
   if (index > lines.length) return; // guard condition
   item = lines[index];
   if (item.trim().length != 0){
     $.ajax({
       type: 'GET',
       url: 'cookie.php',
       dataType: 'html',
       data: 'data=' + item+'&cookie='+track,
       success: function(msg){
         $('#results').append(msg);
         setTimeout(
           function () { sendToServer(lines, index+1); },
           5000 // delay in ms
         );
       }
     });
   }
   else { sendToServer(lines, index+1); }
};

sendToServer(lines, 0);

A: Don't send request to server in for loop. It can take down the server. Instead of what you did , you can do this :
for (var i = 0; i < lines.length; i++) {
     item = lines[i];
}

$.ajax({
    type: 'GET',
        url: 'cookie.php',
        dataType: 'html',
        data: 'data=' + item+'&cookie='+track,
        success: function(msg){
            $('#results').append(msg);

        }

     });

A: Use like this:
 var timeDelay = 5000;
    setTimeout(Function, timeDelay);


text:
Q: Can inkjet printers print envelopes? I occasionally need to print about a hundred envelopes (a couple of times per year).
I have a laser printer which bends the envelopes as it prints them, rendering them almost unusable, and an inkjet printer which leaves random blotches of ink around the edges of the envelopes.
The inkjet printer is dying and needs to be replaced.
Are there any inkjet printers that can print bulk envelopes well?
I'd prefer not to get a second laser printer.

A: If the problem with the laser printer is just that it's bending the envelopes, can you just open the back tray of the printer so that it has a straighter paper path?

A: After reading online it looks like most can but only certain ones do it without constantly jamming. Here are some printers others have had good luck printing on envelopes with.
Edit: If you want a real envelope printer try Here.

A: In the past I have had inkjet printers that let me adjust the input tray for envelopes or even had a separate slot to put them in to make sure they were guided properly through the works of the computer.


text:
Q: Errno 13 Permission denied with Django on a directory I don't want to use I have this error appearing in my Django app on my production server :

[Errno 13] Permission denied: '/var/www/.config'

I never asked to access to this unexisting file or directory in my code. The server is running in a different directory defined in my httpd.conf and I haven't defined the use of any /var/www/ elements in my Django settings.
In my case I'm using the biopython library with Django :
from Bio import Entrez

Entrez.email = "my@email"

handle = Entrez.efetch("taxonomy", id="123, 1")
records = Entrez.parse(handle)

This code is working in a python console on the server. But the instruction Entrez.parse(handle) return the error in a Django environment.
I haven't seen any instruction asking to write or open anything in the source code of the function so it seems to be a problem with Django?
Is it a configuration problem? A background Django function trying to access to a file when I call a specific function?
My configuration :

*

*Python 3.3

*Django 1.8

*Biopython 1.67

A: In facts, Entrez.parse is calling the DataHandler objects. This objects try to write in the user directory with something like :
home = os.path.expanduser('~')
directory = os.path.join(home, '.config', 'biopython')
local_xsd_dir = os.path.join(directory, 'Bio', 'Entrez', 'XSDs')
os.makedirs(local_xsd_dir)

Because biopython user is the httpd user, the home directory is /var/www/.
The solution is here to allow apache to write into /var/www or to move it to a different place.

A: Restart the server or restart the service of django.
That is important, because the services in the background have to know the new location of the configuration.

I guess it works on python, because the library is loading the actual settings and the background service is using the old one.
Hope I could help


text:
Q: Boolian check giving incorrect answer I'm trying to make a reputation system:
if($upvotetruedownvotefalse == false){
    if(strpos($lines[2],$username.",") !== false){
        echo "you've already downvoted";
    }
    else{
        echo "you haven't downvoted yet";
        $lines[2] = $username.",".$lines[2];
        $lines[0] = $lines[0]-1 . "\n";
        file_put_contents( $filename , $lines);

    }
}
if($upvotetruedownvotefalse == true){
    if(strpos($lines[1],$username.",") !== false){
        echo "you've already upvoted";
    }else{
        echo "you haven't upvoted yet";
        $lines[1] = $username.",".$lines[1];
        $lines[0] = $lines[0]+1 . "\n";
        file_put_contents( $filename , $lines);
    }

}

The value of  $upvotetruedownvotefalse is determined through AJAX
However these comparison operators is giving me wrong results.
For example if $upvotetruedownvotefalse = false then $upvotetruedownvotefalse == truewould be triggered.
I've tested this by echoing the value of $upvotetruedownvotefalseand recieving the echo results (including the ones in the if statements)using a success function:
echo $upvotetruedownvotefalse;
success: function(response){
          alert(response);
}

Then I console.log the result and I would get this:

Falseyou haven't upvoted yet

I'm getting conflicting results.
I've also tried using different types of === !=== in different places and I get either an inverted result or my success function fails
Is there something that I don't know about Boolean operators?
Any help would be greatly apreciated

A: If you are doing an echo, and getting False in the output, then it sounds like your variable is holding the string "False", and not the boolean value false.  A non-empty string is a "truth-y" value, meaning when you do if ($some_string) it will come back true.
Quickest fix would seem to be to add this before the rest of your code:
if (strtolower($upvotetruedownvotefalse) === 'false') {
    $upvotetruedownvotefalse = false;
}
//the rest of your code here


text:
Q: Compose_Project_Name variable not set warning and network error I am following this Tutorial
Currently I am on Step 2 (there was a few pre-requisite instructions)
Does anyone know why I would be getting the following warning message and error message when trying to install sudo ./startFabric.sh
?

vmadmin@HyperFabricBoilerPlate:~/marbles/fabric-samples/fabcar$
  sudo ./startFabric.sh
don't rewrite paths for Windows Git Bash users export MSYS_NO_PATHCONV=1
docker-compose -f docker-compose.yml down WARNING: The
  COMPOSE_PROJECT_NAME variable is not set. Defaulting to a blank
  string. Removing network basicnetwork_basic ERROR: network
  basicnetwork_basic not found

My Project Environment is Ubuntu 16 running on an AzureVM

A: Please create a file named ".env" in the same directory where your docker-compose file exists. Add the following line in ".env" file:-

COMPOSE_PROJECT_NAME=net

After creation of this file, your issue will be resolved. This is related to docker networking, you may find more explanation on following URL:-
https://docs.docker.com/compose/networking/


text:
Q: Action Recognition using SVM for 3D array I am working on action recognition topic using Matlab.
Each video contains specific number of frames, and each frame contains different coordinates of X,y,z.
After extracting the features, I got an cell array which contains 3D array for each video. Lets be clear with numbers:
I have 40 videos, which give me 40x1 cell array. Each cell contains 128x3xN where N is number of frames.  have corresponding labels array 40x1 double array.
Example of the first 10 videos:
<128x3x54 double>
<128x3x43 double>
<128x3x43 double>
<128x3x55 double>
<128x3x31 double>
<128x3x45 double>
<128x3x45 double>
<128x3x33 double>
<128x3x38 double>
<128x3x38 double>

I want to classify these videos using libSVM, how I can change the dimensions to 2D array and preserve the meaning of features ? And having similar aray dimensions for each video ?

A: for example
10 action * 40 videos for each * (128x3xN) features = input for SVM for training which create 400 rows with (128x3xN) features and need 400 labels for training
for the testing you have 1 action * 1 video * (128x3xN) features in order to predict the action from trained SVM


text:
Q: Decaffeinated: Double Brackets I decaffeinated an old project recently and I noticed that I got a lot of if clauses where the expressions are wrapped in "extra" brackets:
if ((data == null) || (data === ""))

Is there any case where the wrapping is required? Imho it is the same as:
if (data == null || data === "")

A: With an explicit check, you could omit the parentheses around the comparisons, because of the lower operator precedence of ==/=== over logical OR ||.
if (data == null || data === "")

A: In that case it wouldn't matter, but whenever you remove parentheses from an if statement (or anywhere pretty much) make sure you check the precedence table.
For example, removing the parentheses from this:
if ((someVar && someConditional) == someBool)

Would result in:
if (someVar && someConditional == someBool)

Which is completely different. The first example, due to the parentheses, will evaluate someVar && someConditional first, then resultOfOperation == someBool. In the second example, due to the higher precedence of &&, someConditional == someBool is evaluated first, then 0 && resultOfOperation.


text:
Q: How can I save multiple messages and save it in separate fields in firestore? This is the firestore document of a certain user:

This is how I'll save messages to be saved in firestore:
  const [msg, setMsg] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    try {
      const userRef = firestore.collection("users").doc(uid);
      const ref = userRef.set(
        {
          msg,
        },
        { merge: true }
      );
      console.log(" saved");
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <div>
        <form onSubmit={handleSubmit}>
          <TextField
            value={msg}
            onChange={(e) => setMsg(e.target.value)}
          />
          <Button type="submit">
            Submit
          </Button>
        </form>
    </div>
  );
};

In this way, I can save the message in the firestore, however, if I'll send another one, it will replace the previous message saved in it. How can I save a message in firestore and save another message without it affecting the previous message?

A: I understand that you are overriding the same document in the users collection. This is probably (we don't see the entire code) because you don't change the value of uid between the two writes. uid being the Document ID, it is overwritten (even if you use the { merge: true } option, if the msg object contains existing fields, they are overwritten).
You mention that you save messages, so I guess you want to save several messages for a given user (this user being identified by uid). So you could have a subcollection under the user's document and let Firestore generates a new Document ID each time you add a document to this collection, by using the add() method.
Something along the following lines:
const messagesCollection = firestore.collection("users").doc(uid).collection('messages');

const messagePayload = {foo: 'bar', bar: 'foo'};
messagesCollection.add({messagePayload});


text:
Q: python pandas: why map is faster? in pandas' manual, there is this example about indexing:
In [653]: criterion = df2['a'].map(lambda x: x.startswith('t'))
In [654]: df2[criterion]

then Wes wrote:
**# equivalent but slower**
In [655]: df2[[x.startswith('t') for x in df2['a']]]

can anyone here explain a bit why the map approach is faster? Is this a python feature or this is a pandas feature?

A: Arguments about why a certain way of doing things in Python "should be" faster can't be taken too seriously, because you're often measuring implementation details which may behave differently in certain situations.  As a result, when people guess what should be faster, they're often (usually?) wrong.  For example, I find that map can actually be slower.  Using this setup code:
import numpy as np, pandas as pd
import random, string

def make_test(num, width):
    s = [''.join(random.sample(string.ascii_lowercase, width)) for i in range(num)]
    df = pd.DataFrame({"a": s})
    return df

Let's compare the time they take to make the indexing object -- whether a Series or a list -- and the resulting time it takes to use that object to index into the DataFrame.  It could be, for example, that making a list is fast but before using it as an index it needs to be internally converted to a Series or an ndarray or something and so there's extra time added there.
First, for a small frame:
>>> df = make_test(10, 10)
>>> %timeit df['a'].map(lambda x: x.startswith('t'))
10000 loops, best of 3: 85.8 µs per loop
>>> %timeit [x.startswith('t') for x in df['a']]
100000 loops, best of 3: 15.6 µs per loop
>>> %timeit df['a'].str.startswith("t")
10000 loops, best of 3: 118 µs per loop
>>> %timeit df[df['a'].map(lambda x: x.startswith('t'))]
1000 loops, best of 3: 304 µs per loop
>>> %timeit df[[x.startswith('t') for x in df['a']]]
10000 loops, best of 3: 194 µs per loop
>>> %timeit df[df['a'].str.startswith("t")]
1000 loops, best of 3: 348 µs per loop

and in this case the listcomp is fastest. That doesn't actually surprise me too much, to be honest, because going via a lambda is likely to be slower than using str.startswith directly, but it's really hard to guess.  10 is small enough we're probably still measuring things like setup costs for Series; what happens in a larger frame?
>>> df = make_test(10**5, 10)
>>> %timeit df['a'].map(lambda x: x.startswith('t'))
10 loops, best of 3: 46.6 ms per loop
>>> %timeit [x.startswith('t') for x in df['a']]
10 loops, best of 3: 27.8 ms per loop
>>> %timeit df['a'].str.startswith("t")
10 loops, best of 3: 48.5 ms per loop
>>> %timeit df[df['a'].map(lambda x: x.startswith('t'))]
10 loops, best of 3: 47.1 ms per loop
>>> %timeit df[[x.startswith('t') for x in df['a']]]
10 loops, best of 3: 52.8 ms per loop
>>> %timeit df[df['a'].str.startswith("t")]
10 loops, best of 3: 49.6 ms per loop

And now it seems like the map is winning when used as an index, although the difference is marginal.  But not so fast: what if we manually turn the listcomp into an array or a Series?
>>> %timeit df[np.array([x.startswith('t') for x in df['a']])]
10 loops, best of 3: 40.7 ms per loop
>>> %timeit df[pd.Series([x.startswith('t') for x in df['a']])]
10 loops, best of 3: 37.5 ms per loop

and now the listcomp wins again!
Conclusion: who knows?  But never believe anything without timeit results, and even then you have to ask whether you're testing what you think you are.


text:
Q: Wrong reasoning for existence solution linear system Let us consider the matrix
$$
A =
\begin{pmatrix}
&-1 &1 &-1 \\
&-1 &1 &1 \\
&-2 &2 &0
\end{pmatrix}.
$$
Let us call $\mathbf c_i\in\mathbb R^3$, $i=1,2,3$, it columns. It holds $\det(A)=0$, entailing there exist $\lambda_1,\lambda_2,\lambda_3\in\mathbb R\setminus\{0\}$ such that $\sum_{i=1}^3 \lambda_i \mathbf c_i=\mathbf 0\in\mathbb R^3$. In particular, we have
$$
\mathbf c_3 = -\frac{\lambda_1}{\lambda_3}\mathbf c_1 -\frac{\lambda_1}{\lambda_2}\mathbf c_2,
$$
implying the existence of a solution $\mathbf x\in\mathbf R^2$ to the linear system
$$
\begin{pmatrix}
\mathbf c_1| \mathbf c_2
\end{pmatrix}
\mathbf x = \mathbf c_3.
$$
Where is the mistake?

A: Are you sure that $\lambda_i\neq0$?
Even when vectors $v_1,v_2,v_3$ are linearly dependent, meaning that $\exists c_1,c_2,c_3$, not all $0$, such that $c_1\lambda_1+c_2\lambda_2+c_3\lambda_3=0$, there is a possibility that $c_i=0$ for some $i=1,2,3$.


text:
Q: webrtc: mediaDevices.enumerateDevices() returns empty deviceId I'm currently exploring webRTC and what I want to do is to get all the mediadevices info along with deviceId using navigator.mediaDevices.enumerateDevices(); and then separate it out according to its kind attribute and allow user to choose which media device to use for specific kind. Like Show a dropdown of cameras found and allow user to choose which camera to use which is why i need deviceId of each device.
This is code I'm currently using to get mediadevices:
 const getConnectedDevices = async (type, callback) => {
  const mediaDevices = await navigator.mediaDevices.enumerateDevices();
  console.log(mediaDevices);
  callback(mediaDevices.filter((device) => device.kind === type));
};

And this is what I got back as output:
[
    {
      deviceId: ""
      groupId: "51081772b5c5df2dbcb2ca2b8ae36c5d693d816f8d4bf4039cdb15802b7ffc54"
      kind: "audioinput"
      label: ""
    },
    {
      deviceId: ""
      groupId: "2e7a46f912e66fea3b6af4822e427c02a7725c39d86194dccdf5b7993293d7da"
      kind: "videoinput"
      label: ""
    },
    {
     deviceId: ""
     groupId: "51081772b5c5df2dbcb2ca2b8ae36c5d693d816f8d4bf4039cdb15802b7ffc54"
     kind: "audiooutput"
     label: ""
    }
]

getting a empty deviceId all the time.
I also tried calling await navigator.mediaDevices.getUserMedia( {video: true,audio: true,}) before await navigator.mediaDevices.enumerateDevices() but still got same result.

A: It returns empty deviceIds now ahead of getUserMedia because tracking libraries were (and still are) calling enumerateDevices en masse to fingerprint people, with no intention of ever asking for camera or microphone.
The spec was reviewed by the Privacy Interest Group (PING), and, as a result, this enumerate first strategy (enumerating devices before asking the user for their camera or microphone) was deprecated, to improve user privacy. This is true even in browsers that opt users into persistent permission. (caveat: this last part got backed out in Chrome, so please go ★ crbug 1101860!)
All the big WebRTC sites already use a device first strategy instead (asking for camera or microphone first, then implementing device switching under ⚙ options while live). So web compat of this breaking change was deemed acceptable.
In other words, ahead of getUserMedia resolving, you can only learn whether the user has no camera or no microphone. Those are the only two fingerprinting bits that remain (you won't see multiple devices listed).

I also tried calling [getUserMedia] before, ... but still got same result.

Then you did something wrong,  because both labels and deviceIds are available then, to make device switching still work. See WebRTC Samples for a demo. You can even still store those deviceIds and use them with getUserMedia on future visits, that part still works. You just can't enumerate them (track their presence) before asking for them with the deviceId constraint.
The operating assumption is that the most popular tracking libraries operate in the shadows, and won't risk ever actually prompting the user for their camera or microphone on behalf of their client sites.


text:
Q: failed to open stream wp-settings.php on line 21 fatal error Warning: require(/home/*******/public_html/wp-includes/load.php): failed to open stream: No such file or directory in /home/******/public_html/wp-settings.php on line 21
Fatal error: require(): Failed opening required '/home/****/public_html/wp-includes/load.php' (include_path='.:/opt/alt/php55/usr/share/pear:/opt/alt/php55/usr/share/php') in /home/******/public_html/wp-settings.php on line 21
Can't see anything of my site and can't login to wordpress panel
but i can access cpanel
last thing i was do edit RTL.css and i undo my edits

A: Try uploading "load.php" in binary transfer mode.
It could be also a permission problem:

*

*All directories should be 755 or 750.

*All files should be 644 or 640. Exception: wp-config.php
should be 440 or 400 to prevent other users on the server from
reading it.


text:
Q: Post-Initialization in extbase domain model In one of my extbase models, I want to initialize some properties derived from the properties that are saved in the database. The computation of these virtual properties is time consuming, so I'd like to cache them. Thus my program flow should look somehow like this:

*

*Load the domain object as usual from the database

*Check if the virtual property is available in cache. If so, fetch it from there, otherwise compute and cache it.

I first thought the method "initializeObject" is what I need, but it is not: It is called before any property is initialized from the database. So I came up with two other ways:

*

*I can call an initialization-method manually from the repository after fetching the object, but that seems weird and would break if someone adds another find* method to the general repository.

*Another idea is to add a boolean "virtualPropertiesInitialized" to the model, query it whenever one of the virtual properties is accessed and initialize the virtual properties if needed. Also seems weird, but would not break if someone adds another "find"-method to the generic repository.

My question is:
Is there a default/best-practice how to do what I want to do?

A: If reading the final value from disk or database is less computationally intensive, then store the value using the TYPO3 caching framework or by your own caching method of a static class and restore it in the getter of the virtual property. Doing it in the getter method public mixed getYourPropery() will give you the feature that the value is only get from the cache when you call it.
On the second call, just return the value you stored previously:
private $myValue = NULL;

public function getMyValue() {
    if($this->myValue != NULL) return $this->myValue;

    $this->myValue = "test";
    return $this->myValue;
}


text:
Q: What is the probability $P(X>0\mid X+Y>0)$ when $X$ and $Y$ are both independent normal mean zero with different variances? Let $X$ have standard deviation $\sigma$ and $Y$ standard deviation $\tau$.
I can write
$$P(X>0\mid X+Y>0) = \frac{P(X>0, X+Y>0)}{P(X+Y>0)}$$
As all variables are zero-mean and symmetric, $P(X+Y>0)=1/2$, so that
$$P(X>0\mid X+Y>0) = 2 P(X>0, X+Y>0) = 2 P(X>0, Y>-X)$$
Using the independence of $X$ and $Y$ and the notation $\Phi$ and $\phi$ for the standard normals, I get
$$P(X>0\mid X+Y>0) = 2 \int_0^\infty \phi\left(\frac{x}{\sigma}\right)
\left(1-\Phi\left(-\frac{x}{\tau}\right)\right) dx.$$
But from here on I do not know how to continue to get a simple expression.
Any suggestions?


text:
Q: Parsing data from html based on a string I need to extract a particular value from a html page -- the related html content is as below:
-html --

Sensex : 26326.60
                                    [22.40]

                                        Nifty : 7970.05 [14.60]

-- end of html --

The value I need to extract is the value that appears after "Nifty : "  - in the above example '7970.05'.
I have the following code to extract this:
--code--
$('td.text21').each(function () {
                    status = true;
                    var price1 = $(this).text().substr(340,7);

--end of code --
however at times I have noticed that the place of the value is not 340 - it changes sometimes to 303 because the img src link changes depending on some values.
The value will always be after "Nifty : " - this never changes.
Is there a way where I can code to extract the 7 digit value that appears after "Nifty : "?
Any help will be appreciated.

A: Instead of taking the substring from 340, you can take it from the position after where "Nifty :" is, which you get by doing
$(this).text().indexOf("Nifty :") + 7; // 7 is the length of "Nifty :"

So your new line would be:
var price1 = $(this).text().substr($(this).text().indexOf("Nifty :") + 7, 7);


text:
Q: Creating custom html content based on a sql bit value. null, 0, 1 If there is no image it returns No Rx on File, this works fine. If there is an image it returns Rx Requires Validation in a blue link. When an image is uploaded it's a 0, when it's selected as active it becomes a 1 as the active field in the database. I'm not sure how to have all images as 0 blue and now the active images that are 1 green. I thought my logic is quite busted at this point.. any help would be greatly appreciated.
if ($a['rx_scanned'] === null)
    {
         echo "
**No Rx on File**
";
    }

elseif ($a['rx_scanned'] = 1 )
    {
  $rx_image_color = '#009933';

    echo "
   $event->id, 'patient_id'=>$patient->code, 'uniqueid'=>$a['image_id']))
            . "' style='color:$rx_image_color'>Valid Rx on File
";

    }
else
    {
      $rx_image_color = '#3366FF';
      echo "
" . cbox_return($name) . "$event->id, 'patient_id'=>$patient->code, 'uniqueid'=>$a['image_id']))
            . "'>**Rx Requires Validation**
";
    }

echo "

";

A: If I am understanding you correctly, you're stating rx_scanned is a boolean value, not a numeric.
You need to change your conditional to check for a boolean (I am not a PHP developer, but I imagine something like so)
if ($a['rx_scanned']) {
  $rx_image_color = '#009933';
   // Insert your stuff here.
}
else {
  $rx_image_color = '#3366FF';
  echo "
**No Rx on File**
";
}


text:
Q: Clickable HTML Table in email I'm trying to create a clickable HTML table that doesn't make the text appear hyperlinked -- and that makes the entire table linked. After spending hours sifting through the previous posts on this topic, I thought I had figured the code out and got it to work in an HTML editor.
However, when I send myself test email samples, the code is not working. In Outlook, the table appears clickable but is not linked. In Gmail, it doesn't appear clickable and is not linked.
A very helpful commenter let me know that I can't have an  tag outside the table, but if I move the  tag to inside the  then it will only link the text, not the whole table.
Is there a workaround for this?
Here is my code:

            TEXT
            TEXT
            TEXT

               TEXT-TEXT

                TEXT-TEXT

                TEXT-TEXT

Thanks so much in advance

A: Add a style color: inherit;in your  tag. It should looks like this:

                TEXT
                TEXT
                TEXT

                   TEXT-TEXT

                    TEXT-TEXT

                    TEXT-TEXT


text:
Q: Multiple layers on Google Maps possible An advance bail - please excuse me if this is something that is not possible
I have multiple KML files from different sources - one providing the weather data, one providing the traffic data and so on.
Can I add multiple layer with different KML files? If not , how do I put all the info into one map?


text:
Q: Best way to check string and convert to int in c# Please help me to improve my code.
The idea is:
 if string is ok
    then convert to int
1- it does check just null or blank string
int t=0;
 if(!string.IsNullOrEmpty(textbox1.text.trim())
     t= int.Parse(textbox1.text.trim());

2-
if(int.tryparse(textbox1.text.trim(), out t)
   t=int.Parse(textbox1.text.trim());

or shortif
 return string.IsNullOrEmpty(textbox1.text.trim()) ? 0 :  int.Parse(textbox1.text.trim());

is there other better way?

A: The correct way to get user input and convert it to integers is through the Int32.TryParse method. This method has the advantage to not throw a costly  exception if the input is wrong (like Parse or Convert.ToInt32) but returns true or false allowing you to display a meaningful error message to your user.
int t;
if(Int32.TryParse(textbox1.Text, out t)
{
  // t has ben set with the integer converted
  // add here the code that uses the t variable
}
else
{
  // textbox1.Text doesn't contain a valid integer
  // Add here a message to your users about the wrong input....
  // (if needed)
}

Notice that textbox1.Text is never null so you don't need to explicitly check for it. Of couse I assume that this textbox1 is a TextBox control defined in your InitializeComponent call and thus is not null by itself.

A: int t = 0;
int.TryParse(textbox1?.Text?.Trim(), out t);

A: int i = 0;

Int32.TryParse(TextBox1.Text, out i);

A: Yes. We need to Check whether TryParse returns true or Not. if true then it succeeds & false if any error occurs.The TryParse will return 0 for both if the TryParse is failed or actual string value is 0.
string s2 = "13.3";
int i;

//i = Convert.ToInt32(s2);                   // Run Time Error
Console.WriteLine(int.TryParse(s2, out i));  // False
Console.WriteLine(i);                        // Output will be 0

string s3 = "Hello";
//i = Convert.ToInt32(s2);                  // Run Time Error
Console.WriteLine(int.TryParse(s3, out i)); // False
Console.WriteLine(i);                       // Output will be 0

string s1 = null;
Console.WriteLine(int.TryParse(s1, out i));  // False
Console.WriteLine(i);                        // Output will be 0

string s4 = "0";
Console.WriteLine(int.TryParse(s4, out i));  // return True
Console.WriteLine(i);                        // Output will be 0


text:
Q: Is the WCF Web.API safe for production applications? The WCF Web.API hasn't been incorporated into the .NET Framework as of the date of this post. Is it safe to use this library in production code or is it's only usefulness for testing at the moment ?

A: While I personally have not implemented a production application with WCF web API, I know several people who have.  I have not heard them report any issues that would cause me to question it's production readiness.  That being said, WCF Web API is an open source project, so you can browse the code yourself to get a feeling for how sound the code is.

A: I'm using it in production.
Albeit it is not allowed at the moment to use it in production at your customers site.
But your customer can get the dependencies using Nuget...
And btw: Web API will be out of band release like ASP.NET MVC is.


text:
Q: Derived. doesn't invoke derived's static constructor Why isn't the static constructor in Derived invoked in the following code?
class Base
{
    public static Base Instance;
    static Base() { Console.WriteLine("Static Base invoked."); }
}

class Derived : Base
{
    static Derived() {
        Instance = new Derived();
        Console.WriteLine("Static Derived invoked.");
    }
}

void Main()
{
    var instance = Derived.Instance;
}

OUTPUT:
Static Base invoked.

A: This is because accessing a static member of a base class through a derived class is in fact compiled to go through the base class, the one that declared that member.
As such, this:
Derived.Instance

is actually compiled like this:
Base.Instance

Thus no code is touching Derived, and that's why its static constructor is not called.
Here's how your Main method is compiled (release):
IL_0000:  ldsfld      Base.Instance
IL_0005:  pop
IL_0006:  ret


text:
Q: c# Remote ServerManager & COM Surrogate footprint I have the following method which presents IIS worker requests on a pretty webpage however every time the page is refreshed it increases the memory consumption of dllhost (COM Surrogate) on the target machine until there is no more memory available.
I'm a beginner when it comes to C# so I'm hoping somebody can explain to me how I can change this code to release the memory footprint on the target server each time its refreshed?
protected void Page_Load(object sender, EventArgs e)
{

    manager = ServerManager.OpenRemote("Lonappu01032");

    int filtered = Convert.ToInt32(Request.QueryString["filter"]);
    StringBuilder sb = new StringBuilder();

    foreach (WorkerProcess proc in manager.WorkerProcesses)
    {
        RequestCollection rc = proc.GetRequests(0);

        var selected = from r in rc
                       select r;
         if (filtered>0)
         {
             selected  = from r in rc
                                  where r.SiteId == filtered
                                  select r;

         }

        foreach (Request r in selected)
        {

            sb.AppendFormat("
{8}	{0}	{1}	{2}	 {3}	{4} ({5}s)	{6}	{7}
", r.HostName, Server.HtmlEncode(r.Url), r.Verb, r.ClientIPAddr, r.PipelineState, TimeSpan.FromMilliseconds(r.TimeInState).TotalSeconds, r.CurrentModule, TimeSpan.FromMilliseconds(r.TimeElapsed).TotalSeconds, r.SiteId);
            RequestCount++;
        }

    }
}

A: First part (a general good practice in C#)
In .NET use the 'using' clause when working with a class that implements IDisposable. Doing this ensures the dispose method will get called when you're done. It just so happens that the ServerManager class implements IDisposable, how nice. By itself that 'should' be enough.
So implement 'using' like below and it might take care of your issue:
protected void Page_Load(object sender, EventArgs e)
{

    using (var manager = ServerManager.OpenRemote("Lonappu01032"))
    {
        int filtered = Convert.ToInt32(Request.QueryString["filter"]);
        StringBuilder sb = new StringBuilder();

        foreach (WorkerProcess proc in manager.WorkerProcesses)
        {
            //your foreach remains unchanged
        }
    }
}

Second part (there's always a but)
However it appears there is a known bug that may not be fixed depending on which version of windows / IIS you're using. see here for example use and reported bug: https://connect.microsoft.com/VisualStudio/feedback/details/722272/microsoft-web-administration-servermanager-memory-leak


text:
Q: Assistance with building an inverted-index It's part of an information retrieval thing I'm doing for school. The plan is to create a hashmap of words using the the first two letters of the word as a key and any words with the two letters saved as a string value. So,
hashmap["ba"] = "bad barley base"
Once I'm done tokenizing a line I take that hashmap, serialize it, and append it to the text file named after the key.
The idea is that if I take my data and spread it over hundreds of files I'll lessen the time it takes to fulfill a search by lessening the density of each file. The problem I am running into is when I'm making 100+ files in each run it happens to choke on creating a few files for whatever reason and so those entries are empty. Is there any way to make this more efficient? Is it worth continuing this, or should I abandon it?
I'd like to mention I'm using PHP. The two languages I know relatively intimately are PHP and Java. I chose PHP because the front end will be very simple to do and I will be able to add features like autocompletion/suggested search without a problem. I also see no benefit in using Java. Any help is appreciated, thanks.

A: I would use a single file to get and put the serialized string. I would also use json as the serialization.
Put the data
$string = "bad barley base";
$data = explode(" ",$string);
$hashmap["ba"] = $data;

$jsonContent = json_encode($hashmap);
file_put_contents("a-z.txt",$jsonContent);

Get the data
$jsonContent = file_get_contents("a-z.txt");
$hashmap = json_decode($jsonContent);

foreach($hashmap as $firstTwoCharacters => $value) {
    if ($firstTwoCharacters == 'ba') {
        $wordCount = count($value);
    }
}

A: You didn't explain the problem you are trying to solve. I'm guessing you are trying to make a full text search engine, but you don't have document ids in your hashmap so I'm not sure how you are using the hashmap to find matching documents.
Assuming you want a full text search engine, I would look into using a trie for the data structure. You should be able to fit everything in it without it growing too large. Nodes that match a word you want to index would contain the ids of the documents containing that word.


text:
Q: alternate way to execute function in select statement for each record alternate way to execute function in select statement for each record.
i have select statement which has fixed column from table with calculated column,so to calculate column i am using function .this function gets call for each record.
so is there any alternate way to do it ?
example :
select ProductName,
ProductCode,
dbo.fn_MinPriceByGroupId_DiscountCode(PS1.Product_Id) as Price
from tbl_Product

now problem is to call function for each row would impact on speed so is there any alternate way to do it.


text:
Q: native isnan check in C++ I stumbled upon this code to check for NaN:
/**
 * isnan(val) returns true if val is nan.
 * We cannot rely on std::isnan or x!=x, because GCC may wrongly optimize it
 * away when compiling with -ffast-math (default in RASR).
 * This function basically does 3 things:
 *  - ignore the sign (first bit is dropped with <<1)
 *  - interpret val as an unsigned integer (union)
 *  - compares val to the nan-bitmask (ones in the exponent, non-zero significand)
 **/
template<typename T>
inline bool isnan(T val) {
    if (sizeof(val) == 4) {
        union { f32 f; u32 x; } u = { (f32)val };
        return (u.x << 1) > 0xff000000u;
    } else if (sizeof(val) == 8) {
        union { f64 f; u64 x; } u = { (f64)val };
        return (u.x << 1) > 0x7ff0000000000000u;
    } else {
        std::cerr << "isnan is not implemented for sizeof(datatype)=="
              << sizeof(val) << std::endl;
    }
}

This looks arch dependent, right? However, I'm not sure about endianess, because no matter about little or big endian, the float and the int are probably stored in the same order.
Also, I wonder whether something like
volatile T x = val;
return std::isnan(x);

would have worked.
This was used with GCC 4.6 in the past.

A:
Also, I wonder whether something like std::isnan((volatile)x) would have worked.

isnan takes its argument by value so the volatile qualifier would have been discarded. In other words, no, this doesn't work.
The code you've posted relies on a specific floating point representation (IEEE). It also exhibits undefined behaviour since it relies on the union hack to retrieve the underlying float representation.
On a note about code review, the function is badly written even if we ignore the potential problems of the previous paragraph (which are justifiable): why does the function use runtime checks rather than compile-time checks and compile time error handling? It would have been better and easier just to offer two overloads.


text:
Q: Flexbox List Overflowing Out of Container I have a little card setup going that includes some links at the bottom/footer of each card. I set those up using flexbox, however, they're extending out of the containers.
I tried specifying a width to the list as well as footer divs, but cannot make it wrap. Any thoughts?

.container {
    /*added by the editor to correctly reproduce the problem*/
        width:250px;
    /*-----*/
        background: #fff;
        border-radius: 5px;
        border: 1px solid #404040;
        box-shadow: 2px 2px 4px #888;
        margin: 0 auto;
    }

    .body {
        margin: 0 auto;
        width: 90%;
    }

    .footer ul {
        list-style: none;
        display: flex;
        flex: row wrap;
        justify-content: flex-end;
        padding-left: 0;
    }

    .footer li+li {
        margin-left: .5rem;
    }

  .footer li {
      line-height: 1.5rem;
      text-align: center;
      position: relative;
      white-space: nowrap;
  }

          Header Stuff

          Body Stuff

Footer Link

Footer Link

Footer Link

Footer Link

A: You just have an incorrect property name on your .footer ul. Instead of flex: row wrap, should be flex-flow: row wrap
Since that property value is not valid the rule is ignored, and there is nothing telling the browser to wrap the flex items in that flex container.

.container {
        width:250px;
        background: #fff;
        border-radius: 5px;
        border: 1px solid #404040;
        box-shadow: 2px 2px 4px #888;
        margin: 0 auto;
    }

    .footer ul {
        list-style: none;
        display: flex;
        /*only change is here*/
        flex-flow: row wrap;
        /*--------*/
        justify-content: flex-end;
        padding-left: 0;
    }

    .footer li+li {
        margin-left: .5rem;
    }

  .footer li {
      line-height: 1.5rem;
      text-align: center;
      position: relative;
      white-space: nowrap;
  }

          Header Stuff

          Body Stuff

Footer Link

Footer Link

Footer Link

Footer Link


text:
Q: Why does sortable() doens't work in dynamic list after drag and drop from another list? I have a problem with my sortable cart.
The main idea is from jQuery documentation, But I also need to make the cart sortable after dynamic drag and drop. I can't understand why sortable('refresh') doesn't work. I tried more than 100 ideas for that, but the result is the same. The code isn't clear, sorry for that.

// There's the gallery and the cart
let $galleries = $('.gallery'),
  $gallery1 = $('#gallery1'),
  $gallery2 = $('#gallery2'),
  $gallery3 = $('#gallery3'),
  $cart = $('#cart'),
  $ul = $('.order'),
  $cartUl = $('#cartUl');

// Let the gallery items be draggable
$('li', $galleries).draggable({
  cancel: 'a.ui-icon', // clicking an icon won't initiate dragging
  revert: 'invalid', // when not dropped, the item will revert back to its initial position
  containment: 'document',
  helper: 'clone',
  cursor: 'move'
});

// Let the cart be droppable, accepting the gallery items
$cart.droppable({
  accept: '.gallery > li',
  classes: {
    'ui-droppable-active': 'ui-state-highlight'
  },
  drop: function (event, ui) {
    addItem(ui.draggable);
  }
});

// Let the galleries be droppable, accepting items from the cart
$galleries.droppable({
  accept: '#cart li',
  classes: {
    'ui-droppable-active': 'custom-state-active'
  },
  drop: function (event, ui) {
    removeItem(ui.draggable);
    updateOrder();
  }
});
// $cartUl.droppable({ accept: '#cartUl li' });

// moving images to the cart
let remove_icon = "Remove";
function addItem($item) {
  $cartUl.sortable();

  $item.fadeOut(function () {
    $item.find('a.ui-icon-cart').remove();
    $item
      .append(remove_icon)
      .appendTo($cartUl)
      .fadeIn(function () {
        $item.find('img');
      });
    $cartUl.sortable('refresh');
    $cartUl.droppable({ accept: '#cartUl li' });

    if ($cartUl.sortable('refresh')) {
      console.log($cartUl.sortable('refresh'));
    }
    showOrder();
    // $item.find('.ui-icon.ui-icon-refresh').next().remove();
  });
}

// Item remomove
let cart_icon = "Add item";
function removeItem($item) {
  switch ($item.attr('data-parent')) {
    case '1':
      $item.fadeOut(function () {
        $item
          .find('a.ui-icon-refresh')
          .remove()
          .end()
          .css('width', '200px')
          .append(cart_icon)
          .find('img')
          .css('height', '180px')
          .end()
          .appendTo($gallery1)
          .fadeIn();
      });
      // updateOrder($item);
      break;
    case '2':
      $item.fadeOut(function () {
        $item
          .find('a.ui-icon-refresh')
          .remove()
          .end()
          .css('width', '200px')
          .append(cart_icon)
          .find('img')
          .css('height', '180px')
          .end()
          .appendTo($gallery2)
          .fadeIn();
      });
      break;
    case '3':
      $item.fadeOut(function () {
        $item
          .find('a.ui-icon-refresh')
          .remove()
          .end()
          .css('width', '200px')
          .append(cart_icon)
          .find('img')
          .css('height', '180px')
          .end()
          .appendTo($gallery3)
          .fadeIn();
      });
      break;
  }
}

function showOrder() {
  //order list
  let $li = document.createElement('li');
  $('#cartUl li h5').each(function () {
    $li.textContent = $(this).text();
    $li.setAttribute('data-id', $(this).parent()[0].id);
  });
  $li = $ul.append($li);
}

function updateOrder($item) {
  ///////once!!!!!
  if ($item.attr('id') === $('.order li').attr('data-id')) {
    console.log($item.attr('id'));
  }
}
// behavior with events
$('ul.gallery > li').on('click', function (event) {
  let $item = $(this),
    $target = $(event.target);

  if ($target.is('a.ui-icon-cart')) {
    addItem($item);
  } else if ($target.is('a.ui-icon-refresh')) {
    removeItem($item);
    updateOrder($item);
  }
  return false;
});

//tabs
$(function () {
  $('#tabs').tabs();
});
.gallery {
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
}
.gallery.custom-state-active {
  background: #eee;
}
.gallery li {
  /* float: left; */
  width: 200px;
  padding: 0.4em;
  margin: 0 0.4em 0.4em 0;
  text-align: center;
}
.gallery li h5 {
  margin: 0 0 0.4em;
  cursor: move;
}
.gallery li a {
  float: right;
  font-size: 14px;
  color: darkgreen;
}

.gallery li > .ui-icon.ui-icon-refresh {
  color: darkred;
  font-size: 12px;
}
.gallery li img {
  width: 100%;
  height: auto;
  cursor: move;
  object-fit: cover;
}

#cart {
  float: right;
  width: 50%;
  min-height: 18em;
  padding: 1%;
  list-style-type: none;
}
#cart h4 {
  line-height: 16px;
  margin: 0 0 0.4em;
}
#cart h4 .ui-icon {
  float: left;
}
#cart .gallery h5 {
  /* display: none; */
}

.ui-widget-wrap {
  display: flex;
  justify-content: center;
}
.cart {
  border: 1px solid green;
}

.ui-tabs-nav {
  display: flex;
  list-style-type: none;
}

.ui-tabs-anchor {
  padding: 15px 20px;
  text-align: center;
  color: darkcyan;
}

#tabs {
  width: 50%;
}

<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

TAB1 TITLE

TAB2 TITLE

TAB3 TITLE

item 1-1

          Add item

item 1-2

          Add item

item 1-3

          Add item

iten 1-4

          Add item

item 2-1

          Add item

item 2-2

          Add item

item 2-3

          Add item

item 2-4

          Add item

item 3-1

          Add item

Hitem 3-2

          Add item

item 3-3

          Add item

item 3-4

          Add item

Cart

11

21

Order:


text:
Q: react-native-firebase can't receive notification while open app iam using react native firebase have an issue I can't receive notification while opening the application if it close I recieve it

A: Try this its worked for me
   notification=()=>{
Const FCN = firebase.notifications();
Const channel = New firebase.notifications.Android.Channel(
  'all',
  'All Notifications',
  firebase.notifications.Android.Importance.Max
).setDescription('All notifications');

FCN.android.createChannel(channel);
 this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification: Notification) => {
 // Process your notification As required
 // ANDROID: Remote notifications Do Not contain the channel ID. You will have To specify this manually If you'd like to re-display the notification.

 Const { title, body } = notification;

 });

this.notificationlocal = FCN.onNotification((notif: Notification) => {

 If (Platform.OS === 'android') {

Const { title, body } = notif;
        Const localNotification = New firebase.notifications.Notification({
          sound: 'sampleaudio',
            show_in_foreground: True,
             local: True,
          })

          .setSound('sampleaudio.wav')
        .setNotificationId(notif.notificationId)
        .setTitle(notif.title)
          .setBody(notif.body)
          .android.setChannelId('all') // e.g. the id you chose above
          .android.setSmallIcon('@drawable/logo') // create this icon in Android Studio
          .android.setColor('#000000')
           .android.setPriority(firebase.notifications.Android.Priority.High);
           console.log("channel",channel)
        firebase.notifications()
          .displayNotification(localNotification)

          .catch(err => console.error(err));

      }

 })
 this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
 // Process your notification As required
 this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification: Notification) => {
 // Process your notification As required
 // ANDROID: Remote notifications Do Not contain the channel ID. You will have To specify this manually If you'd like to re-display the notification.
 Const { title, body } = notification;
 });
 Const { title, body } = notification;
 });
this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
 // Get the action triggered By the notification being opened
  this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification: Notification) => {
 // Process your notification As required
 // ANDROID: Remote notifications Do Not contain the channel ID. You will have To specify this manually If you'd like to re-display the notification.
 Const { title, body } = notification;
 });
 Const action = notificationOpen.action;
 // Get information about the notification that was opened
 Const notification: Notification = notificationOpen.notification;
  Const { title, body } = notification;
 firebase.notifications().removeDeliveredNotification(notification.notificationId);
 //console.log('OPEN:', notification.data);
 });
firebase.notifications().getInitialNotification()
 .then(Async(notificationOpen: NotificationOpen) => {
 // console.log("notificationOpen1",notificationOpen)
 If (notificationOpen) {
 //console.log("notificationOpen",notificationOpen)
 // App was opened By a notification
 // Get the action triggered By the notification being opened
 Const action = notificationOpen.action;
 // Get information about the notification that was opened
 Const notification: Notification = notificationOpen.notification;
 //Const { title, body } = JSON.parse(notification.data.custom_notification);

 }
 });
 this.messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {

 });
}

componentDidMount(){
this.notification
}


text:
Q: Count of last status per day / week is it possible to get the count of last statuses in a day / week via DAX measure?
I want to count only the last status of backlog tickets in a day / week. The backlog is calculated on ticket level (below table Data  per ticket) as accumulated difference of count of opened and closed tickets:
Backlog:=
VAR MaxDate = MAX('q_Calendar'[Date])
RETURN
CALCULATE([Opened]-[Closed],CALCULATETABLE(ALL('q_Calendar')),'q_Calendar'[Date]<=MaxDate)

There are 2 source tables, example below:
Data per step

Ticket Number
Step
Step Date
StepStatus

00001
1
8/25/2021 11:06 AM
10

00001
2
8/25/2021 12:05 PM
20

00001
3
8/27/2021 01:13 PM
30

00001
4
8/27/2021 03:33 PM
40

00002
1
8/27/2021 10:01 AM
10

00002
2
8/27/2021 10:05 AM
20

00002
3
8/30/2021 08:47 AM
30

00002
4
8/30/2021 08:59 AM
35

00002
5
8/30/2021 04:25 PM
30

00002
6
8/31/2021 07:49 AM
40

Data per ticket

Ticket Number
Date Created
Date Resolved
TicketStatus

00001
8/25/2021 11:06 AM
8/30/2021 07:51 AM
Closed

00002
8/27/2021 10:01 AM
8/31/2021 07:55 AM
Closed

So in case the ticket is closed, it should be omitted in the status calculation of that and all future days.
The result should be a bar chart with following data:

Date
StepStatus
Count

8/25/2021
20
1

8/26/2021
20
1

8/27/2021
20
1

8/27/2021
40
1

8/28/2021
20
1

8/28/2021
40
1

8/29/2021
20
1

8/29/2021
40
1

8/30/2021
30
1

There is a relationship between per step and per ticket data. 1 ticket to many steps. So if I take the StepStatus and use the backlog calculating measure, the results are multiplied per each StepStatus type.

A: For example you can create this kind of table ( physical or virtual (to use inside another mesure)):
Table =
var __TickAllDayBetween = GENERATE(Sheet1, CALENDAR(Sheet1[Date Created],Sheet1[Date Resolved]))
var LookupTable =  ADDCOLUMNS(SUMMARIZE(ADDCOLUMNS(SELECTCOLUMNS(Sheet2, "TicketNumber", Sheet2[Ticket Number], "StepDate", DATE(YEAR(Sheet2[Step Date]), MONTH(Sheet2[Step Date]),DAY(Sheet2[Step Date]))), "MAX", CALCULATE(max(Sheet2[Step Date]), filter(ALL(Sheet2[Step Date]), DATEVALUE(Sheet2[Step Date]) = [StepDate]))),[TicketNumber],[MAX]),"LastStatusPerDay", CALCULATE( min(Sheet2[StepStatus]), Filter(ALL(Sheet2[Step Date]),[MAX] = Sheet2[Step Date] )))
var __return =  SELECTCOLUMNS(GENERATE(__TickAllDayBetween, TOPN(1,FILTER(LookupTable, DATEVALUE([MAX]) <= [Date] && [TicketNumber] = [Ticket Number]), [MAX], DESC)), "Date",[Date], "Status",[LastStatusPerDay])
return __return


text:
Q: How make all the dependencies needed for android development offline I have an internet connection problem, and cannot download dependencies on demand, as a solution I thought to download them at another computer and take them to my computer. Is there any method to download all dependencies at once and use them offline?

A: You can, but only if you download it once.
Setting -> Build, Execution, Development -> Gradle
And select offline work:

I hope this is what you need.
Happy coding


text:
Q: finding the solution to $(I_3+A)x=b+2x$ I am having trouble solving the $(I_3+A)x=b+2x$ without finding the matrix $A$.
you are also given the inverse of $A$ and the matrix $b$ which consist of 3x1.

A: The equation $(I_3+A)x=b+2x$ can be turned into $$(I_3+A-2I_3)x=b\\(A-I_3)x=b$$
So you just need to solve for this matrix system:
$$\left[\begin{array}{ccc|c}A_{11}-1&A_{12}&A_{13}&b_1\\A_{21}&A_{22}-1&A_{23}&b_2\\A_{31}&A_{32}&A_{33}-1&b_3\end{array}\right]$$


text:
Q: TPopupActionBar has no ColorMap property? Ok, so I almost have a good looking UI, using TActionManager, TActionMainMenuBars and TToolBar with DrawingStyle as gradient to create a OfficeXP style interface.
I am using a couple of TPopupActionBar popup menus too, but I dont see a ColorMap property. I am using a ColorMap property to change the color of the default XP style color, and also changing the Hot Color of the TToolBar to match the menu.
I now need the TPopupActionBar popup menu to match the menu and toolbar, but how can I do this when I see no way of assigning a ColorMap to it?
Excuse me if this is non trivial, I have looked and cannot see. I also tried at runtime to assign a ColorMap but there doesnt seem to be the property for it?? I can change the Style of the TPopupActionBar, but cannot assign a ColorMap.

A: To assign a ColorMap you can use the OnGetControlClass event of the TPopupActionBar component , then check if the PopupMenu is not nil and finally assign the nested property ColorMap of this property.
check this sample.
procedure TFormMain.PopupActionBar1GetControlClass(Sender: TCustomActionBar;
  AnItem: TActionClient; var ControlClass: TCustomActionControlClass);
begin
  if Assigned(PopupActionBar1.PopupMenu) then
    PopupActionBar1.PopupMenu.ColorMap:= TwilightColorMap1;
end;

check this image which contains a TPopupActionBar with the TwilightColorMap applied


text:
Q: How to do normalization for each feature using Hadoop Pig? Now, I have a data like this:
data_new =
    foreach data
    generate
        (float)$0,
        (float)$1,
        ......;

If data_new only 2 columns, I know we can do normalization to each column as following:
grp_data = group data_new all;
tmp = foreach grp_data {
    sum0 = SUM($0);
    sum1 = SUM($1);
    count = COUNT(data_new);
    generate
        flatten(data_new),
        sum0/count as mean1,
        sum1/count as mean2,
        count as count;
};

tmp = foreach tmp {
    diff0 = ($0 - mean0) * ($0 - mean0);
    diff1 = ($1 - mean1) * ($1 - mean1);
    geneate *, diff0 as diff0, diff1 as diff1;
};

grp_data = group tmp all;
tmp =
    foreach grp_data
    generate
        flatten(tmp),
        SUM(tmp.diff0) as diff0,
        SUM(tmp.diff1) as diff1;

tmp =
    foreach tmp
    generate
        ($0 - mean0) / (SQRT(diff0/count)),
        ($1 - mean1) / (SQRT(diff1/count));

When there are too many columns in data_new, it is impossible to use the above way. So could I ask if there is any way to realize the same function?


text:
Q: Why is it that you don't have to declare (object) for a class that only has __init__ in python? Thanks for helping a n00b
Example of what I am talking about:
class Complex:
    def __init__(self,x,y):
        self.x = x
        self.y = y

Why is it that when you declare the class, you don't have to add (object) to it,
class Complex(object):

A: In Python 2.x, this makes your class old-style, with a different inheritance semantics. Since you don't use inheritance (and the method resolution order is the same in simple cases), it makes no difference in practice. If you're programming in Python 2.x, you should add (object) to profit from the advantages of new-style classes.
In Python 3.2, object is simply the default class you inherit from, and can be left out.

A: class Complex1:
    def __init__(self,x,y):
        self.x = x
        self.y = y

>>> dir(Complex1)
['__doc__', '__init__', '__module__']

class Complex2(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y

>>> dir(Complex2)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__']

A: When you define the class simply like this class Complex you don't inherit the class from any other class and hence it only has those attributes which you define like __init__ (and __doc__ and __module__.) This is a an old-style class.
When you define a class like this - class Complex(object), it means you inherit the class from the class object. As a result, many of its attributes are inherited automatically without the need to yourself define them again like __str__, __class__ , etc. This is new style class.
In python 2.x, new style classes are usually preferred as using old style classes may lead to some problems. For example, __slots__, super, descriptors don't work in old style classes.
Old style classes have been kept in python 2.x just to maintain a backward compatibility. In python 3, this is cleaned up and any class you define is a new style class.
(Also, from what you say, inheriting from object has nothing to do with only defining __init__.)


text:
Q: Too many nested wp_query loops in this hypothetical query? I'm attempting something more complex than I've ever done before with WordPress, so please forgive me if this question doesn't make sense.
I have a Books archive page and want it to display excerpts from my custom post type "Books", sorted first by Genre, then by Series, then by Reading Order. So it would look like this:
Historical GENRE
--- My First Historical SERIES; SERIES description;
------BOOK 1, BOOK 2, BOOK 3
--- My Second Historical SERIES; SERIES description;
------BOOK 1, BOOK 2, BOOK 3
Contemporary GENRE
... ETC
I have gone back and forth on how to set up my data. Right now, I'm set up like this:
"Series" is a Custom Post Type with custom fields "Genre" and "Description";
"Books" is a Custom Post Type with custom fields for "Series" (dropdown list populated by currently published Series) and Reading Order (a number).
So conceptually, this is the code I think I need to do to display my Books Archive page:

*

*WP_Query to select all custom-post-type-SERIES sorted by custom field GENRE;

*For each GENRE, display Genre name if not different from previous Genre name;

*Display SERIES name and description;

*NEW query to select all custom-post-type-BOOKS with parent ID of current custom-post-type-SERIES, sorted by custom field READING ORDER;

*When that query is done, display next SERIES name/description and repeat from 4;

*When there are no more SERIES with current custom-field GENRE, display next GENRE name and repeat from 2.
This seems like a ton of queries though. Before I go write all the code, can you tell me if there's a better way to either think about this or organize my content? Thank you so much!!
Michelle

A: When you need to retrieve and present a lot of information there is bound to be complexity. Mostly it is finding right balance between complex querying and complex sorting in PHP (which is often overlooked option).
Your logic looks mostly fine, what could use tweaking as for me:

*

*Genre seems more like a taxonomy than custom field;

*you are essentially building post relationships here and might be better of just using one of relationships plugins, rather than trying to handle it with custom fields. It seems easy enough now, but add more CPTs into the mix and it might fall apart.


text:
Q: Basic Linked List operations in C I am creating a program to perform basic linked list operations. Right now i have wrote the code only for inserting the node at the front. I ran my program to see its working or not but the program is terminating after accepting the input for the node, then it prints the message after switch. It doesn't even pause for accepting my input for continuing the operations (just before end of main())
here is the code :
#include <stdio.h>
#include <stdlib.h>

struct linkedlist
{
    int num;
    struct linkedlist *next;
};
struct linkedlist *head = NULL;

void display();

void insertBeginning()
{

    struct linkedlist *obj;
    int no;

    obj = (struct linkedlist *)malloc(sizeof(struct linkedlist));

    if(obj == NULL)
    {
        printf("\n Overflow ");
    }
    else
    {
        printf("\n Enter the number = ");
        scanf("%d", &no);

        obj->num = no;

        if(head == NULL)
        {
            head = obj;
            obj->next = NULL;

        }
        else
        {
            obj->next = head;
            head = obj;
        }

    }
}

void display ()
{
    struct linkedlist *head2 = head;
    while(head2 != NULL)
    {
        printf("%d ->",head2->num);
        head2=head->next;
    }
    printf("NULL \n");
}

int main()
{

    int choice;
    char wish;

    printf("\n 1. Insert at beginning");
    printf("\n 2. Insert at end");
    printf("\n 3. Insert in between");
    printf("\n 4. Delete from front");
    printf("\n 5. Delete from end");
    printf("\n 6. Delete from in between");
    printf("\n 7. Reverse");
    printf("\n 8. Sort ascending");
    printf("\n 9. Sort descending");
    printf("\n 10.Swap alternate elements");
    printf("\n 11.Display\n\n");

   do
   {
        printf("\n Enter the option = ");
        scanf("%d", &choice);

        switch(choice)
        {
            case 1:
                insertBeginning();
                break;

            case 2:
//              insertEnd();
                break;

            case 3:
//              insertInbetween();
                break;

            case 4:
//              deleteFront();
                break;

            case 5:
//              deleteEnd();
                break;

            case 6:
//              deleteInbetween();
                break;

            case 7:
//              Reverse();
                break;

            case 8:
//              sortAsc();
                break;

            case 9:
//              sortDesc();
                break;

            case 10:
//              swap();
                break;

            case 11:
                display();
                break;

            default:
                printf("\n Wrong choice ");

        }

        printf("\n Do you wish to continue (y/n) = ");
        scanf ("%c",&wish);

   }while(wish == 'y' || wish =='Y');

return 0;
}

A: In your case, you have to change
 scanf ("%c",&wish);

to
scanf (" %c",&wish);

because, if you don't include the leading white-space before the format specifier, it will consider the remaining \n (newline) which got generated and stored into the input buffer by pressing ENTER key after the first input. So, the second scanf() won't wait for the user input.

A: when calling scanf()
1) with a '%d' format specifier, the trailing newline, from where the user entered the number, will not be consume.
2) with a '%c' format specifier, leading white space, like a newline, will cause the scanf() to fail, leaving the parameter (wish) unchanged.
3) in the posted code, when the 'wish' does not contain a valid 'Y' or 'y' then the program exits.
I agree with the other poster, that adding a choice '0' for exiting would be a much better way than the separate call to scanf()

A: there is a new line after giving the input 'choice' which scan by the variable 'wish'. So we need to remove that newline ('\n').
So if you want the user to continue just use a getchar() before take the input wish. Its easy and simple.
printf("\n Do you wish to continue (y/n) = ");
getchar();
scanf ("%c",&wish);


text:
Q: Javascript Date bug on 31 june? I am trying to check a dates form and I am having the following problem: date difference between 2014-06-30 and 2014-07-01 is two days. Here is a simplified part of my test code :
var date1 = (new Date(2012, 06, 30)).getTime();
var date2 = (new Date(2012, 07, 01)).getTime();
console.log(Math.round((date2-date1)/(1000.0*60*60*24)));

The result is "2". It gives me 1 only if I set date1 to (2014, 06, 31) But you know June is only 31 days!
The result is the same event if I change Year to 2012, 2013...

A: Months start at 0 as the documentation of the Date object explains:

Integer value representing the month, beginning with 0 for January to 11 for December.

So new Date(2012, 06, 30) is not June as you might think. This is July. That's why it has 31 days.
In your example you are calculating the date difference between 1st of August and 30th of July which as your calculus indicates is 2 days.
If you wanted to calculate the day difference between 1st of July and 30th of June:
var date1 = (new Date(2012, 05, 30)).getTime();
var date2 = (new Date(2012, 06, 01)).getTime();
console.log(Math.round((date2-date1)/(1000.0*60*60*24)));

A: new Date(2012, 06, 30) is July, not June.
Try it in your JavaScript console:
> new Date(2012, 06, 30)
Mon Jul 30 2012 00:00:00 GMT-0400 (EDT)
> new Date(2012, 06, 31)
Tue Jul 31 2012 00:00:00 GMT-0400 (EDT)