text:
Q: @convention to closure in swift i have following method:
public func AwesomeSDK_initializeSDK(_ name: UnsafePointer<CChar>?,
                          _ apiKey: UnsafePointer<CChar>?,
                                     _ completionHandler: @convention(c) (UnsafePointer<CBool>) -> Void)

i want to convert last parameter into escaping closure in swift.
@_cdecl("AwesomeSDK_initializeSDK")
public func AwesomeSDK_initializeSDK(_ name: UnsafePointer<CChar>?,
                          _ apiKey: UnsafePointer<CChar>?,
                                     _ completionHandler: @convention(c) (UnsafePointer<CBool>) -> Void) {
    Awesome.initializeSDK(name: String(cString: name!),
                          apiKey: String(cString: apiKey!),
                          completionHandler: <convert_@convention_to_escaping_closure_here>)
}


text:
Q: Combinator logic and unification Summary: if we are trying to use combinator logic to solve first-order logic type problems, is the best method to feed in free variables and use the standard first-order unification algorithm?
In standard first-order logic, consider the problem of deducing that the following is a contradiction
p(x)
~p(5)

By the rule that we can substitute specific for general, we can derive
p(5)
~p(5)

and q & ~q => false.
The particular choice of the constant 5 to substitute for x is obtained using the standard unification algorithm, which in the case of first-order logic is computable (and indeed quite efficient).
Translating this into combinator logic gives
p = K true
~(p 5)

Substituting the value of p gives
~(K true 5)

Evaluating gives
~true

Which is false, QED.
But it doesn't look so good when we try a more complex expression
p(f(f(x)))
~p(f(f(5)))

In standard first-order logic, unification works just as well here as for the simpler case. The translation to CL, however, is
S (K p) (S (K f) f) = K true
~(p (f (f 5)))

This isn't a problem we can solve with simple substitution. One approach we could try is to feed both sides of an equation the same value; if we take the number 5 as a value, the left-hand side of the equation evaluates as
S (K p) (S (K f) f) 5
K p 5 (S (K f) f 5)
p (S (K f) f 5)
p (S (K f) f 5)
p (K f 5 (f 5))
p (f (f 5))

So we have
p (f (f 5)) = K true 5
p (f (f 5)) = true

Substituting into the second expression from the original problem gives
~true

So we have solved the problem, but we did it by guessing the correct value to feed both sides of the equation, by inspection. Is there a general method that could be used?
One that suggests itself is to feed in a variable, which would give
p (f (f x)) = true

From which the standard first-order unification algorithm could be used.
Have we just established that the only way to solve problems in CL is to convert them back into standard logic? Perhaps it's not that bad; at least we have eliminated lambda and the other quantifiers, and their associated bound variables, leaving only free variables.
Still, is there a better method that I'm missing?
(I'm omitting consideration of types here; because combinator logic is Turing complete, presumably type checking will also be needed to avoid the paradoxes of the sort that make simple untyped lambda calculus unsound.)

A: I think first-order unification cannot replace higher-order unification because:
(1) if a variable occurs at the predicate position, FO unification is not supposed to handle that, though it may be fixed (seems easy).
(2) more importantly, sometimes a variable can be replaced by a combinatory term containing combinators such as S K I, and upon substitution, the new term may be reduced by combinatory rules to something else, and then becomes identical with the other term.  By definition that would be a valid unifier.  But FO unification is completely powerless to do that.  So HO unification seems much more complex than the FO version...

redpajama_set_name: RedPajamaStackExchange


text:
Q: NodeJS server "swallows" header field I am creating a proxy server with nodejs.
It works fine unless a CSRF token is required.
When making a request with the request plugin (https://github.com/request/request), the response object's header won#t continue x-csrf-token, even tho the req.header object made a "Fetch".
Any ideas?
app.use("/", function (req, res, next) {
    options = {
    'url': sDestination + req.url,
        'ca': cas,
        'jar': true,//jar,
        'strictSSL': true,
        'headers': {
    accept: '*/*'
        }
    };
    request(options, function (err, response, body) {
    if (err) {
     console.error(err);
     }
    else {
     if (typeof req.headers['x-csrf-token'] === "string") {
    console.log("#1 " + (typeof req.headers['x-csrf-token'])); // string
     console.log("#2 " + (req.headers['x-csrf-token'])); // "Fetch"
     console.log("#3 " + (typeof response.headers['x-csrf-token'])); // undefined
     }
     }
    }).pipe(res);
}

A: Try to also add this request header:
"X-Requested-With": "XMLHttpRequest"

It could do the trick in some (probably not all) cases

A: This did the job:
req.pipe(request(options, function (err, response, body) {
    if (err) {
        return console.error('upload failed:', err);
    }
}), {end: (req.method === "GET" ? true : false)}).pipe(res);


text:
Q: On canvas, a way to make it so multiple apples fall in game? I am creating a game (using HTML5 canvas) that involves catching falling apples, i know, how original! I am having trouble finding a way to make it so multiple apples fall?
Here is the link to the JSFiddle: https://jsfiddle.net/pgkL09j7/14/
var apple_x = 100;
var apple_y = 0;
var basket_x = 100;
var basket_y = 100;
var points = 0;

var basket_img = new Image();
basket_img.src = "http://s18.postimg.org/h0oe1vj91/basket.png";

var Countable = function() {}

     //Background colour of canvas
var c = document.getElementById("c");
var ctx = c.getContext("2d");
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, 500, 500);

     //Here is the event listener
c.addEventListener("mousemove", seenmotion, false);

                        //////////////////////

      function seenmotion(e) {

            //This is the code for the mouse
            //moving over the canvas.
       var bounding_box = c.getBoundingClientRect();
       basket_x = (e.clientX - bounding_box.left) * (c.width / bounding_box.width) - basket_img.width / 2;
       basket_y = (e.clientY - bounding_box.top) * (c.height / bounding_box.height) - basket_img.height / 2;
                        }

                        function start_game() {
                            setInterval(game_loop, 50);
                        }

                        function game_loop() {
                            // The code above is called every 50ms and is a
                            // frame-redraw-game-animation loop.

                            c.width = c.width;

                            // Below is the code that draws the objects
                            draw_apple(apple_x, apple_y);
                            draw_basket(basket_x, basket_y);

                            // Below is the code that updates the balloons location
                            apple_y++;
                            if (apple_x > c.width) {
                                apple_x = 0;
                            }

                            //Here is the collision detection code
                            if (collision(apple_x, apple_y, basket_x, basket_y)) {
                                points -= 0.5;
                            }

                            //Here is the code for the point system
                            points += 1;

                            // and let's stick it in the top right.
                            var integerpoints = Math.floor(points); // make it into an integer
                            ctx.font = "bold 24px sans-serif";
                            ctx.fillText(integerpoints, c.width - 50, 50);
                        }

                        context.clearRect(0, 0, 500, 500);

                        function collision(basket_x, basket_y, apple_x, apple_y) {
                            if (apple_y + 85 < basket_y) {
                                return false;
                            }
                            if (apple_y > basket_y + 91) {
                                return false;
                            }
                            if (apple_x + 80 < basket_x) {
                                return false;
                            }
                            if (apple_x > basket_x + 80) {
                                return false;
                            }

                            return true;
                        }

                        // Code to stop the game when we're finished playing
                        function stop_game() {

                        }

                        //Code for the ball
                        function draw_apple(x, y) {
                            var apple_img = new Image();
                            apple_img.src = "http://s15.postimg.org/3nwjmzsiv/apple.png";
                            ctx.drawImage(apple_img, x, y);

                        }

                        //Code for the basket
                        function draw_basket(x, y) {
                            ctx.drawImage(basket_img, x, y);

                        }

A: I posted this on your previous question, so I'll repeat it here.  You will need to maintain an array of apples, but you will also want to check out requestAnimationFrame in order to improve performance.  Things are going to get janky for you, and you probably already noticed it when you move the bucket around.  I've modified your fiddle to demonstrate exactly how you might modify your program to support multiple apples falling at different rates of speed.  (Set apples_per_level to 2 or more to immediately see multiple apples -- or just play the game, and watch as they accumulate!).
https://jsfiddle.net/h82gv4xn/
Improvements include:

*

*Fixed scoreboard

*Added level progression (Level increases every 10 apples)

*Allowance for many many more apples on screen (play to level 9).

*Apples will fall at different speeds and speed up as the levels increase.

*Uses the animation frame system for much smoother animations.

*Relaxed collision handling (The center of the bucket must touch the apple)

It all gets really silly as the levels wind upwards, but it should be a nice example to improve upon.  The relevant javascript follows (this would go into your onLoad function):
var game = create_game();
game.init();

function create_game() {
    debugger;
    var level = 1;
    var apples_per_level = 1;
    var min_speed_per_level = 1;
    var max_speed_per_level = 2;
    var last_apple_time = 0;
    var next_apple_time = 0;
    var width = 500;
    var height = 500;
    var delay = 1000;
    var item_width = 50;
    var item_height = 50;
    var total_apples = 0;
    var apple_img = new Image();
    var apple_w = 50;
    var apple_h = 50;
    var basket_img = new Image();
    var c, ctx;

    var apples = [];
    var basket = {
        x: 100,
        y: 100,
        score: 0
    };

    function init() {
        apple_img.src = "http://s15.postimg.org/3nwjmzsiv/apple.png";
        basket_img.src = "http://s18.postimg.org/h0oe1vj91/basket.png";

        level = 1;
        total_apples = 0;
        apples = [];

        c = document.getElementById("c");
        ctx = c.getContext("2d");
        ctx.fillStyle = "#000";
        ctx.fillRect(0, 0, 500, 500);

        c.addEventListener("mousemove", function (e) {
            //moving over the canvas.
            var bounding_box = c.getBoundingClientRect();
            basket.x = (e.clientX - bounding_box.left) * (c.width / bounding_box.width) - basket_img.width / 2;
            basket.y = (e.clientY - bounding_box.top) * (c.height / bounding_box.height) - basket_img.height / 2;
        }, false);

        setupApples();
        requestAnimationFrame(tick);
    }

    function setupApples() {
        var max_apples = level * apples_per_level;
        while (apples.length < max_apples) {
            initApple(apples.length);
        }
    }

    function initApple(index) {
        var max_speed = max_speed_per_level * level;
        var min_speed = min_speed_per_level * level;
        apples[index] = {
            x: Math.round(Math.random() * (width - 2 * apple_w)) + apple_w,
            y: -apple_h,
            v: Math.round(Math.random() * (max_speed - min_speed)) + min_speed,
            delay: Date.now() + Math.random() * delay
        }
        total_apples++;
    }

    function collision(apple) {
        if (apple.y + apple_img.height < basket.y + 50) {
            return false;
        }
        if (apple.y > basket.y + 50) {
            return false;
        }
        if (apple.x + apple_img.width < basket.x + 50) {
            return false;
        }
        if (apple.x > basket.x + 50) {
            return false;
        }

        return true;
    }

    function maybeIncreaseDifficulty() {
        level = Math.max(1, Math.ceil(basket.score / 10));
        setupApples();
    }

    function tick() {
        var i;
        var apple;
        var dateNow = Date.now();
        c.width = c.width;
        for (i = 0; i < apples.length; i++) {
            apple = apples[i];
            if (dateNow > apple.delay) {
                apple.y += apple.v;
                if (collision(apple)) {
                    initApple(i);
                    basket.score++;
                } else if (apple.y > height) {
                    initApple(i);
                } else {
                    ctx.drawImage(apple_img, apple.x, apple.y);
                }
            }
        }
        ctx.font = "bold 24px sans-serif";
        ctx.fillStyle = "#2FFF2F";
        ctx.fillText(basket.score, c.width - 50, 50);
        ctx.fillText("Level: " + level, 20, 50);

        ctx.drawImage(basket_img, basket.x, basket.y);
        maybeIncreaseDifficulty();
        requestAnimationFrame(tick);
    }

    return {
        init: init
    };
}

A: Your next logical step would be to create an apple Object with appropriate properties. Following that, you can store them in an Array and animate multiple apples.

A: As Gerard said, you should create an Array of apple Objects. You can take a look at this example with balls instead of apples.
One you are done with that, I would recommend that you draw all the apples that fall at the same speed in different offscreen canvases and that you animate those instead of going apple by apple if you are planning to add many of them. If they are all going to fall at the same speed, use just one offscreen canvas and move all at once.
Also take a look at http://www.html5rocks.com/en/tutorials/canvas/performance/ if you have trouble keeping your FPS at an appropriate rate.


text:
Q: Postgresql Slow query on large table with GROUP BY and ORDER BY I have a table with 7 million tuples which looks like this:
                                                          Table "public.tbl_db_hashcode"
  Column      |           Type           | Collation | Nullable |                   Default                   | Storage  | Stats target | Description
 ------------------+--------------------------+-----------+----------+---------------------------------------------+----------+--------------+-------------
 id               | integer                  |           | not null | nextval('tbl_db_hashcode_id_seq'::regclass) | plain    |              |
 inserttime       | timestamp with time zone |           | not null | now()                                       | plain    |              |
 buildid          | text                     |           | not null |                                             | extended |              |
 app_version      | text                     |           |          |                                             | extended |              |
 device           | text                     |           |          |                                             | extended |              |
 device_api       | text                     |           |          |                                             | extended |              |
 userid           | text                     |           |          |                                             | extended |              |
 request_name     | text                     |           |          |                                             | extended |              |
 hash_code        | bigint                   |           | not null |                                             | plain    |              |
 request_duration | numeric                  |           |          |                                             | main     |              |
 count_number     | integer                  |           | not null | 1                                           | plain    |              |
 foreground       | integer                  |           | not null | 0                                           | plain    |              |
 background       | integer                  |           | not null | 0                                           | plain    |              |
 worker_thread    | integer                  |           | not null | 0                                           | plain    |              |
 main_thread      | integer                  |           | not null | 0                                           | plain    |              |
 status           | integer                  |           | not null | 0                                           | plain    |              |
Partition key: RANGE (inserttime)
Partitions: tbl_db_hashcode_20180729 FOR VALUES FROM ('2018-07-29 00:00:00+07') TO ('2018-07-30 00:00:00+07'),
            tbl_db_hashcode_20180730 FOR VALUES FROM ('2018-07-30 00:00:00+07') TO ('2018-07-31 00:00:00+07'),
            tbl_db_hashcode_20180731 FOR VALUES FROM ('2018-07-31 00:00:00+07') TO ('2018-08-01 00:00:00+07'),
            tbl_db_hashcode_20180801 FOR VALUES FROM ('2018-08-01 00:00:00+07') TO ('2018-08-02 00:00:00+07'),
            tbl_db_hashcode_20180802 FOR VALUES FROM ('2018-08-02 00:00:00+07') TO ('2018-08-03 00:00:00+07'),
            tbl_db_hashcode_20180803 FOR VALUES FROM ('2018-08-03 00:00:00+07') TO ('2018-08-04 00:00:00+07'),
            tbl_db_hashcode_20180804 FOR VALUES FROM ('2018-08-04 00:00:00+07') TO ('2018-08-05 00:00:00+07'),
            tbl_db_hashcode_20180805 FOR VALUES FROM ('2018-08-05 00:00:00+07') TO ('2018-08-06 00:00:00+07'),
            tbl_db_hashcode_20180806 FOR VALUES FROM ('2018-08-06 00:00:00+07') TO ('2018-08-07 00:00:00+07'),
            tbl_db_hashcode_20180807 FOR VALUES FROM ('2018-08-07 00:00:00+07') TO ('2018-08-08 00:00:00+07'),
            tbl_db_hashcode_20180808 FOR VALUES FROM ('2018-08-08 00:00:00+07') TO ('2018-08-09 00:00:00+07'),
            tbl_db_hashcode_20180809 FOR VALUES FROM ('2018-08-09 00:00:00+07') TO ('2018-08-10 00:00:00+07'),
            tbl_db_hashcode_20180810 FOR VALUES FROM ('2018-08-10 00:00:00+07') TO ('2018-08-11 00:00:00+07'),
            tbl_db_hashcode_20180811 FOR VALUES FROM ('2018-08-11 00:00:00+07') TO ('2018-08-12 00:00:00+07'),
            tbl_db_hashcode_20180812 FOR VALUES FROM ('2018-08-12 00:00:00+07') TO ('2018-08-13 00:00:00+07'),
            tbl_db_hashcode_20180813 FOR VALUES FROM ('2018-08-13 00:00:00+07') TO ('2018-08-14 00:00:00+07'),
            tbl_db_hashcode_20180814 FOR VALUES FROM ('2018-08-14 00:00:00+07') TO ('2018-08-15 00:00:00+07'),
            tbl_db_hashcode_20180815 FOR VALUES FROM ('2018-08-15 00:00:00+07') TO ('2018-08-16 00:00:00+07'),
            tbl_db_hashcode_20180816 FOR VALUES FROM ('2018-08-16 00:00:00+07') TO ('2018-08-17 00:00:00+07'),
            tbl_db_hashcode_20180817 FOR VALUES FROM ('2018-08-17 00:00:00+07') TO ('2018-08-18 00:00:00+07'),
            tbl_db_hashcode_20180818 FOR VALUES FROM ('2018-08-18 00:00:00+07') TO ('2018-08-19 00:00:00+07'),
            tbl_db_hashcode_20180819 FOR VALUES FROM ('2018-08-19 00:00:00+07') TO ('2018-08-20 00:00:00+07'),
            tbl_db_hashcode_20180820 FOR VALUES FROM ('2018-08-20 00:00:00+07') TO ('2018-08-21 00:00:00+07'),
            tbl_db_hashcode_20180821 FOR VALUES FROM ('2018-08-21 00:00:00+07') TO ('2018-08-22 00:00:00+07'),
            tbl_db_hashcode_20180822 FOR VALUES FROM ('2018-08-22 00:00:00+07') TO ('2018-08-23 00:00:00+07'),
            tbl_db_hashcode_20180823 FOR VALUES FROM ('2018-08-23 00:00:00+07') TO ('2018-08-24 00:00:00+07'),
            tbl_db_hashcode_20180824 FOR VALUES FROM ('2018-08-24 00:00:00+07') TO ('2018-08-25 00:00:00+07'),
            tbl_db_hashcode_20180825 FOR VALUES FROM ('2018-08-25 00:00:00+07') TO ('2018-08-26 00:00:00+07'),

Now I want to select some values but the query is incredibly slow:
explain analyze
Select
a.buildid,
hashcode.request_name ,
a.totalAffectUser,
a.count_number,
a.totalDuration,
a.totalForeGround
FROM (
    SELECT buildid,
           hash_code,
           array_length(array_agg(distinct userid),1) as totalAffectUser,
           SUM(count_number) as count_number,
           SUM(request_duration) as totalDuration ,
           sum(foreground) as totalForeGround
    FROM
    tbl_db_hashcode
     WHERE inserttime >= '2018-08-26 08:58:08.813' AND inserttime < '2018-08-28 08:58:08.814'
    AND buildid like '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'
    GROUP BY hash_code,buildid
    ORDER BY SUM(request_duration)/SUM(count_number) DESC  LIMIT 10
) a
INNER JOIN
tbl_db_hashcode as hashcode
ON a.hash_code = hashcode.hash_code
WHERE hashcode.inserttime >= '2018-08-26 08:58:08.813' AND
hashcode.inserttime < '2018-08-28 08:58:08.814'
AND hashcode.buildid like '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'  ;

Gather  (cost=532532.00..634634.61 rows=100498 width=222) (actual time=24621.422..25594.576 rows=6977 loops=1)
Workers Planned: 2
Workers Launched: 2
->  Hash Join  (cost=531532.00..623584.81 rows=41874 width=222) (actual time=24243.046..25278.780 rows=2326 loops=3)
     Hash Cond: (hashcode.hash_code = a.hash_code)
     ->  Append  (cost=0.00..88493.51 rows=837482 width=141) (actual time=0.095..949.127 rows=670084 loops=3)
           ->  Parallel Seq Scan on tbl_db_hashcode_20180826 hashcode  (cost=0.00..8853.74 rows=79636 width=141) (actual time=0.094..76.940 rows=63694 loops=3)
                 Filter: ((inserttime >= '2018-08-26 08:58:08.813+07'::timestamp with time zone) AND (inserttime < '2018-08-28 08:58:08.814+07'::timestamp with time zone) AND (buildid ~~ '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
                 Rows Removed by Filter: 3722
           ->  Parallel Seq Scan on tbl_db_hashcode_20180827 hashcode_1  (cost=0.00..79638.77 rows=757845 width=141) (actual time=0.027..748.550 rows=606390 loops=3)
                 Filter: ((inserttime >= '2018-08-26 08:58:08.813+07'::timestamp with time zone) AND (inserttime < '2018-08-28 08:58:08.814+07'::timestamp with time zone) AND (buildid ~~ '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
           ->  Parallel Seq Scan on tbl_db_hashcode_20180828 hashcode_2  (cost=0.00..1.00 rows=1 width=40) (actual time=0.001..0.001 rows=0 loops=3)
                 Filter: ((inserttime >= '2018-08-26 08:58:08.813+07'::timestamp with time zone) AND (inserttime < '2018-08-28 08:58:08.814+07'::timestamp with time zone) AND (buildid ~~ '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
     ->  Hash  (cost=531531.87..531531.87 rows=10 width=97) (actual time=24240.695..24240.695 rows=10 loops=3)
           Buckets: 1024  Batches: 1  Memory Usage: 10kB
           ->  Subquery Scan on a  (cost=531531.75..531531.87 rows=10 width=97) (actual time=24240.682..24240.688 rows=10 loops=3)
                 ->  Limit  (cost=531531.75..531531.77 rows=10 width=129) (actual time=24240.680..24240.682 rows=10 loops=3)
                       ->  Sort  (cost=531531.75..531631.75 rows=40000 width=129) (actual time=24240.678..24240.679 rows=10 loops=3)
                             Sort Key: ((sum(tbl_db_hashcode_20180826.request_duration) / (sum(tbl_db_hashcode_20180826.count_number))::numeric)) DESC
                             Sort Method: top-N heapsort  Memory: 27kB
                             ->  GroupAggregate  (cost=484443.38..530667.36 rows=40000 width=129) (actual time=12283.461..24235.974 rows=3443 loops=3)
                                   Group Key: tbl_db_hashcode_20180826.hash_code, tbl_db_hashcode_20180826.buildid
                                   ->  Sort  (cost=484443.38..489468.26 rows=2009955 width=66) (actual time=12283.357..13829.061 rows=2010252 loops=3)
                                         Sort Key: tbl_db_hashcode_20180826.hash_code, tbl_db_hashcode_20180826.buildid
                                         Sort Method: external merge  Disk: 167000kB
                                         ->  Append  (cost=0.00..109128.83 rows=2009955 width=66) (actual time=0.017..5353.023 rows=2010252 loops=3)
                                               ->  Seq Scan on tbl_db_hashcode_20180826  (cost=0.00..10918.38 rows=191127 width=66) (actual time=0.017..515.033 rows=191083 loops=3)
                                                     Filter: ((inserttime >= '2018-08-26 08:58:08.813+07'::timestamp with time zone) AND (inserttime < '2018-08-28 08:58:08.814+07'::timestamp with time zone) AND (buildid ~~ '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
                                                     Rows Removed by Filter: 11167
                                               ->  Seq Scan on tbl_db_hashcode_20180827  (cost=0.00..98209.46 rows=1818827 width=66) (actual time=0.037..4076.622 rows=1819169 loops=3)
                                                     Filter: ((inserttime >= '2018-08-26 08:58:08.813+07'::timestamp with time zone) AND (inserttime < '2018-08-28 08:58:08.814+07'::timestamp with time zone) AND (buildid ~~ '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
                                               ->  Seq Scan on tbl_db_hashcode_20180828  (cost=0.00..1.00 rows=1 width=112) (actual time=0.105..0.105 rows=0 loops=3)
                                                     Filter: ((inserttime >= '2018-08-26 08:58:08.813+07'::timestamp with time zone) AND (inserttime < '2018-08-28 08:58:08.814+07'::timestamp with time zone) AND (buildid ~~ '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
  Planning time: 4.971 ms
  Execution time: 25694.155 ms
  (35 rows)

Total time handle this query is 25694.155ms
The hash_code column is the int 64bit hash of request_name.My problem is i have to group buildid and hash_code and it take 12s / 29s . After that I have to sort Average total request duration / the number called , it take 15s / 29s.
I tried to create index for both buildid and hash_code :
CREATE INDEX tbl_db_hash_code_20180826_code_buildid_idex ON tbl_db_hashcode_20180826(hash_code,buildid);
CREATE INDEX tbl_db_hash_code_20180827_code_buildid_idex ON tbl_db_hashcode_20180827(hash_code,buildid);
CREATE INDEX tbl_db_hash_code_20180828_code_buildid_idex ON tbl_db_hashcode_20180828(hash_code,buildid);

but it even made query slower ( 36821.304ms ):
Nested Loop  (cost=475582.93..518822.76 rows=100498 width=222) (actual time=36684.262..36820.406 rows=6977 loops=1)
   ->  Limit  (cost=475573.26..475573.29 rows=10 width=129) (actual time=36684.158..36684.167 rows=10 loops=1)
     ->  Sort  (cost=475573.26..475673.26 rows=40000 width=129) (actual time=36684.156..36684.160 rows=10 loops=1)
           Sort Key: ((sum(tbl_db_hashcode_20180826.request_duration) / (sum(tbl_db_hashcode_20180826.count_number))::numeric)) DESC
           Sort Method: top-N heapsort  Memory: 27kB
           ->  GroupAggregate  (cost=1.12..474708.87 rows=40000 width=129) (actual time=1.251..36676.934 rows=3443 loops=1)
                 Group Key: tbl_db_hashcode_20180826.hash_code, tbl_db_hashcode_20180826.buildid
                 ->  Merge Append  (cost=1.12..433509.77 rows=2009955 width=66) (actual time=0.844..26010.678 rows=2010252 loops=1)
                       Sort Key: tbl_db_hashcode_20180826.hash_code, tbl_db_hashcode_20180826.buildid
                       ->  Index Scan using tbl_db_hash_code_20180826_code_buildid_idex on tbl_db_hashcode_20180826  (cost=0.42..41283.13 rows=191127 width=66) (actual time=0.369..2426.700 rows=191083 loops=1)
                             Index Cond: (buildid = '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text)
                             Filter: ((inserttime >= '2018-08-26 08:58:08.813+07'::timestamp with time zone) AND (inserttime < '2018-08-28 08:58:08.814+07'::timestamp with time zone) AND (buildid ~~ '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
                             Rows Removed by Filter: 11167
                       ->  Index Scan using tbl_db_hash_code_20180827_code_buildid_idex on tbl_db_hashcode_20180827  (cost=0.55..371265.07 rows=1818827 width=66) (actual time=0.466..22373.155 rows=1819169 loops=1)
                             Index Cond: (buildid = '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text)
                             Filter: ((inserttime >= '2018-08-26 08:58:08.813+07'::timestamp with time zone) AND (inserttime < '2018-08-28 08:58:08.814+07'::timestamp with time zone) AND (buildid ~~ '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
                       ->  Index Scan using tbl_db_hash_code_20180828_code_buildid_idex on tbl_db_hashcode_20180828  (cost=0.12..8.15 rows=1 width=112) (actual time=0.005..0.005 rows=0 loops=1)
                             Index Cond: (buildid = '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text)
                             Filter: ((inserttime >= '2018-08-26 08:58:08.813+07'::timestamp with time zone) AND (inserttime < '2018-08-28 08:58:08.814+07'::timestamp with time zone) AND (buildid ~~ '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
   ->  Append  (cost=9.67..4312.35 rows=1259 width=141) (actual time=0.077..13.431 rows=698 loops=10)
     ->  Bitmap Heap Scan on tbl_db_hashcode_20180826 hashcode  (cost=9.67..422.16 rows=115 width=141) (actual time=0.062..0.657 rows=70 loops=10)
           Recheck Cond: (hash_code = tbl_db_hashcode_20180826.hash_code)
           Filter: ((inserttime >= '2018-08-26 08:58:08.813+07'::timestamp with time zone) AND (inserttime < '2018-08-28 08:58:08.814+07'::timestamp with time zone) AND (buildid ~~ '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
           Rows Removed by Filter: 6
           Heap Blocks: exact=766
           ->  Bitmap Index Scan on tbl_db_hash_code_20180826_code_buildid_idex  (cost=0.00..9.64 rows=122 width=0) (actual time=0.041..0.041 rows=77 loops=10)
                 Index Cond: ((hash_code = tbl_db_hashcode_20180826.hash_code) AND (buildid = '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
     ->  Bitmap Heap Scan on tbl_db_hashcode_20180827 hashcode_1  (cost=52.27..3889.24 rows=1143 width=141) (actual time=0.363..10.198 rows=627 loops=10)
           Recheck Cond: (hash_code = tbl_db_hashcode_20180826.hash_code)
           Filter: ((inserttime >= '2018-08-26 08:58:08.813+07'::timestamp with time zone) AND (inserttime < '2018-08-28 08:58:08.814+07'::timestamp with time zone) AND (buildid ~~ '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
           Heap Blocks: exact=6261
           ->  Bitmap Index Scan on tbl_db_hash_code_20180827_code_buildid_idex  (cost=0.00..51.98 rows=1143 width=0) (actual time=0.203..0.203 rows=627 loops=10)
                 Index Cond: ((hash_code = tbl_db_hashcode_20180826.hash_code) AND (buildid = '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
     ->  Index Scan using tbl_db_hash_code_20180828_code_buildid_idex on tbl_db_hashcode_20180828 hashcode_2  (cost=0.12..0.95 rows=1 width=40) (actual time=0.004..0.004 rows=0 loops=10)
           Index Cond: ((hash_code = tbl_db_hashcode_20180826.hash_code) AND (buildid = '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
           Filter: ((inserttime >= '2018-08-26 08:58:08.813+07'::timestamp with time zone) AND (inserttime < '2018-08-28 08:58:08.814+07'::timestamp with time zone) AND (buildid ~~ '260c9262-7aaf-4de5-97ae-b7bfdc0761bd'::text))
  Planning time: 4.230 ms
  Execution time: 36821.304 ms
  (38 rows)

I dont have any idea to optimize my query , if you have any suggest please tell me know. Thank you.
-------- Add more information ------
Environment : Intel Core i5 3570 * 4 , RAM 16gb , DISK 256 SSD , UBUNTU 16.04
PostgreSQL 10.4 (Ubuntu 10.4-2.pgdg16.04+1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609, 64-bit
Data : I have 6500 different hash_code ( same with request_name ).


text:
Q: Shift + delete sends to trash for desktop files I'm on Ubuntu 20.10. When I use shift+delete in the file manager, I get a confirmation dialog asking if I want to permanently delete the files, and if I click yes, they're permanently deleted.
However, if I shift+delete a file on the desktop, I get no confirmation dialog, and the file goes to trash.
Why is this behavior inconsistent? How can I make it consistent? I've Google'd a good bit, but all I've found is people saying to use shift+delete to delete permanently, which is what I'm already trying to do.


text:
Q: Naive Bayes in Python I'm trying to do Laplace smoothing on my Naive Bayes code. It gives me 72.5% accuracy on 70% train 30% test set, which is kinda low. Does anyone see anything wrong?
posTotal=len(pos)
negTotal=len(neg)

for w in larr:
  if (w not in pos) or (w not in neg):
    unk[w]+=1
    unkTotal=len(unk)
  else:
    if (w in pos):
      posP+=(math.log10(pos[w])-math.log10(posTotal))
    if (w in neg):
      negP+=(math.log10(neg[w])-math.log10(negTotal))

pos and neg are a defaultdic.

A: My Python's a little rusty, but for the if, don't you want if (w not in pos) and (w not in neg)? Seems like this version would only adjust your scores for words that are somehow found in both pos and neg.


text:
Q: WCF-Rest security using Windows Identity Foundation (STS) I have successfully installed a "Security Service Token".
I have a Wcf-Rest service that is running under the STS created as security.
I am calling the Wcf-Rest service from a Web page using ajax. I would like get the Claims that I have received in the web page once successfully log-in in the STS.
I am able to pass the encrypted cookie, but the wcf-rest service cannot read any claim.
Does Wcf-rest (webHttpBinding) support this possibility?

A: With a bit of plumbing - yes.
Securing WCF Data Services using WIF
Also see Claims Based Identity & Access Control Guide  which has some chapters on REST.


text:
Q: How to read in parallel multiple chunks from the same connection in R? I have a .bz2 file and I want to read it and do some processing. The file cannot be loaded in memory. I want to do some computations on the chunks I read and I they can be performed independently of one another and therefore I thought I would try to do it in parallel.
I tried the following:
library(parallel)
no_cores <- detectCores() - 1
cl <- makeCluster(no_cores)
con = file("myfile.bz2", "r")

parLapply(cl, con,
          function(x)
            print(head(read.csv(x, nrows = 100, stringsAsFactors = F, header = F, colClasses = "character", fill = F), 16)))
## Doesn't work Error in checkForRemoteErrors(val) :
  one node produced an error: 'file' must be a character string or connection

parLapply(cl, list(con, con, con),
          function(x)
            print(head(read.csv(x, nrows = 100, stringsAsFactors = F, header = F, colClasses = "character", fill = F), 16)))
## Doesn't work Error in checkForRemoteErrors(val) :
  3 nodes produced errors; first error: invalid connection

Can this somehow work?
Also any other recommendation as to how to go about it would be really helpful, as I am new to the world of parallel processing.

A: You cannot and must not use connections from one R process in another R process - connections are unique to the R session where they are created.
Internally, they are just integer indices and there is very little in R that protects you from mistakenly trying to use them in other R processes.  If your want to know for details, see https://github.com/HenrikBengtsson/Wishlist-for-R/issues/81.
FWIW, if you use the future framework for parallelization and set R option future.globals.onReference to "error", then it protects you against this mistake (https://cran.r-project.org/web/packages/future/vignettes/future-4-non-exportable-objects.html).  For example,
library(future.apply)
options(future.globals.onReference = "error")

library(parallel)
no_cores <- detectCores() - 1
cl <- makeCluster(no_cores)

cat("Hello world\n", file = bzfile("myfile.bz2", open="wb"))
con <- file("myfile.bz2", "r")

y <- future_lapply(list(con, con, con), FUN = function(x) {
  data <- read.csv(x, nrows = 100, stringsAsFactors = FALSE, header = FALSE, colClasses = "character", fill = FALSE)
  print(head(data), 16)
})
Error: Detected a non-exportable reference ('externalptr') in one of the globals (<unknown>) used in the future expression


text:
Q: Electronic Data Interchange Processing in Java My requirement is to process the EDI (Electronic data interchange) file and create the appropriate records in my application , then send back the acknowledgement back in EDI format.
I want to know any standard API available for creating and processing EDI documents in Java.
Also give me some references (Books) to understand the EDI Standard formats for E-commerce and ERP.
Thanks,
Vel.

A: In order to understand EDI and develop parsing and persisting for EDI you must fist know about their grammar (Loops, segments and fields). below are EDI Loops for your understanding purpose.
LOOP 1000A PAYER IDENTIFICATION
LOOP 1000B PAYEE IDENTIFICATION
LOOP 2100 CLAIM PAYMENT INFORMATION
As for i know there is no Java API, you must implement their selves. In order to understand their grammar and development guidelines you must purchase their guide (Not open source).
"Health Care Claim Payment/Advice" for ePayment 835
"Health Care Claim: Professional" for eClaim 837


text:
Q: In $K[X,Y]$, is the power of any prime also primary? I've recently been reading about primary decomposition, and was browsing the questions here.
From this, I know that it is not true that every primary ideal is the power of a prime ideal.
I'm curious about a slight variation inspired by the comments.

Consider $K[X,Y]$, for $K$ a field. For any prime $\mathfrak{p}\subset K[X,Y]$, and any $n\geq 1$, is the ideal $\mathfrak{p}^n$ primary, so that if $ab\in\mathfrak{p}^n$, then either $a\in\mathfrak{p}^n$ or $b^j\in\mathfrak{p}^n$ for some $j$?

I suspect it is indeed true, and it is obviously true when $n=1$. An inductive approach doesn't feel right, so is there another way to reach the conclusion?

A: The answer is yes. Recall the following important fact:
Theorem. (Reid, Undergraduate Commutative Algebra, Proposition page 22) The prime ideals of $k[x,y]$ are as follows:

*

*$0$;

*$(f)$, for irreducible $f \in k[x,y]$;

*maximal ideals $\mathfrak{m}$.

Now you can easily conclude with the following two facts:
(a) a power of a maximal ideal is primary (Atiyah, Macdonald 4.2); (b) in a UFD the power of a principal prime ideal is primary.
I don't know what happens in general in $k[x_1, \dots, x_n]$, when $n \geq 3$. It can be proved that if $\mathfrak{p}$ is a monomial prime in $k[x_1, \dots, x_n]$ then $\mathfrak{p}^m$ is $\mathfrak{p}$-primary for all $m$.


text:
Q: What is the proper way to declare variables in php? I was using variables in my php file without declaring them. It was working perfect in old version of localhost (i.e vertrigoServ 2.22).
But when I moved to latest version of localhost (i.e xampp 3.2.1), I encountered variables declaration warnings and errors something like this:

Notice: Undefined variable: att_troops_qty in D:\Installed
  Programs\htdocs\dashboard\WarLord\PHP_Code\MyAjax.php on line 1247

So I declared all the variables at the top of php file like this:
$page = "";
$att_troops_qty = "";
$def_troops_qty = "";
$ca_level = "";
$b_level = "";
$pre_buildings = "";
$created_pre_b = "";
$building_id = "";
$building_loc = "";
$ca_1_b_loc = "";
$ca_1_b_level = "";
$ca_2_b_loc = "";
$ca_2_b_level = "";

It solved the problem But I have confusion that this is not the proper way to declare variables.
Is there some more better way for variables declaration?

A: How you are declaring is perfectly alright and proper way.
$test = "";

or

$test = null;

these both are proper ways for declaring empty variables.
for more info please visit http://php.net/manual/en/language.types.null.php

A: You need to declare variables before echoing them out. An example is here:
<?php
    $var = "test";
    echo $var; // it will echo out test
?>

And trying to echo out a variable this way will generate an error:
<?php
    echo $var; // it will generate error
    $var = "test";
?>

In addition, you can declare variables in another file and can include that file to echo out the variable somewhere. Remember to include the file first and then call it.
Example vars.php:
<?php
    // define vars
    $var1 = "Test 1";
    $var2 = "Test 2";
?>

Now in another file, include vars.php first and then call the variable:
<?php
    require_once"vars.php";
    echo $var1;
?>

A: You cannot use undeclared variables but
you can declare them on the go.
Inside functions you can do something like that:
function abc() {
    return $newVar or null; // without variable declaration
}

If $newVar is not declared before function will return null;
Or better way:
function abc($newVar = null) {
    return $newVar; // with variable declaration
}

A: The best way to check whether the variable is declare or not, is to use the isset() function, which checks whether the variable is set  or not like:
<?php
    if(isset($a)){
       // execute when $a is set ( already declare ) or have some value
    }
    else {
      // execute when $a not set
   }
?>

A: You can declare variables in php as
<?php
   $test = "xyz" //for String datatype
   $test1 = 10 //for integer datatype
?>

Name of a variable declared must be alphanumeric and you don't need to specify the type.


text:
Q: Logic synthesis from an arbitary piece of code I have completed on a project making physical logic gates and am now looking for a way to turn an arbitrary program into some series of logic gates so I can use them.
I need a program that can take some arbitrary function (say f= x^2 -1) directly into some series of logic gates. Does this already exist?
I have found Verilog and several other open source options but they do not appear to output circuit diagrams. There is also Quartus II and other programs which will convert VHDL code into a schematic.
Preferably I would like something that compiles Python/C++ to a logic gate schematic directly - but really any language is fine.
Thanks.
EDIT: I do mean physical gates - they use ball bearings!
I have all of the 1-bit-input/1-bit-output gates and all of the 2-bit-input/1-bit output-gates. From these I can also construct a MAJ gate to do error correction.

A: Write your arbitrary code in VHDL, turning VHDL into gates is what a synthesis tool does.
Not everything you write will be synthesisable; file handling can't be translated into gates, neither can anything that conventionally uses the heap (such as malloc, or pointers, in C, or "new" and access types in VHDL). Floating point can be synthesised (with VHDL-2008) but it's not quite as simple as signal  A : Real; A <= 2.0 * X * X - 1.0; you have to use types from the synthesisable floating point library. So there may be some negotiation with the tool about the programming language subset you can use.

But I'm sensing a slightly different question here : how do I translate arbitrary code into MY logic gates, implemented in (technology not described in the question). And that's harder to answer.
Synthesis tools usually come from a vendor such as an FPGA vendor, and they translate arbitrary code into that vendor's logic gates, not yours.
The ideal solution is to create a library describing your logic technology, which plugs into a vendor-neutral synthesis tool, such as Synplicity from Synopsys. Then Synplicity can synthesise to your technology instead of an FPGA vendor's.
OK, but creating that library is likely to be a task roughly on a par with writing a backend for a custom CPU's instruction set, and integrating that backend into gcc. Except that Synplicity, unlike gcc, isn't open source, so without considerable financial and technical resources, and help and internal documentation from a major EDA tool company, it's approximately impossible. (At this point I'd be delighted to be corrected by someone who's actually done it)
EDIT (nearly 7 years later!)
GHDL (open source VHDL simulator) available from Github has grown a synthesis branch, so this route is now likely to be easier (I'll stop short of saying easy!) or may be a better choice than a proprietary toolset for the route below. It has a tie-in to the YOSYS open source synthesis suite. CAVEAT : I haven't tried it, but it may be worth a look for future viewers of this question.
(end edit)

So we need a different approach.
Back to the FPGA synth tools : I'll use Xilinx XST as an example. It'll synth to Xilinx primitives, in some Xilinx closed internal format.
However there's also an option labelled "Write post-synthesis netlist".
Using that, you can get a structural VHDL file representing the translation of your arbitrary code into Xilinx gates, flip-flops, and other elements, which are drawn from the Simprims library.
Attempt to compile that (e.g. in a simulator) without making the Simprims library visible (e.g. with the library Simprims; use Simprims; statements commented out and you'll get something valuable:
a list of compilation errors
Not so valuable, you may think : except that it's actually a list of gates, flipflops and other elements that are needed to implement your design.
If you can find (or create) a one-to-one correspondence between these, and elements in your chosen technology, then you can map this netlist to your technology.
If there are Simprims elements for which you don't have equivalents, you need to implement them - e.g. by creating 3-input AND gates from networks of the 2-input NAND gates you have.
Use the corresponding elements from your own (VHDL) library, instead of Simprims, and you should, in theory, have a usable compiled design.
(You're on your own with problems like layout, routing, timing analysis. This is not trivial, but for the sake of this question I'm assuming your "project making physical gates" has these covered...)

A: Firstly, logic synthesis is basic logic optimization of logic circuits, or the transformation of structural logic circuits into a data structure representing logic circuits. See https://stackoverflow.com/a/60535990/1531728 for resources about logic synthesis.
Secondly, to transform computer programs (e.g., in Python, C, C++, or otherwise) into logic circuits, you would need to perform high-level synthesis (or behavioral synthesis) to transform the computer program by parsing it into a control and data flow graph (CDFG, or a pair of control flow graph and a dataflow graph), optimize the CDFG, and subsequently transform this CDFG into a logic circuit for logic synthesis. Once you have the logic circuit, you still need to perform physical design (e.g., floorplanning, placement, and routing) to map that logic circuit into a layout for tapeout (standard-cell -based digital integrated circuit design) or onto a field-programmable gate array (FPGA).
The references below provide literature reviews into the topics I mentioned.
@book{Lavagno2016a,
    Address = {Boca Raton, {FL}},
    Author = {Luciano Lavagno and Igor L. Markov and Grant Martin and Louis K. Scheffer},
    Doi = {https://dx.doi.org/10.1201/b19569},
    Edition = {Second},
    Publisher = {{CRC} Press},
    Series = {Electronic Design Automation for Integrated Circuits Handbook},
    Title = {Electronic Design Automation for {IC} System Design, Verification, and Testing},
    Volume = {1},
    Year = {2016}}

@book{Lavagno2016,
    Address = {Boca Raton, {FL}},
    Author = {Luciano Lavagno and Igor L. Markov and Grant Martin and Louis K. Scheffer},
    Doi = {https://dx.doi.org/10.1201/b19714},
    Edition = {Second},
    Publisher = {{CRC} Press},
    Series = {Electronic Design Automation for Integrated Circuits Handbook},
    Title = {Electronic Design Automation for {IC} Implementation, Circuit Design, and Process Technology},
    Volume = {2},
    Year = {2016}}

See https://github.com/lsils/lstools-showcase for the state-of-the-art logic synthesis libraries from EPFL (Ecole Polytechnique Fédérale de Lausanne) in Lausanne, Switzerland.
You can use these tools to perform logic synthesis. They are programs, commercial high-level synthesis software, that transform C or C++ code into Verilog (or some other hardware description language, HDL), and subsequently into logic circuits.
You can also consider Python-based HDL (such as PyMTL, PyRTL, or MyHDL), Scala-based HDL (e.g., Chisel HDL), or Haskell-based HDL (e.g., Clash). These HDLs provide a workaround to your goal of transforming computer programs into logic circuits.


text:
Q: Tree to Array in Javascript - 2x difference in performance between spread (...) and generator based syntax What causes the difference in performance between these two implementations of pre-order traversal?
So I wanted to practice some functional programming in JavaScript and to create some functions that can operate on trees. I checked a bunch of articles abut it, and it seems that functional programming is not the way to go in JavaScript and that for loops and other imperative functionalities are quite common. I wanted to test which way of traversing a tree would be faster - the functional one based on spread syntax or the one based on yield. It seems that the spread syntax based is much faster - it's roughly twice as fast as the one based on yield! Also, it has quite a lot of variance, while the
I got this code from being as slow as 700op/s and as fast as 1500 op/s while the yield based implementation is stable around 400 op/s.
Here is the code:
class BinaryTreeNode {
  constructor(key, value = key, parent = null) {
    this.key = key;
    this.value = value;
    this.parent = parent;
    this.left = null;
    this.right = null;
  }

  get isLeaf() {
    return this.left === null && this.right === null;
  }

  get hasChildren() {
    return !this.isLeaf;
  }
}

class BinaryTree {
  constructor(key, value = key) {
    this.root = new BinaryTreeNode(key, value);
  }

  seql(node = this.root) {
    return [
      node,
      ...(node.left ? this.seql(node.left) : []),
      ...(node.right ? this.seql(node.right) : []),
    ];
  }

  *preOrderTraversal(node = this.root) {
    yield node;
    if (node.left) yield* this.preOrderTraversal(node.left);
    if (node.right) yield* this.preOrderTraversal(node.right);
  }

  fill() {
    for (let node of this.seql()) {
      if (node.left === null) {
        node.left = new BinaryTreeNode(Math.random(), Math.random(), node);
      }
      if (node.right === null) {
        node.right = new BinaryTreeNode(Math.random(), Math.random(), node);
      }
    }
  }
}

let i = 1;
const tree = new BinaryTree(Math.random, Math.random());
while (i < 13) {
  tree.fill();
  i++;
}

const test = () => {
  [...tree.preOrderTraversal()];
  //[...tree.seql()];
};

const iterationsC = 50;
const main = async () => {
  const runBaseline = (iterations = iterationsC) => {
    let startTime = new Date().getTime();
    for (let i = 0; i < iterations; i++) {
      // no operation
    }
    let endTime = new Date().getTime();
    return endTime - startTime;
  };

  const runTest = (iterations = iterationsC) => {
    let startTime = new Date().getTime();

    for (let i = 0; i < iterations; i++) test();

    let endTime = new Date().getTime();
    let baselineTime = runBaseline(iterations);
    let totalTime = endTime - startTime - baselineTime;
    let fnTime = (totalTime / iterations).toFixed(10);
    let operations = Math.floor((1000 / totalTime) * iterations);

    console.log(`total: ${totalTime}, time: ${fnTime}, op/sec: ${operations}`);
  };

  while (true) {
    runTest();
    await sleep(50);
  }

  function sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
};

main();

The code for the binary tree comes from 30 seconds blog and is licensed under CC 4.0 and the code from benchmarking comes from this blogpost.
This is a massive difference. What can be the cause of that?


text:
Q: Default timezone hardcoded as UTC? While debugging a plugin I was writing, I noticed that on line 36 of wp-settings.php, the default timezone is hardcoded to UTC with a call to the date_default_set_timezone() function. This means any call to the PHP date/time functions will work with UTC as the local time.
Can someone please explain to me why this is a sane design choice by the Wordpress team? I understand if they want to store and manipulate times internally as UTC, but wouldn't a better alternative be to explicitly switch to a "UTC mode" when they need to do such logic?
Assuming you know to set your server's php.ini's timezone setting, this hardcoded UTC basically invalidates php.net's description of the date() function:

date — Format a local time/date

Which strikes me as a bad thing, no?

A: Somehow I missed the current_time function, which gives a good description of the situation and how to properly deal with the need to get the current blog-local time.
http://codex.wordpress.org/Function_Reference/current_time
Though the purist in me still hates how WP makes the time zone setting in php.ini obsolete without giving you a choice. *grumble grumble*

A: WordPress is not a simplistic script, it is a extensive web app. It includes own time zone settings and own functions for output of localized date/time info.
I suppose it is much more straightforward to set baseline time zone and operate on top of that, than trying to change it back and forth around all related functionality.


text:
Q: Modifying a set while iterating over it I would like to iterate over a set while I'm deleting
items from it. There are similar questions for deleting
one item at the time or for lists, but they do
not work for my case.
The code follows; I iterate over a
set ZN and in the end of the iteration I'm removing a
few items (the ones belonging to the set temp). But the
iteration is still happening over the "original" ZN.
How can I modify this code to change the set ZN while
I'm iterating over it?
def CyclotomicCosets(q,n):
    N=q^n-1
    ZN=set(range(N))
    Cosets=[]
    for i in ZN:
        tmp=set([])
        for j in range(n):
            tmp.add( i*(q^j) %N)
        Cosets.append(list(tmp))
        ZN=ZN.difference(tmp) # <------------ Does not do what I want
    return(Cosets)

A: Use a while loop and .pop() values to process from the set:
def CyclotomicCosets(q, n):
    N = q ^ n - 1
    ZN = set(range(N))
    Cosets = []
    while ZN:
        i = ZN.pop()
        tmp = {i * (q ^ j) % N for j in range(n)}
        Cosets.append(list(tmp))
        ZN -= tmp
    return Cosets

Note that I replaced your inner for loop with a set comprehension to make it a little faster and more compact. These were introduced in Python 2.7 and Python 3, in earlier versions of python you can use a generator expression instead:
tmp = set(i * (q ^ j) % N for j in range(n))

Your original mistake was to replace ZN rather than update it:
ZN=ZN.difference(tmp)

This did not alter the original set you were using in the for loop. Rather, you are creating a new set and point the ZN reference to that.
However, you cannot modify a set while iterating over it, so even an in-place difference would not have worked; you would have to use ZN -= tmp or ZN.difference_update(tmp) but that would lead to exceptions instead:
>>> ZN = set(range(3))
>>> for i in ZN:
...     ZN -= set([2])
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: Set changed size during iteration

The corrected code gives:
>>> CyclotomicCosets(3, 5)
[[0], [0, 1, 2, 3], [0, 1, 4, 5], [0, 4, 5, 6]]

Alternatively, loop over range(N) instead, and keep a set of values you've already processed:
def CyclotomicCosets(q, n):
    N = q ^ n - 1
    Cosets = []
    seen = set()
    for i in range(N):
        if i in seen: continue
        tmp = {i * (q ^ j) % N for j in range(n)}
        Cosets.append(list(tmp))
        seen |= tmp
    return Cosets


text:
Q: I want to shorthand my code in using condition? I did $company into new array according to its same group value.
In my real project $company array is more than that.So the group value has many ,then checking my if else condition code will be more need to write.I'll be appreciate if there is any good shortand code below that condition !!
<?php
$company = [["name"=>"Gnext","group"=>"Pro"],
            ["name"=>"AXN","group"=>"Standard"],["name"=>"Victim","group"=>"VIP"],
            ["name"=>"Necom","group"=>"Standard"],["name"=>"Mnet","group"=>"Pro"]
           ];
$new_arr = array();

foreach ($company as $key => $value) {
    if($value["group"] == "Pro"){
        $new_arr[$value["group"]][] = $value["name"];
    }
    elseif ($value["group"] == "VIP") {
        $new_arr[$value["group"]][] = $value["name"];
    }
    else{
        $new_arr[$value["group"]][] = $value["name"];
    }
}
var_dump($new_arr);

A: You do the same in every if / else statement.. why dont you shorten this?
foreach ($company as $key => $value) {
  $new_arr[$value["group"]][] = $value["name"];
}


text:
Q: Combine row pairs with swapped columns I have a table that contains an even number of rows.
The rows form pairs with the same information but the content
of the first two columns swapped. Here is an example with three columns:
1  2  3
=======
A  B  W
B  A  W
C  D  X
D  C  X
E  F  Y
H  G  Z
F  E  Y
G  H  Z

My actual table has many more columns, but the content is always the same
within a pair.
I'm looking for an SQL-Statement that gets rid of one row of each pair.
The result should look like this:
1  2  3
=======
A  B  W
C  D  X
E  F  Y
G  H  Z

My table is generated by a script (which I can't change), so I assume
my input is correct (every row has a partner, rows >=3 are the same for each pair).
A statement that could check these preconditions would be extra cool.

A: If every row has a counterpart where c1 and c2 are swapped then just select rows where c1 and c2 are in a certain order (i.e. c1 < c2).
The EXISTS part makes sure that only rows that have a counterpart are shown. If you want to show all unique rows regardless of whether or not they have a counterpart, then change the last condition from AND EXISTS to OR NOT EXISTS.
SELECT * FROM myTable t1
WHERE c1 < c2
AND EXISTS (
    SELECT * FROM myTable t2
    WHERE t2.c1 = t1.c2
    AND t2.c2 = t1.c1
    AND t2.c3 = t1.c3
) ORDER BY c1

A: Something similar would help using ROWNUM and CTE
with test_Data as
(
SELECT COL1, COL2, COL3, ROWNUM ROWCOUNT FROM
(
SELECT 'A' COL1,  'B' COL2,  'W' COL3 FROM DUAL UNION
SELECT 'B' COL1,  'A' COL2,  'W' COL3 FROM DUAL UNION
SELECT 'C' COL1,  'D' COL2,  'X' COL3 FROM DUAL UNION
SELECT 'D' COL1,  'C' COL2,  'X' COL3 FROM DUAL
) ORDER BY COL3, COL1
)
SELECT TAB1.COL1, TAB1.COL2, TAB1.COL3 FROM TEST_DATA TAB1, TEST_DATA TAB2
WHERE
TAB1.COL1 = TAB2.COL2
AND TAB1.COL2 = TAB2.COL1
AND TAB1.COL3 = TAB2.COL3
AND TAB1.ROWCOUNT = TAB2.ROWCOUNT+1;

Your query without testdata would be,
with CTE as
(SELECT COL1, COL2, COL3, ROWNUM ROWCOUNT FROM MY_TABLE ORDER BY COL3,COL1)
SELECT TAB1.COL1, TAB1.COL2, TAB1.COL3 FROM CTE TAB1, CTE TAB2
WHERE
TAB1.COL1 = TAB2.COL2
AND TAB1.COL2 = TAB2.COL1
AND TAB1.COL3 = TAB2.COL3
AND TAB1.ROWCOUNT = TAB2.ROWCOUNT+1;

A: You didn't state your DBMS so this is ANSI SQL:
select least(c1,c2),
       greatest(c1,c2),
       min(c3) -- choose min or max to your liking
from the_table
group by least(c1,c2), greatest(c1,c2)

A: For Me the below code is working
DECLARE @TEST TABLE
(A CHAR(1),B CHAR(1),C CHAR(1))

INSERT INTO @TEST VALUES
('A','B','W'),
('B','A','W'),
('C','D','X'),
('D','C','X'),
('E','F','Y'),
('H','G','Z'),
('F','E','Y'),
('G','H','Z')

SELECT      MIN(A) [1],
            MAX(A) [2],
            C [3]
FROM        @TEST
GROUP BY    C

Result:


text:
Q: How do you tail oozie job logs? I typically check logs with this command:
 $ oozie job -oozie http://localhost:8080/oozie -log 14-20090525161321-oozie-joe

This will print everything. However I want to only see the last few lines.
How can i tail oozie job logs?
Thanks

A: As Chris suggested above use this to print last 10 lines
$ oozie job -oozie oozie_URL -log job_ID | tail -n 10


text:
Q: How to create array structure of div my matching div id with data-id which is id of other child div?

var pushData = [];
$(function() {
  CreateArray();
});

function CreateArray() {
  //output in data:
  var data = [{
    "Id": 38,
    "Connections": [39, 40],
    "Name": "ABc"
  }, {
    "Id": 39,
    "Connections": [40],
    "Name": "pqr"
  }, {
    "Id": 40,
    "Connections": [],
    "Name": "lmn"
  }];

  $.each(data, function(index, value) {
    $(document.createElement('div')).addClass("latestblock")
      .html(value.Name)
      .attr('id', value.Id)
      .attr('data-id', value.Connections)
      .appendTo($("#container"));
  });

  //Above loops generates this:
  //
ABc

  //
pqr

  //
lmn

  //Here data-id:39,40 indicated that div 39 and div 40 are connected to div 38 and so i want to create my array
  //like this:

  //Expected Output:
  //  pushData[0]:
  //   from:
ABc

  //   To:
pqr

  //  pushData[1]:
  //    from:
ABc

  //   To:
lmn

  //  pushData[2]:
  //   from:
pqr

  // To:
lmn

  //$('#container').find('div').each(function () {
  //    var Id = $(this).attr('id');
  //    var connections = $(this).attr('data-id').split(',');
  //    for (var i = 0; i < connections.length; i++) {
  //       pushData.push({
  //            from: userId,
  //            to: connections[i]
  //        });
  //    }
  //    console.log(pushData)
  //});

  //With above code i am getting output like this:
  // pushData[0]:
  // from:38
  // To:39
  // pushData[0]:
  // from:38
  // To:40

}

  ertertert

I want to create array structure of div by matching data-id(which is comma seperated and this data-id is nothing but id of other child divs)
along with other div id:
This is my div:

var pushData = [];
function CreateArray(){
 $.getJSON('My Wcf service Url', function (data) {

          //output in data:
          var data=[
           {
              "Id": 38,
               Connections":[39,40],
                   "Name":"ABc"
          },
           {
              "Id": 39,
               Connections":[40],
               "Name":"pqr"
           },
           {
               "Id": 40,
                Connections":[],
               "Name":"lmn"
           }]

               $.each(data, function (index, value) {
                    $(document.createElement('div')).addClass("latestblock")
                    .html(value.Name)
                    .attr('id', value.Id)
                    .attr('data-id', value.Connections)
                    .appendTo($("#container"));
                });

               //Above loops generates this:
                  //
ABc

                  //
pqr

                  //
lmn

                 //Here data-id:39,40 indicated that div 39 and div 40 are connected to div 38 and so i want to create my array
                 //like this:

                 Expected Output:
                 pushData[0]:
                             from:
ABc

                              To:
pqr

                 pushData[1]:
                             from:
ABc

                             To:
lmn

                 pushData[2]:
                             from:
pqr

                              To:
lmn

        //$('#container').find('div').each(function () {
        //    var Id = $(this).attr('id');
        //    var connections = $(this).attr('data-id').split(',');
        //    for (var i = 0; i < connections.length; i++) {
        //       pushData.push({
        //            from: userId,
        //            to: connections[i]
        //        });
        //    }
        //    console.log(pushData)
        //});

        //With above code i am getting output like this:
        pushData[0]:
                   from:38
                   To:39
        pushData[0]:
                   from:38
                   To:40
 });
}

Expected Output:
 pushData[0]:
                         from:
ABc

                              To:
pqr

                pushData[1]:
                            from:
ABc

                             To:
lmn

                pushData[2]:
                             from:
pqr

                              To:
lmn

A: See the comments inline in the code.
// The resulting array
var result = [];

// Iterate over all the objects in array
data.forEach(function (obj) {
    // Create the `from` object
    var from = $('
' + obj.Name + '
');

    // Iterate over all connections of this item
    obj.Connections.forEach(function (id) {
        // Get the corr. data from the main array
        var connectionObj = data.find(obj => obj.Id === id),
            to = $('
' + connectionObj.Name + '
');

        // Add the object in the result array
        result.push({from, to});
    });
});

console.log(result);

Demo on JSFiddle


text:
Q: subset vertices such that minimum weight is d Imagine you have a weighted undirected graph G=(V,E) that is fully connected (edge between every pair of vertices). You seek to have a graph G' where G' is a subset of G where vertices with their corresponding edges have been removed such that the edge with the minimum weight is d.
Trivially you can just remove all vertices but a few with highly weighted edges. But what if you want G' to be as big as possible ?   What is the way to remove the minimal set of vertices to satisfy the weight condition ?
For instance I have graph A,B,C  (A,B) = 2 (A,C) = 3 and (B,C) = 2 and my minimum d=2. I could remove both A and C to get just B. But I could also remove B to leave A and C. The second solution is the one with the minimal amount of removals.


text:
Q: Is Stack Overflow for Teams going to be removed from the sidebar on the rest of the network?
I got a toast on my left sidebar saying -

"Stack Overflow for Teams is moving to its own domain! When the migration is complete, you will access your Teams at stackoverflowteams.com, and they will no longer appear in the left sidebar on stackoverflow.com.
Check your email for updates."

I checked my mail and this was mentioned:

You will be able to access your private team from stackoverflowteams.com. Private teams will no longer appear in the left sidebar on stackoverflow.com and will not be accessible from the public site.

Is this true for the rest of the network as well? I actually tend to check Teams from MSE and SU. This would result in a minor rejigging of my tabs but I can imagine this could change the workflow for some.

A: Yes, it applies network-wide. Once your team has been migrated to stackoverflowteams.com it will no longer appear in the sidebar anywhere on the network.

A: It seems that stackoverflow.com can't know about your Teams but no such restriction applies on the stackoverflowteams.com site itself, where all your teams appear in the site chooser.

This certainly is an inconvenient change.
There are many domains with knowledge of other domains that don't fall under the Stackoverflow.com subdomain list. The reason offered is for SOC 2 compliance when reviewed by an auditor, but such doesn't require this inconvenience; indeed factors allowed for are: "meeting the entity's objectives" and "allowing information to flow up, down, and across the organization".
Rather than being a "technical difficulty", it's more of a limitation built into the design and language of the organization's requirements. Rather than writing a slightly more lenient criteria requirement they have produced one which is not necessary to comply with SOC 2; necessitating the removal of the teams from the site chooser. Such teething pains were often built in to documents specifying implementations of the Common Criteria in various organizations.


text:
Q: Apache rewrite behavior changes - depending on server I've got an apache headache, and I'm looking for some stackoverflow advil.
Here's the .htaccess.
php_flag display_errors off

RewriteEngine On

# Redirect everything to the Front COntroller
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^(css|images|files)/ index.php [NC,L]

This is how it is treated on Server A:

*

*Request is made to : http://mysite.com/blog

*Request is routed to index.php

*$_SERVER[REQUEST_URI] resolves to blog
This is how it is treated on Server Nightmare B:

*

*Request is made to : http://mysite.com/blog

*Apache makes http call to http://mysite.com/index.php

*$_SERVER[REQUEST_URI] resolves to index.php
All I'm trying to do is reroute/write the request to index.php, without $_SERVER[REQUEST_URI] being changed to index.php. In the above example, I would like $_SERVER[REQUEST_URI] to resolve to blog on both Server A and Server B - but it's not working on Server B.
Could someone please tell me why this is happening?


text:
Q: How do I completely close a file if an exception is caught in a using block? I have an application that needs to parse a file, using FileStream. If that file is used by another process, the FileStream initialization throws an IOException. I catch that exception, telling the user to close the file, and I offer to let the user "Retry." Unfortunately, every Retry results in another IOException being thrown, even if the user closed the file. Why is this happening, and how can it be fixed?
I have the FileStream in a using block, and I open the file with FileShare.Read. Since it is inside the using block, it should get disposed when the exception is thrown, shouldn't it?
// Read all the lines in the file and save them to a List
try
{
    using(FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        int count = 0;
        do
        {
            byte[] buffer = new byte[RECORD_LENGTH];
            count = fileStream.Read(buffer, 0, RECORD_LENGTH);
            fileLines.Add(Encoding.ASCII.GetString(buffer));
        } while(fileStream.CanRead && count > 0);
    }
}
catch(IOException)
{
    DialogResult result = MessageBox.Show("There was a problem reading the file:\n" + path +
        "\nPlease ensure it is not used by another process and try again.", "File Error",
        MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
    if(result == DialogResult.Retry)
        ParseFile(path);
    else
        return null;
}

Things I have tried:

*

*Calling the method recursively (as seen above)

*Putting a label before the try block, with goto in place of the recursive method call

*Adding a retryFlag, setting it in the catch block, then recalling ParseFile(path) after the catch block if the flag is on

Each of these solutions ended in the same result: a never-ending cycle of IOExceptions being thrown.

A: So, to directly answer the question asked:
You don't need to, the using block will close the stream.  Behind the scenes using blocks utilize a try-catch-finally and in the finally block they call dispose which will close your stream.
Many of the comments make other good points, but I hope this answers your question.
Something else you may want to try is simply outputting the exception.message instead of overwriting with your own to close file.  The IOException your getting might not be that one...


text:
Q: awk: assigning a shell variable in awk script I have a situation in awk where I need to convert an input format into another format and later use the number of records processed separately. Is there any way I can use a shell variable to get the value of NR in the END section? Something like:
cat file1 | awk 'some processing END{SHELL_VARIABLE=NR}' > file2

Then later use SHELL_VARIABLE outside awk.
I do not want to process the file and then do a wc -l separately as the files are huge.

A: One way: Use the redirection inside your awk command and print your result in the END block. And use command substitution to read the result in a shell variable:
my_var=$(awk '{ some processing; print "your output" >>file2 } END { print NR }' file1)

A: No subprocess can affect the parent's environment variables. What you can do is have awk write output to the file directly, then have it print the value you want to stdout and capture it. Or if you prefer, you could reverse that and have awk just print it to a file and read it back afterwards.
Incidentally, you have a UUOC.
rows=$(awk '{ ...; print > "file2"} END {print NR}' file1)

Or
awk '... END{print NR > "rows"}' file1 >file2
rows=$(<rows)
rm rows


text:
Q: Mouse wheel in VirtualPC (mostly) does not work on 64-bit Windows 7 RC I have recently upgraded my laptop from WinXP Pro (32-bit) to Windows 7 RC (64-bit).  I have a number of VirtualPC 2007 images that I use for testing on various platforms and looking at beta software.  I have installed the 64-bit version of VirtualPC.  The images all work with the exception of the mouse wheel within the virtual machine.  I have tried this out with WinXP Pro, Windows 7 RC, and Windows Server 2008 images.  All are 32-bit and all exhibit the same behavior:  a gentle rotation of the wheel does nothing; a quick rotation of the wheel sometimes gets a scroll and sometimes not.  I regard this behavior as unusable as I tend to use the mouse wheel a lot.  All of this worked just fine on WinXP.  I have re-installed the Virtual machine additions on all of the machines.  The Windows 7 RC virtual image was created after the upgrade to Windows 7 and the 64-bit version of VirtualPC (just to isolate the possibility that I had corrupted the images during the transition).
I have googled, binged, and yahoo-ed.  There are scattered mentions of this problem (dating back to VPC 2004) but no solutions.
I am aware that I could start up one of these images and then use remote desktop connections to get access to that image.  I, in fact, do just that for some development that I am doing; the mouse works just fine.  This is acceptable in this case because I spend hours at a time in the development VM.  These test environments are different in that I will bring up an image for just a short time: minutes rather than hours.  Adding the rdc step is much more significant in these cases.
Does anyone have any idea of what to do next?

A: Well windows 7RC is just an RC, after all. You can't reasonably expect that everything just works.

A: It is a little confusing reading your post (always is with new releases of MS products).
Are you running "Windows Virtual PC" on your new workstation, and not "Virtual PC 2007"?


text:
Q: How do you do the action for a form be null When defining a <form>, it is possible to set the action tag.
How can I set it to null (#), so that it will not actually change the page?

A: A bit hard to understand but I think what you want is this:
<form action="#">
 <!-- code here -->
</form>

A: A <form> tag without an action attribute will send the data to the page it was submitted from.
You only need to use the action attribute if you're sending the form data to a different page.
<form method="GET">
    <input type="text" size="10" name="input" value="default">
    <input type="submit" value="Submit">
</form>

(NOTE: This does not work on the file:/// protocol handler.)

A: For anyone else reading this, it is usually better to have your input or button object return false; when it's clicked. This will make sure the form doesn't follow an action, and instead stays on the page. It would be similar conceptually to what is being asked, as in it will stay on the current page.
This let's you handle submit options in javascript.
Here's an example of how you would submit an email address to your API route, alerting the user what is returned by the API call:
HTML:
<form>
<input type="text" name="email">
<button onclick="do_something(); return false;"
</form>

JAVASCRIPT:
var do_something = function(){
  $.ajax({
    url: "http://myapi.com/route",
    type: 'POST',
    data: $('form').serialize(),
    context: document.body
  }).done(function(data) {
    alert(data);
  });
};

A: You can set form action to null in the following way. This worked for me.
< form action ='' >

A: Try This
<form method="dialog">
    <input type="text" size="10" name="input" value="default">
    <input type="submit" value="Submit">
</form>


text:
Q: Altering display on PHP page from SQL Query I have an SQL query that goes through a search and displays hundred of records for several columns.  However the display for two columns must be change; the Effective Date and the Purge Date.  Currently they are both being displayed like this: (e.g. Aug 29 1991).  I want to change the output to 29-Aug-1991.  I'm not sure how I would do this since it's pulling this data straight from the database into the table.
Please note I'm using MS-SQL and PHP for this project.
This is my SQL Query:
   $sql = "select SerialNum as [Serial Number],ts_sitename As Site,(case m.Scratched
   when 0 then 'Live'
   when 1 then 'Free'
   END) as Status,  Note as Comment, (case Destroyed when 0 then 'NO'
   when 1 then 'YES' END) as [Destroyed],
   SUBSTRING(cast(mg_effectivedate as char), 1, 12) AS [Effective Date],
   SUBSTRING(cast(mg_effectivedate as char), 12, 8) AS [Effective Time],
   SUBSTRING(cast(ScratchedDate as char), 1, 4) + '-' +
   SUBSTRING(cast(ScratchedDate as char), 3, 2) + '-' +
   SUBSTRING(cast(ScratchedDate as char), 5, 2)
   AS [Scratched Date],
   SUBSTRING(cast(ScratchedDate as char), 10, 2) + ':' +
   SUBSTRING(cast(ScratchedDate as char), 12, 2) + ':' +
   SUBSTRING(cast(ScratchedDate as char), 14, 2)
   AS [Scratched Time],
   SUBSTRING(cast(mg_scratchdate as char), 1, 12) AS [Purge Date],
   (select fl_filename from TheFiles_tab where mg_filenum = fl_filenum) as [Dataset],
   (select hs_hostname from TheHosts_tab where mg_hostnum = hs_hostnum) as [Host],
   (select UserCode from [User] where mg_usernum = UserId) as [UserCode]
   from ((Media m left join MediaGenT g on m.MediaId = g.mg_medianum)
   join TheSites_tab s on m.SiteId = s.ts_sitenum)
   join Note n on m.NoteId = n.NoteId
   where SerialNum like '" . $userQuery . "%'";

And this my code to display the two columns:
   echo 'Effective Date	';
   echo 'Purge Date	';

   foreach ($result as $r)
   {
   echo "
";
   echo "".$r['Serial Number'] . " 	";
   echo "".$r['Site'] . " 	";
   echo "".$r['Status'] . "	 ";
   echo "".$r['Comment'] . " 	";
   echo "".$r['Destroyed'] . " 	";
   echo "".$r['Effective Date'] . " 	";
   echo "".$r['Effective Time'] . "	 ";

   echo "";
   if ($r['Scratched Date'] == "") {
   echo "NULL";
   }
   else {
   echo $r['Scratched Date'];
   }  echo "	";

   echo "" ;
   if ($r['Scratched Time'] == "") {
   echo "NULL";
   }
   else {
   echo $r['Scratched Time'];
   }  echo "	";

   echo "".$r['Purge Date'] . " 	";
   echo "".$r['Dataset'] . "	 ";
   echo "".$r['Host'] . " 	";
   echo "".$r['UserCode'] . " 	";
   echo "".$r['NoteId'] . " 	";
   echo "
";
   }

Please note that I'm new to the SO community.  I've always used this website in research but have just created an account for the very first time.

A: If I understand correctly, you simply want to substitute the spaces in the dates for hyphens?
Right now your dates are of the format:
MMM DD YYYY
You want this:
DD-MMM-YYYY
If I remember correctly, in PHP, you can do this:
$effective_date = date("d-M-Y", strtotime($r['Effective Date']));

That converts the database-pulled value to a timestamp, and then formats that timestamp into a new date notation. Look up php's date() function for what other options you have: PHP: date - Manual
Same goes for the other date(s) you want to change.
EDIT
Total PHP code:
echo 'Effective Date	';
echo 'Purge Date	';

foreach ($result as $r)
{
    echo "
";
    echo "".$r['Serial Number'] . " 	";
    echo "".$r['Site'] . " 	";
    echo "".$r['Status'] . "	 ";
    echo "".$r['Comment'] . " 	";
    echo "".$r['Destroyed'] . " 	";
    echo "".date("d-M-Y", strtotime($r['Effective Date'])) . " 	";
    echo "".$r['Effective Time'] . "	 ";

    echo "";
    if ($r['Scratched Date'] == "") {
    echo "NULL";
    }
    else {
    echo $r['Scratched Date'];
    }  echo "	";

    echo "" ;
    if ($r['Scratched Time'] == "") {
    echo "NULL";
    }
    else {
    echo $r['Scratched Time'];
    }  echo "	";

    echo "".date("d-M-Y", strtotime($r['Purge Date'])) . " 	";
    echo "".$r['Dataset'] . "	 ";
    echo "".$r['Host'] . " 	";
    echo "".$r['UserCode'] . " 	";
    echo "".$r['NoteId'] . " 	";
    echo "
";
}


text:
Q: min() function not working on date objects in R I have a working solution to this but I'd really like to understand what is causing this issue in the first place. I have a data frame named 'ngx' with a date column named 'DeliveryDate'.

When I try to find the minimum date of a subset of this data frame:
min(ngx[which(ngx$TradedIndexID == 4810), 2])

I run into this error:
Error in FUN(X[[i]], ...) : only defined on a data frame with all numeric variables

But when I tweak the selection of the 'DeliveryDate' column to:
min(ngx[which(ngx$TradedIndexID == 4810), ]$DeliveryDate)

It works just fine:
[1] "2019-08-01"

Does anyone know the underlying issue causing this?

A: As you mentioned in the comment, your data is of type tibble. That means you could solve the problem by

*

*transforming the data to data.frame prior to your calculations: as.data.frame(ngx)

*doing the same in the tidyverse way:
ngx %>% filter(TradedIndexID == 4810) %>% summarise(Min = min(DeliveryDate))


text:
Q: android.os.TransactionTooLargeException: data parcel size NOUGAT ERROR I am making an api call using RETROFIT, I got the JSON response from the server which is hardly 30kb in size. While the JSON parses the response into a complex Object, it is throwing this error.
java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 1098852 bytes
    at android.app.servertransaction.PendingTransactionActions$StopInfo.run(PendingTransactionActions.java:161)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
 Caused by: android.os.TransactionTooLargeException: data parcel size 1098852 bytes
    at android.os.BinderProxy.transactNative(Native Method)
    at android.os.BinderProxy.transact(BinderProxy.java:510)
    at android.app.IActivityTaskManager$Stub$Proxy.activityStopped(IActivityTaskManager.java:4524)
    at android.app.servertransaction.PendingTransactionActions$StopInfo.run(PendingTransactionActions.java:145)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

If I try to store the response in an Object class, and then get values via LinkedHashMap, I am able to fetch the data. But, it will be a tedious process.
Can anyone please help me to figure out what the issue here is and how to find a solution ?
According to my research this only happens to android devices with version >= Nougat. Below that, it works like a piece of cake.
I have also tried some of the solutions mentioned in:
--> onSaveInstanceState.clear() - but this does not work.
you can find the post here

A: This is the typical error when you put a large amount of data into Bundle of Android.
I would suggest you do it right. The large data has to persistent to disk (either database or files) and you only pass the reference of this data to other places to consume it.
Here you may find 30kb is small, but the actual configuration of size limit for Bundle may be various from different devices/vendors configurations.
The Bundle was meant to keep simple and small data only, don't over-abuse it.


text:
Q: Can't sleep in owned house Completed the quest "Served Cold," but I can't sleep in any of the beds and I can't wait. When I try, I see the message: "You cannot sleep/wait while being asked to leave."

*

*When I execute setcellownership DLC2RRSeverinHouse this issue is not resolved.

*When I execute player.isTrespassing, the value is 0.00

*When I execute getStage DLC2RR02, the value is GetStage >> 200.0 (which is the completed stage for this quest)

Is there a way to fix this?
UPDATE
I've gone back to a previous save (before the Ashfallow Citadel), finished the quest again and find myself with the same results.

A: This is a fairly late answer, so I hope your problem is fixed already.
Are you using the Unofficial Dragonborn patch?
If not, please install it and try the pre-finish save again. The patch fixes a lot of developer bugs that Bethesda haven't got around to fixing. In this case it appears that the quest completion script fails to remove any previous trespassing effects and set full ownership. I'm fairly sure I've been able to sleep there when I last played that part of the game.


text:
Q: Customizing matplotlib image display to add copy/paste I would like to customize matplotlib image display so that i can type control-c and it will copy the image to the clipboard so then i can copy it to openoffice spreadsheet to organize all of my raw data and image results. Is there any way to do this? Thanks!

A: If you're using the wx backend, FigureCanvasWxAgg has  a Copy_to_Clipboard method you can use.  You could bind the CTRL+C key event to call this method.  For an example, see this sample code.

A: import matplotlib
import matplotlib.pyplot as plt
if not globals().has_key('__figure'):
    __figure = matplotlib.pyplot.figure

def on_key(event):
    print event
    if event.key=='c':
        #print event.canvas.__dict__#.Copy_to_Clipboard(event=event)
       # print event.canvas._tkphoto.__dict__
        plt.savefig("/tmp/fig.png")
def my_figure():
    fig = __figure()
    fig.canvas.mpl_connect('key_press_event',on_key)
    return fig
matplotlib.pyplot.figure = my_figure

This works for tk backend, but i have no clue how to copy an image to a clipboard. For text, i can use xclip, but images dont work! And for some reason the wx backend doesnt work too well on ubuntu...


text:
Q: How to record audio with Superpowered SDK on Android Q? I want to record audio with Superpowered SDK on my rooted Android Q device.
As Google has put some restrictions on recording Audio on Android Q so I am trying to port Superpowered SDK Android Example into a Linux executable that I can run on system space bypassing the Android Apps restriction. Please let me know if I am wrong at this point.
For this I have created a simple project with the main class as the following:
#include <string>
#include <OpenSource/SuperpoweredAndroidAudioIO.h>
#include <Superpowered.h>
#include <SuperpoweredSimple.h>
#include <SuperpoweredRecorder.h>
#include <unistd.h>
#include <iostream>
#include <chrono>
#include <thread>

static SuperpoweredAndroidAudioIO *audioIO;
static Superpowered::Recorder *recorder;

// This is called periodically by the audio I/O.
static bool audioProcessing(
    void *clientdata,   // custom pointer
    short int *audio,   // buffer of interleaved samples
    int numberOfFrames, // number of frames to process
    int samplerate      // current sample rate in Hz
)
{
    std::cout << "------- Processing Audio...numberOfFrames:" << numberOfFrames << " audio:" << *audio << std::endl;
    float floatBuffer[numberOfFrames * 2];
    Superpowered::ShortIntToFloat(audio, floatBuffer, (unsigned int)numberOfFrames);
    recorder->recordInterleaved(floatBuffer, (unsigned int)numberOfFrames);
    return false;
}

// StartAudio - Start audio engine.
void startAudio(
    unsigned int samplerate,
    int buffersize,
    const char *temp,
    const char *dest)
{
    Superpowered::Initialize(
        "ExampleLicenseKey-WillExpire-OnNextUpdate",
        false, // enableAudioAnalysis (using SuperpoweredAnalyzer, SuperpoweredLiveAnalyzer, SuperpoweredWaveform or SuperpoweredBandpassFilterbank)
        false, // enableFFTAndFrequencyDomain (using SuperpoweredFrequencyDomain, SuperpoweredFFTComplex, SuperpoweredFFTReal or SuperpoweredPolarFFT)
        false, // enableAudioTimeStretching (using SuperpoweredTimeStretching)
        false, // enableAudioEffects (using any SuperpoweredFX class)
        false, // enableAudioPlayerAndDecoder (using SuperpoweredAdvancedAudioPlayer or SuperpoweredDecoder)
        false, // enableCryptographics (using Superpowered::RSAPublicKey, Superpowered::RSAPrivateKey, Superpowered::hasher or Superpowered::AES)
        false  // enableNetworking (using Superpowered::httpRequest)
    );

    // Initialize the recorder with a temporary file path.
    recorder = new Superpowered::Recorder(temp);
    // Start a new recording.
    recorder->prepare(
        dest,       // destination path
        samplerate, // sample rate in Hz
        true,       // apply fade in/fade out
        1           // minimum length of the recording in seconds
    );

    std::cout << "Initializing audioIO..\n";
    // Initialize audio engine with audio callback function.
    audioIO = new SuperpoweredAndroidAudioIO(
        samplerate,      // native sampe rate
        buffersize,      // native buffer size
        true,            // enableInput
        false,           // enableOutput
        audioProcessing, // process callback function
        nullptr          // clientData
    );
}

// StopAudio - Stop audio engine and free audio buffer.
void stopRecording()
{

    std::this_thread::sleep_for(std::chrono::seconds(60));

    recorder->stop();
    std::cout << "Deleting IO\n";
    delete audioIO;

    // Wait until the recorder finished writing everything to disk.
    // It's better to do this asynchronously, but we're just blocking (sleeping) now.
    std::cout << "Finishing..\n";
    while (!recorder->isFinished())
        usleep(100000);

    //    __android_log_print(ANDROID_LOG_DEBUG, "Recorder", "Finished recording.");
    std::cout << "Deleting Recorder\n";
    delete recorder;
}

// onBackground - Put audio processing to sleep if no audio is playing.
void onBackground()
{
    audioIO->onBackground();
}

// onForeground - Resume audio processing.
void onForeground()
{
    audioIO->onForeground();
}

int main(int, char **)
{
    std::cout << "Hello, AudioRecorder!\n";

    unsigned int samplerate = 48000;
    int buffersize = 192;
    const char *temp = "/system/recording/temp.wav";
    const char *dest = "/system/recording/final.wav";

    std::cout << "Starting recording::"
              << "\n\tsamplerate:" << samplerate
              << "\n\tbuffersize:" << buffersize
              << "\n\ttemp:" << temp
              << "\n\tdest:" << dest
              << std::endl;
    startAudio(samplerate, buffersize, temp, dest);
    onForeground();

    std::cout << "Starting thread to stop recording...\n";
    std::thread stopThread(&stopRecording); // thread starts running

    std::cout << "Stoping recording...\n";
    stopThread.join(); // main thread waits for the thread t to finish

    std::cout << "Returning from main\n";
    return 0;
}

I am trying to record a 1 minute audio with the above code. But I can't get any call to audioProcessing function. When I run the above code then I get the following output:
OnePlus7Pro:/system # ./xbin/audio_recorder
Hello, AudioRecorder!
Starting recording::
        samplerate:48000
        buffersize:192
        temp:/system/recording/temp.wav
        dest:/system/recording/final.wav
Initializing audioIO..
Starting thread to stop recording...
Stoping recording...
Deleting IO
Finishing..
^C
130|OnePlus7Pro:/system # cd recording
OnePlus7Pro:/system/recording # ls -l
total 0
-rw-r--r-- 1 root root 0 2020-01-08 12:34 temp.wav
-rw-r--r-- 1 root root 0 2020-01-08 12:34 temp.wav.txt

After "Finishing.." it doesn't print "Deleting Recorder" so there is some issue in the code but I am not getting it.
I am an Android Developer and new to c++. Is there anyone who can guide me?


text:
Q: ValueError: unknown url type: 'LanguageTool-3.2.zip' I am trying to install pycontractions library which is dependent on language-check library. So when installing language-check I am getting the below error
ValueError: unknown url type: 'LanguageTool-3.2.zip

I have python-3.10 and java-8 installed. When I am using pip install language-check, I get urllib.error.HTTPError: HTTP Error 403: Forbidden So, I downloaded language tool manually(as instructed in github link) and run the following command:
pip install git+https://github.com/myint/language-check

I tried all the possible ways available here but still couldnt resolve it. Its getting installed on mac with no issues but I am a windows user. So I need to install it in my windows desktop.
Error:
Collecting git+https://github.com/myint/language-check.git
  Cloning https://github.com/myint/language-check.git to c:\users\skamble\appdata\local\temp\pip-req-build-c78lrf2e
  Running command git clone --filter=blob:none -q https://github.com/myint/language-check.git 'C:\Users\skamble\AppData\Local\Temp\pip-req-build-c78lrf2e'
  Resolved https://github.com/myint/language-check.git to commit 58e419833ef28a9193fcaa21193616a8a14504a9
  Preparing metadata (setup.py) ... done
Using legacy 'setup.py install' for language-check, since package 'wheel' is not installed.
Installing collected packages: language-check
    Running setup.py install for language-check ... error
    ERROR: Command errored out with exit status 1:
     command: 'C:\Users\skamble\AppData\Local\Programs\Python\Python310\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\skamble\\AppData\\Local\\Temp\\pip-req-build-c78lrf2e\\setup.py'"'"'; __file__='"'"'C:\\Users\\skamble\\AppData\\Local\\Temp\\pip-req-build-c78lrf2e\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\skamble\AppData\Local\Temp\pip-record-msctmso8\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\skamble\AppData\Local\Programs\Python\Python310\Include\language-check'
         cwd: C:\Users\skamble\AppData\Local\Temp\pip-req-build-c78lrf2e\
    Complete output (23 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\skamble\AppData\Local\Temp\pip-req-build-c78lrf2e\setup.py", line 595, in <module>
        sys.exit(main())
      File "C:\Users\skamble\AppData\Local\Temp\pip-req-build-c78lrf2e\setup.py", line 590, in main
        run_setup_hooks(config)
      File "C:\Users\skamble\AppData\Local\Temp\pip-req-build-c78lrf2e\setup.py", line 561, in run_setup_hooks
        language_tool_hook(config)
      File "C:\Users\skamble\AppData\Local\Temp\pip-req-build-c78lrf2e\setup.py", line 584, in language_tool_hook
        download_lt()
      File "C:\Users\skamble\AppData\Local\Temp\pip-req-build-c78lrf2e\download_lt.py", line 131, in download_lt
        with closing(urlopen(url)) as u:
      File "C:\Users\skamble\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 216, in urlopen
        return opener.open(url, data, timeout)
      File "C:\Users\skamble\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 503, in open
        req = Request(fullurl, data)
      File "C:\Users\skamble\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 322, in __init__
        self.full_url = url
      File "C:\Users\skamble\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 348, in full_url
        self._parse()
      File "C:\Users\skamble\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 377, in _parse
        raise ValueError("unknown url type: %r" % self.full_url)
    ValueError: unknown url type: 'LanguageTool-3.2.zip'
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'C:\Users\skamble\AppData\Local\Programs\Python\Python310\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\skamble\\AppData\\Local\\Temp\\pip-req-build-c78lrf2e\\setup.py'"'"'; __file__='"'"'C:\\Users\\skamble\\AppData\\Local\\Temp\\pip-req-build-c78lrf2e\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\skamble\AppData\Local\Temp\pip-record-msctmso8\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\skamble\AppData\Local\Programs\Python\Python310\Include\language-check' Check the logs for full command output.

A: I resolved it. Used git+https://github.com/coreyryanhanson/language-check and it worked.


text:
Q: Get Hidden Field in Code Behind I have been looking at answers here and other places but so far have not found exactly how to do this.
I have the following definition for a hidden field in my .aspx page:
<asp:HiddenField ID="hfAddressChange" runat="server" />

I set the value in a javascript function on the client:
function confirmAddressChange()
{
    if (typeof document.forms[0].hfAddressChange.valueOf ==="undefined")
    {
     var res = (confirm('"Update Contact Addresses to Rich?"')==true);
     document.forms[0].hfAddressChange.valueOf = res;
    }
}

Basically I only want to set the value once.
Now I want to check the value in the code behind:
If hfAddressChange.Value <> String.Empty Then
    Dim x As String = "Do Something here"

End If

However, even though I have verified that the value IS being set in the js function, it is always an empty string when it gets to my code behind.
Anyone see what the heck I'm doing wrong?

A: document.forms[0].hfAddressChange.valueOf = res;

The property is value, not valueOf. (And it won't be undefined earlier, either; just check !document.forms[0].hfAddressChange.value.)