text:
Q: Is the instruction after a RET always the one after CALL? In a well-behaved C program, shall the return statement (RET) always return to the instruction following the CALL statement? I know this is the default, but I would like to check if anyone knows or remembers authentic examples of cases where this standard does not apply (common compiler optimization or other things...). Someone told me that it could happen with a function pointer (the function pointer would put the value on the stack, instead of the CALL... I searched for it but I did not see an explanation anywhere).
Let me try to better explain my question. I know that we can use other structures to change the execution flow (including manipulating the stack)... I understand that if we change the return address written on the stack the execution flow will change to the address that was written on the stack. What I need to know is: is there any not unusual execution situation where the next instruction is not the one that follows the CALL? I mean, I would like to be sure that it doesn't happen, unless something unexpected occurs (like a memory access violation that would lead to a structured exception handler).
My concern is whether the commercial application programs in general ALWAYS follow the mentioned pattern. Notice that in this case I have a fixation for exceptions (it is important to know whether they exist in this case, for a research project I'm developing into a M. Sc. program's discipline). I know, for example, that a compiler may, sometimes, change a RET to a JMP (tail-call optimization). I would like to know if something like this may change the order of the instruction that is executed after the RET and, mainly, if the CALL will always be just before the instruction executed after the RET.

A: CALL subroutine address is equivalent to
PUSH next instruction address + JMP subroutine address.
At the same time, PUSH address is nearly equivalent to
SUB xSP, pointer size + MOV [xSP], address.
SUB xSP, pointer size can be replaced by PUSH.
RET is nearly equivalent to
JMP [xSP] followed by ADD xSP, pointer address at the location where JMP leads.
And ADD xSP, pointer address can be replaced by POP.
So, you can see what kind of basic freedom the compiler has. Oh, btw, it can optimize your code such that your function is entirely inlined and there's neither a call to it, nor a return from it.
While somewhat perverse, it's not impossible to devise much weirder control transfers using instructions and techniques highly specific to the platform (CPU and OS).
You can use IRET instead of CALL and RET for control transfer, provided you put the appropriate stuff on the stack for the instruction.
You can use Windows Structured Exception Handling in a way that an instruction that causes a CPU exception (e.g. division by 0, page fault, etc) diverts execution to your exception handler and from there control can be transferred either back to that same instruction or to the next or to the next exception handler or to any location. And most of x86 instructions can cause CPU exceptions.
I'm sure there are other unusual ways for control transfer to, from and within subroutines/functions.
It's not uncommon to see code something like this either:
...
CALL A
A: JMP B
db "some data", 0
B: CALL C ; effectively call C with a pointer to "some data" as a parameter.
...

C:
; extracts the location of "some data" from the stack and uses it.
...
RET

Here, the first call isn't to a subroutine, it's just a way to put on the stack the address of the data stuck in the middle of the code.
This is probably what a programmer would write, not a compiler. But I may be wrong.
What I'm trying to say with all this is that you shouldn't expect to have CALL and RET as the only ways to enter and leave subroutines and you shouldn't expect them to be used for that purpose only and balance each other.

A: A "well behaved" C program could be translated by a compiler to a program that does not follow this pattern.   For example for obfuscation reasons the code could use a push / ret combination instead of a jmp.

A: Excluding virtual memory situations (where a RET may cause a page fault, technically meaning that the thing the RET triggers is the fault handler), I think the main thing worth discussing is that setjmp and longjmp may completely subvert the stack — so you can legitimately CALL something, then have it hop back an arbitrary number of stack frames without ever hitting the RETs.
I guess it's quite conceivable that a longjmp implementation may involve a RET with a modified stack — it'd be up to the vendor on how they wanted to implement that.

A:
In a well-behaved C program, shall the return statement (RET) always return to the instruction following the CALL statement?

This is kind of a non sequitur because there's nothing that requires calling a function and returning from it to necessarily map to these instructions, though of course it's quite common.  One example of that is when a function gets inlined.
I think it would be very unusual for an x86 targeting compiler to rig things so a ret instruction corresponding to a return statement went somewhere other than the address following the call instruction. But that's something I think might happen occasionally on an ARM processor.
Since an ARM instruction can't always contain a full 32-bits of immediate data, it's common for constants (numeric or string) to be 'embedded' as data in the code stream so the value or a pointer to it can be loaded using a pc (program counter) relative address.  Usually these constants are located at a spot where a jump doesn't need to be made just because of the data. One of the more common places for such data would be in the area between the code for two functions. But another spot where that condition holds after a branch made for a function call, since a branch needs to be taken in any case to get to the instructions following the call site (the return from the function).  So, it doesn't hurt execution time to place the data just after the call and set the return address to be the address that follows the data.  The compiler loads the lr register (which is used by convention to hold the return address) with the address following the data, then issues an unconditional branch to the function. You might not see this too often, but similar techniques to place data in the code segment are common on the ARM.

A: Theoretically, a compiler could, given the following code:
return f(), g();

generate assembly along the lines of:
push $g
jmp f

A: Maybe.  On some processors there is something called a "delay slot" (sometimes two) which are instructions immediately following branch instructions (including CALL) which are executed as if they were at the target of the branch.  This apparent nonsense was added to increase performance, since the instruction pre-fetcher has quite often fetched ahead of the branch instruction by the time it realizes there is a branch.  The address pushed by a CALL as the return address is not the address following the CALL if there are delay slot instructions, the return address is the address following the delay slot instruction(s).
http://en.wikipedia.org/wiki/Delay_slot
This introduced complexity in the Instruction Set Architecture (ISA) for that machine, for example what happens if you place branches in the delay slots, what happens if an instruction in the delay slot causes a fault?  What happens if there is a trap (like a single step trap)?
You can see it gets messy... but a surprising number of older RISC processors have that, like MIPS, SPARC, and PA-RISC.


text:
Q: Question about pulse transformer I understand transformers only work with AC because there is electromagnetic induction only when the current going through is AC. In switch-mode power supplies, the pulse transformers are powered by high frequency signals generated by MOSFETs which means they can be smaller because the high frequency will compensate for the missing inductance.
I also learned that, when the output voltage drops (due to a load in the secondary), the PWM controller increases the duty cycle of the signal generated by the MOSFETs, in order to compensate and keep the voltage constant. However, the frequency of the signal is the same. Given that transformers only work with AC and that the frequency of ON/OFF switching of the MOSFETs (variation) is the same when the duty cycle is increased, how does that result in higher output power?

A: My observations plus your comments suggest that in a switching power supply, the step down transformer is powered from a rectified standard AC, fed to the transformer in the form of high frequency pulses.  If the frequency is fixed, then the power can be varied by changing the width of each pulse.

redpajama_set_name: RedPajamaStackExchange


text:
Q: while inserting data to a mysql database using Php. I'm getting an error saying Incorrect integer value: '' for column 'rate' at row 1 1.Php code is as follows and i do not have an auto increment field
full error description

ERROR: Could not able to execute INSERT INTO employee( emp_name, rate,
  ifsc_code, acc_num, acc_holder_name) VALUES ( '', '', '', '', '').
  Incorrect integer value: '' for column 'rate' at row 1

 <?php

include_once('connectdb.php');

$emp_name = mysqli_real_escape_string($link, $_REQUEST['emp_name']);
$rate = mysqli_real_escape_string($link, $_REQUEST['rate']);
$ifsc_code = mysqli_real_escape_string($link, $_REQUEST['ifsc_code']);
$acc_num = mysqli_real_escape_string($link, $_REQUEST['acc_num']);
$acc_holder_name = mysqli_real_escape_string($link, $_REQUEST['acc_holder_name']);

$sql = "INSERT INTO employee(   emp_name,
                                rate,
                                ifsc_code,
                                acc_num,
                                acc_holder_name)

        VALUES              (   '$emp_name',
                                '$rate',
                                '$ifsc_code',
                                '$acc_num',
                                '$acc_holder_name')";

if(mysqli_query($link, $sql)){

    //echo "<script type='text/javascript'>alert('Commodity added to inventory')</script>";
    echo "<meta http-equiv='refresh' content='0;url=insert_emp_details.php'>";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

mysqli_close($link);

?>

A: As per my comments you should convert $rate into integer or remove ' single quotes like this
$sql = "INSERT INTO employee(   emp_name,
                                rate,
                                ifsc_code,
                                acc_num,
                                acc_holder_name)

        VALUES              (   '$emp_name',
                                $rate,
                                '$ifsc_code',
                                '$acc_num',
                                '$acc_holder_name')";

Or
you can convert into integer like this $rate= (int)$rate;
Also use pdo with bind parameter function for prevent sql injection

A: As noted above in a comment the original code is potentially vulnerable to SQL injection so the use of a prepared statement would be advised to help mitigate risk.
The error message you posted though concerns me - it appears that all the values are empty... is that the case? You should check for the existence of these variables before attempting the sql operations.
<?php

    include_once('connectdb.php');

    try{

        $sql='insert into `employee` ( `emp_name`, `rate`, `ifsc_code`, `acc_num`, `acc_holder_name` ) values (?,?,?,?,?);';

        /* field names expected in REQUEST array and associated data type for filtering */
        $args=array(
            'emp_name'          =>  FILTER_SANITIZE_STRING,
            'rate'              =>  FILTER_SANITIZE_NUMBER_INT, /* assumed that rate is an integer */
            'ifsc_code'         =>  FILTER_SANITIZE_STRING,
            'acc_num'           =>  FILTER_SANITIZE_NUMBER_INT, /* assumed that acc_num is an integer ?? */
            'acc_holder_name'   =>  FILTER_SANITIZE_STRING
        );
        /* filter REQUEST array using above arguments */
        filter_input_array( INPUT_REQUEST, $args );

        /* extract variables */
        extract( $_REQUEST );

        /* If all the variables were extracted correctly after filtering - proceed */
        if( $emp_name && $rate && $ifsc_code && $acc_num && $acc_holder_name ){

            /* if the filter failed this will probably never be called but... */
            if( !is_integer( $rate ) ) throw new Exception('rate is not an integer');

            /* create a prepared statement */
            $stmt=$link->prepare( $sql );

            /* If the query failed for some reason - abandon ship */
            if( !$stmt )throw new Exception( sprintf( 'error preparing sql query: %s', $stmt->error ) );

            /* assumed that rate and acc_num is an integer ?? */
            $stmt->bind_param( 'sisis', $emp_name, $rate, $ifsc_code, $acc_num, $acc_holder_name );

            /* execute the query */
            $result = $stmt->execute();
            if( $result ){

                echo "Success";

            } else {
                throw new Exception( sprintf( "Bogus! %s", $stmt->error ) );
            }
        } else {
            throw new Exception( 'an error occurred extracting one or more variables - check "$args" array!' );
        }

    } catch( Exception $e ){
        exit( $e->getMessage() );
    }
?>


text:
Q: jquery each if value exists append to previous value I have a list of events and venues which I am rendering in a google map. see fiddle
    var mylatlongs = [
                        {"confid":"1","venueid":"1","date":"2014-09-09","venue":"Venue 1","name":"Conference 1","lat":"34.042435","lng":"-118.266586"},
                        {"confid":"2","venueid":"2","date":"2014-10-10","venue":"Venue 2","name":"Conference 2","lat":"34.052778","lng":"-118.255833"},
                        {"confid":"3","venueid":"3","date":"2014-11-11","venue":"Venue 3","name":"Conference 3","lat":"34.050592","lng":"-118.242663"},
                        {"confid":"4","venueid":"1","date":"2014-12-12","venue":"Venue 1","name":"Conference 4","lat":"34.042435","lng":"-118.266586"}
                    ];
    var infowindow = null;
    jQuery(function() {
            var StartLatLng = new google.maps.LatLng(mylatlongs[0]['lat'], mylatlongs[0]['lng']);
            var mapOptions = {
                center: StartLatLng,
                streetViewControl: false,
                panControl: false,
                maxZoom:17,
                zoom : 14,
                zoomControl:true,
                zoomControlOptions: {
                    style:google.maps.ZoomControlStyle.SMALL
                }
            };

        var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

        var infowindow = new google.maps.InfoWindow({
            content: ''
        });

        jQuery.each( mylatlongs, function(i, m) {
            var StartLatLng = new google.maps.LatLng(30.984298 , -91.962333);
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(m.lat, m.lng),
                bounds: true,
                id : 'mk_' + m.confid,
                letter : m.index,
                map: map,
                title: m.name
            });

            google.maps.event.addListener(marker, 'click', function() {
                infowindow.close();
                infowindow.setContent(contentString);
                infowindow.open(map,marker);
            });

            var desc = m.date + " -- " + m.name;
            /*
            if (venueid already exists) {
            keep the one pin for the venue and append each name and date into the description seperated by a

            }
            */

            var contentString = '
'+
              '
'+
              '
'+
              '
'+ m.venue + '
'+
              '
' + desc + '
'+
              '
';

        });
    });

This works well except if there is multiple events at the one venue.
I have looked at clustering and Spiderfier which give the option to break out the pins into multiple pins, but what I want to do is in my contentString add each event in the one venue.
So with my example data
The popup description should have the below content.

Venue 1

            2014-09-09 -- Conference 1

            2014-12-12 -- Conference 4

Venue 2

            2014-10-10 -- Conference 2

Venue 3

            2014-11-11 -- Conference 3

At the moment it has two pins on top of each other and when you click on it you get the last rendered pin (the latest event).
Is there a way to do this within the each with js or does the structure of the data in mylatlongs need to change.

A: possible approach:

*

*create an object where you store the markers:
   var markers={};

*When you store the markers inside this object use the venueid as property-name and store the desired properties as marker-properties, for the descs use an array:
 //inside loop:

   //when there isn't a marker for the venue
   //create the marker
   if(!markers[m.venueid]){
        //create the marker
        markers[m.venueid]=new google.maps.Marker({
            position: new google.maps.LatLng(m.lat, m.lng),
            bounds: true,
            id : 'mk_' + m.confid,
            letter : m.index,
            map: map,
            title: m.name,
            venue:m.venue,
            descs:[]
        });
        google.maps.event.addListener(markers[m.venueid], 'click', function() {
            infowindow.close();
            infowindow.setContent('
'+
          '
'+
          '
'+
          '
'+this.venue + '
'+
          '
' + this.descs.join('
') + '
'+
          '
');
            infowindow.open(map,this);
        });
      }

*push the desc to the descs-property of the marker:
 markers[m.venueid].descs.push(m.date + " -- " + m.name)

Result: http://jsfiddle.net/rf48gvz5/8/


text:
Q: Two different electrostatic charges in rotation It's a theoretical problem. I mean I drawn a circle and I consider this circle exist.
I would like to understand how works this device composed of a circle and two charges:

Two charges fixed on a circle, one positive, one negative turn at the same angular velocity. The circle is free to move or rotate.
Each charge will give a magnetic field and this field will interact with the other charge.
Does the device moves in linear velocity ?
Does the device rotates in another axis ?
Does the device be in a stable position or vibrates ?
I need a little help for understood how a charge can interact with the other.
The velocity of the charge is $30000 km/s$ and the radius of the circle is $1e-22 m$. I choose value for cancel the centrifugal force with the electrostatic force. So, the charge is $1.6e-19C$ and the mass is around $2.5e-21kg$. Maybe it's possible to choose anothers datas, just cancel the centrifugal force and the electrostatic force. But, if it's possible I would like to study this device like that.

A: There are two aspects of this question,one charge part and the other mass part. If you consider charge part,we see that magnetic force on + ball due to -ve ball and on -ve ball due to +ve ball both act upward,so the torque gets canceled and since these forces are internal, they will not make any change in momentum of system. The attractive forces of charges are acting along radius and thus will also not produce any momentum. Now coming to mass aspect, since the external force on system is zero and angular momentum is also constant, therefore it would also not make any change in momentum and thus the device will not rotate on any axis nor will it have any linear velocity. Take care:-)

A: At the level of magnetic & electric forces, there's really no change.  At the moment that is depicted above, the negative charge will feel a magnetic field pointing into the page;  and so it will feel an additional attractive force towards the positive charge.  If the charges are held at a fixed distance by a rigid rod, this would cause a slight change in the tension required of the rod, but nothing more.
However, that's not the interesting answer.  The interesting answer is that this is an accelerating dipole, and so it will emit energy in the form of electromagnetic waves.  Thus, the rotation will slow down and eventually stop.  This is not easy to see on the level of magnetic and electric forces acting on the charges;  to actually see it, you have to take into account the amount of time necessary for electromagnetic "news" to travel around the system at the speed of light.  Nevertheless, once you do this, you'll find that the charges will slow down.  I believe that in this case, you'll end up with $\omega \propto 1/\sqrt{t}$ for long amounts of time, but I'd have to go through the math more carefully to check.


text:
Q: sendGrid set headers/content type I'm looking to use sendGrid to create an outlook meeting request.
I need to be able to set the content type (header) to something specific, however does anyone know how I can do this? I presume I am to use the x-smtpapi, whilst accepting a json string.
Here is what I currently have.
$json_string = array(
'Content-Type' => array(
    'text/calendar; Content-Disposition: inline; charset=utf-8;\r\n',
    'text/plain;charset=\"utf-8\"\r\n'
));

Many thanks

A: Unfortunately, using SendGrid Web API there is no way to change the content type yet.

In Web API, there's no way to force the content-type. In SMTP however, we'll respect whatever you set it to.

Reference: this SendGrid support engineer answer
Edit:
The answer is 2 years old. You may have better luck asking again on https://community.sendgrid.com/sendgrid


text:
Q: Model parallelism in Keras I am trying to implement model parallelism in Keras.
I am using Keras-2.2.4
Tensorflor-1.13.1
Rough structure of my code is :
import tensorflow as tf
import keras
def model_definition():
input0 = Input(shape = (None, None))
input1 = Input(shape = (None, None))
with tf.Session(config=tf.ConfigProto(allow_soft_placement=False, log_device_placement=True)):
model = get_some_CNN_model()
with tf.device(tf.DeviceSpec(device_type="GPU", device_index=0)):
op0 = model(input0)
with tf.device(tf.DeviceSpec(device_type="GPU", device_index=1)):
op1 = model(input1)
with tf.device(tf.DeviceSpec(device_type="CPU", device_index=0)):
concatenated_ops = concatenate([op0, op1],axis=-1, name = 'check_conc1')
mixmodel = Model(inputs=[input0, input1], outputs = concatenated_ops)
return mixmodel

mymodel = model_definition()
mymodel.fit_generator()

Expected result: While training, computations for op0 and op1 should be done on gpu0 and gpu1, respectively.
Problem 1: When I have 2 gpus available, the training works fine. nvidia-smi shows that both gpus are being used. Though I am not sure if both gpus are doing their intended work. How to confirm that?
Because, even I set log_device_placement as True, I don't see any task allocated to gpu 1
Problem 2: When I run this code on a machine with 1 GPU available, still it runs fine. It is expected show an error because GPU 1 is not available.
The example shown here works fine as expected. It doesn't show the problem 2, i.e. on single GPU, it raises an error.
So I think some manipulation is happening inside keras.
I have also tried using import tensorflow.python.keras instead of import keras, in case it is causing any conflict.
However, the both problems persist.
Would appreciate any clue about this issue. Thank you.


text:
Q: Calling controllers method from page with asp-action Whatever I do the button bellow always calls the OnGetAsync() method of the controller, not the desired SetEditMode()
Controller/Model code:
public class DetailsModel : PageModelBase
{
    private readonly ICommunicationService communicationService;

    public DetailsModel(ICommunicationService communicationService)
    {
        this.communicationService = communicationService;
    }

    public bool IsEditMode { get; set; } = false;

    public EmployeeProfileData EmployeeProfileData { get; set; }

    public async Task OnGetAsync()
    {
        this.EmployeeProfileData = await this.communicationService.GetEmployeeProfileData();
    }

    [HttpGet(nameof(SetEditMode))]
    public IActionResult SetEditMode()
    {
        this.IsEditMode = true;
        return Page();
    }
}

View code:
@page
@using Common.Resources
@model PersonalProfile.DetailsModel
@{
    ViewData["Title"] = TextResources.Profile;
}

@TextResources.EmployeeProfileData

    @if (!Model.IsEditMode)
    {

            Edit

    }

A: You are working with a Razor Page, rather than a Controller. In your example, you're confusing Razor Pages routing with the attribute-based routing approach used with Controllers.
For this to work, you can use a Named Handler Method, which follows a convention of On[Verb][Handler]. Here's an example:
public IActionResult OnGetSetEditMode()
{
    this.IsEditMode = true;
    return Page();
}

Note that I've also removed the HttpGet attribute above.
With this change, the .cshtml file needs to be updated to use the new handler:
Edit

Note that I've also removed the method attribute in this case, as a elements trigger GET requests by design.


text:
Q: Object composition vs providing explicit wrappers I have a class A that looks like this:
class A {
// A's internal state
public:
  void someMethod();
  void anotherMethod();
};

I want to use A inside another class B. I don't want B to be a subtype of A, but I want A's public methods to be accessible in some form to B's users.
One way to accomplish this is by simply including an instance of A as a public member of B:
class B {
public:
  A a;
  // other members
};

Another is to have A be a private member of B, and provide wrappers around A's public methods:
class B {
  A a;
public:
  void someMethod(){ a.someMethod(); }
  void anotherMethod(){ a.anotherMethod(); }
}

I'd like to know if there's a "preferred" way of doing this (or even one that might not involve the two alternatives above), or if it's simply a matter of preference. Thanks.

A: Yet another way is to do:
class B : private A
{
public:
    using A::someMethod;
    using A::anotherMethod;
};

A:
I'd like to know if there's a "preferred" way of doing this (or even one that might not involve the two alternatives above), or if it's simply a matter of preference. Thanks.

It really comes down to specifics here I'm afraid.
You're right in preferring composition over inheritance when inheritance doesn't make sense.  How you implement that depends on whether or not it makes sense to make an instance of A public.
Is there any state in A that you do not want changed, or functions that you do not wish to be public?  Do you wish to perform any pre- or post-pocessing when one of A's functions are called?  Do you care is users set your instance of A to another?  You probably do (though you could just make a getter function), so in this case prefer wrapping the functions.
Does it make more sense for A to be completely public?  If so you save time by not writing a bunch of boilerplate code.
It really comes down to the semantics of your wrapper class here.


text:
Q: Why won't these cross-referenced classes compile when split into different files? I have two classes that reference each other. Class B has a list of pointers to A objects and each A object requires a pointer to the B object that created it. Why does this compile when written in a single file but not when split into multiple files?
namespace.h
#ifndef NAMESPACES_H
#define NAMESPACES_H

#include "A.h"
#include "B.h"
#include "C.h"

namespace NAMESPACE
{
    class A;
    class B;
    class C;
}
#endif

A.h
#ifndef A_H
#define A_H
#include "namespaces.h"
#include <iostream>

namespace NAMESPACE{
class A
{
private:
    int x;
    B* ptrB;
public:
    void print();
    A(int g_x, B* g_ptrB);
};
}

#endif

A.cpp
#include "A.h"

namespace NAMESPACE{

A::print()
    {
        std::cout<<"I am class A, my x = "<<x<<std::endl;
    }
    A::A(int g_x, B* g_ptrB)
    {
        x = g_x;
        ptrB = g_ptrB;
    }
}

B.h
#ifndef B_H
#define B_H

#include "namespaces.h"
#include <vector>
#include <iostream>
namespace NAMESPACE{

class B
{
private:
    std::vector<A*> vA;
public:
    B(int g_x);
    void print();
};
}

#endif

B.cpp
#include "B.h"

namespace NAMESPACE{

B::B(int g_x)
    {
        vA.push_back(new A(g_x, this));
    }
    void B::print()
    {
        std::cout<<"I am class B\n";
        vA[0]->print();
    }
}

main.cpp
#include <iostream>
#include "namespaces.h"

int main()
{
    B *b = new B(3);
    b->print();
    return 0;
}

/* By contrast, this single .cpp file compiles just fine */
#include <iostream>
#include <vector>
class B;
class A
{
private:
    int x;
    B* ptrB;
public:
    void print()
    {
        std::cout<<"I am class A, my x = "<<x<<std::endl;
    }
    A(int g_x, B* g_ptrB)
    {
        x = g_x;
        ptrB = g_ptrB;
    }
};

class B
{
private:
    std::vector<A*> vA;
public:
    B(int g_x)
    {
        vA.push_back(new A(g_x, this));
    }
    void print()
    {
        std::cout<<"I am class B\n";
        vA[0]->print();
    }
};

class C:public A
{
public:
    C(int g_x, B* g_ptrB):A(g_x, g_ptrB){}
};

int main()
{
    B *b = new B(3);
    b->print();
    return 0;
}

When compiling the separate files, I get a lot of errors like
In file included from namespaces.h:4:0,
                 from B.h:4,
                 from B.cpp:1:
A.h:11:2: error: 'B' does not name a type
  B* ptrB;
  ^
A.h:14:13: error: 'B' has not been declared
  A(int g_x, B* g_ptrB);
             ^
In file included from namespaces.h:6:0,
                 from B.h:4,
                 from B.cpp:1:
C.h:10:13: error: 'B' has not been declared
  C(int g_x, B* g_ptrB):A(g_x, g_ptrB){}

But when compiling a single file, it all runs smoothly and I get
I am class B
I am class A, my x = 3

How come?


text:
Q: Response PHP is empty I use jquery to call two url in file indexFunctions.php but the response of server is empty i dont know why please help there is my code
$("#start_peering").submit(function(event){
    $("#wait").html('<img src="ajax-loader.gif">');
    event.preventDefault();
    $.ajax({
            url : 'indexFunctions.php',
            type : 'POST',
            data : {peering:true},
            success : function(data){
                    $("#StbStatus").html(data);
                    $.ajax({
                            url : 'indexFunctions.php',
                            type : 'POST',
                            data : {test_params:true},
                            success : function(data){
                                    $("#results").html(data);
                                    $("#wait").html('');
                                    }
                             });

            }
    });

});

File indexFunctions.php
$rpi="http://192.168.1.15";

  if (isset($_POST['peering']) && isset($_POST['test_params']))
{
  $url = $rpi."/peering.php?askSTB=true";
  $response = proxy::get($url);
  echo $response;
  $url = $rpi."/installUSBKeyOnStb.php";
  $response = proxy::get($url);
  echo $response;

 }

 ?>

Thank you in advance.

A: You seem to be sending two request but checking if both are set at the same time.
if (isset($_POST['peering']) && isset($_POST['test_params']))

You should check for either or not both.
Try changing it to:
if (isset($_POST['peering']) || isset($_POST['test_params']))

A: You used AND && instead of OR ||


text:
Q: How to filter by value field in a pivot table? I am trying to filter "Sum of TEST" value field in my pivot table.
An error message

Application-defined or object-defined error

shows up at line number 4.
ActiveSheet.PivotTables("PivotTable1").PivotFields("Sum of TEST").PivotFilters.Add _
  Type:=xlValueIsGreaterThan, Value1:=30

Private Sub Filter()
    Application.ScreenUpdating = False
    ActiveSheet.PivotTables("PivotTable1").ManualUpdate = True
    ActiveSheet.PivotTables("PivotTable1").PivotFields(2).ClearAllFilters
    ActiveSheet.PivotTables("PivotTable1").PivotFields("Sum of TEST").PivotFilters.Add _
      Type:=xlValueIsGreaterThan, Value1:=30
    ActiveSheet.PivotTables("PivotTable1").ManualUpdate = False
    Application.ScreenUpdating = True
End Sub

A: To Filter the Pivot table you will have to parse pivot items and then set the visibility to false for items that you don't want to show. Try the following:
Sub Pivot_Filtering()
    Dim pf As PivotField
    Set pf = ActiveSheet.PivotTables("PivotTable1").PivotFields("Sum of Test")
    'Clear Out Any Previous Filtering
  pf.ClearAllFilters
  'Enable filtering on multiple items
  pf.EnableMultiplePageItems = True
    For i = 2 To pf.PivotItems.Count
        If pf.PivotItems(i) > 30 Then
            pf.PivotItems(i).Visible = False
        End If
    Next i
End Sub


text:
Q: Android, looping through Parse data, assigning to ArrayAdapter I am looping through data in Android, using Parse data.  I came up with this as a way to get user information; the larger goal is to create a model of data that I can use in an array adapter, so I can create a custom list view (as described here) In the example, the data are hard-coded, not pulled from a database.
public static ArrayList<Midwifefirm> getUsers() {

    //Parse data to get users
    ParseQuery<ParseUser> query = ParseUser.getQuery();

    query.orderByAscending(ParseConstants.KEY_PRACTICE_NAME);

    query.findInBackground(new FindCallback<ParseUser>() {
        @Override
        public void done(List<ParseUser> users, ParseException e) {

            if (e == null) {

                final List<ParseUser> mMidwives;
                mMidwives = users;

                String usertype;

                String[] midwives = new String[mMidwives.size()];
                String[] yearsofexperience = new String[mMidwives.size()];
                String[] education = new String[mMidwives.size()];
                String[] philosophy = new String[mMidwives.size()];

                int i = 0;
                for (ParseUser user : mMidwives) {

                    usertype = user.getString("userType");

                    if (!Arrays.asList(midwives).contains(usertype) && usertype != "patient") {

                        midwives[i] = user.getString("practicename");
                        yearsofexperience[i] = user.getString("yearsofexperience");
                        education[i] = user.getString("education");
                        philosophy[i] = user.getString("practicephilosophy");

                        ArrayList<Midwifefirm> midwifefirm = new ArrayList<Midwifefirm>();
                        midwifefirm.add(new Midwifefirm(midwives[i], yearsofexperience[i], education[i], philosophy[i]));

                        return midwifefirm;
                    }
                }
            }
        }
    });
}

The intention is that for every user that does not have the type patient, collect this data about them, then store it in the arrayList.
On the return statement, though, there is an error: cannot return a value from a method with a void return type.
I may be over complicating this...read through various sources to get a model for this...in the end, I want to display a list of information about specific users, after the user makes a selection of a city...it would therefore display all the information about the medical practices in that city.
Thanks for your help
Michael

A: The code won't even compile in the form you sent it.
You make an asynchronous call when you use findInBackground. That means the code that calls it will just carry on after it calls it. It won't wait for it to finish, it doesn't care about it anymore.
The right way to deal with this type of code is by writing the logic you want and manipulating the results in the callback. So the first thing we change is the return type of getUsers to void.
Now getUsers merely says: "OK, please find this in background and from here I'll let you do your thing in done()".
public static void getUsers() {

    //Parse data to get users
    ParseQuery<ParseUser> query = ParseUser.getQuery();

    query.orderByAscending(ParseConstants.KEY_PRACTICE_NAME);

    query.findInBackground(new FindCallback<ParseUser>() {
        @Override
        public void done(List<ParseUser> users, ParseException e) {

            if (e == null) {
                // here you manipulate your list. you set up your data structures
                // or whatever and call other methods from your `Activity` or whatever,
                // passing the data as parameter
            }
        }
    });
}

You will need to update the code that calls getUsers and needs the list of users, because, as you see, it can't get the results straight away. You may be able to move some of that code in done.
LE: You may also want to remove the static modifier from your method.


text:
Q: Open a recordset with a parameter from an open form I'm trying to send emails from Access to Outlook. The record-set is to be base on a table using a parameter (date) on an open form.
I get this running OK :
    Set rstEMail = MyDB.OpenRecordset("Select [Courriel] FROM [N_BR_TEST_TOTAL]where [D examen]=#2016-08-20#", dbOpenSnapshot, dbOpenForwardOnly)

But not this :
    Set rstEMail = MyDB.OpenRecordset("Select [Courriel] FROM [N_BR_TEST_TOTAL]where [D examen]=[Forms]![F-EVENEMENT]![DATE]", dbOpenSnapshot, dbOpenForwardOnly)

The second line gives a Run-time error 3061: Too few parameters. Expected 1.
Is there away to pass the value of the date on the Select/Where?
I'd like for an email to be sent to all registered for an event on a specific date shown on the form containing the command button that run the code

A: You need to remove the form and field reference from the double quotes and join it to the rest of the sql string with an ampersand.
Set rstEMail = MyDB.OpenRecordset("Select [Courriel] FROM [N_BR_TEST_TOTAL]where [D examen]=" & [Forms]![F-EVENEMENT]![DATE], dbOpenSnapshot, dbOpenForwardOnly)


text:
Q: I'm looking to make my discord.js bot invisible client.user.setStatus('invisible')
client.on('ready',  async() => {
    console.log('I am online and ready to listen to commands!')
})

Does that work? Also I'm looking for a command that will do that like ;status dnd or ;dnd, pretty sure this code won't work:
client.user.setStatus('dnd')

Ok, so I realised that the error is:
https://pastebin.com/xtUZy0WW

A: You need to call client.user.setStatus('invisible') within the ready callback, otherwise client.user will be null. Other than that looks good :)
EDIT: looks like this
client.on('ready',  async() => {
    console.log('I am online and ready to listen to commands!')
    client.user.setStatus('invisible')

})


text:
Q: How to change the background of the Action Bar How can I change the background of the action bar in my app to a image from the drawable folder? It would be nice if you could tell me in which code goes to which file.

A: Add this property in your toolbar:
 android:background="@drawable/yourImage"

A: You can set background of your action bar as simple as that:
    <android.support.v7.widget.Toolbar
        android:id="@+id/your_app_bar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@drawable/your_drawable" />


text:
Q: JQuery Slider alternative? I am using the JQuery Slider control for use as a double sided slider.
It's a great UI control but I'm looking for an alternative that isn't so "fat".
Right now, just for me to use the Slider control, I have to include:

*

*JQuery core

*JQuery UI core

*JQuery Slider plugin

When I both minimize using Google's awesome Closure (minimizer) and GZIP the JavaScript, I'm still at around 29kb.
Do a comparable Slider control exist that isn't such a large download?

A: I recommend noUISlider, cross browser support (including touch devices) and at only 6KB minimized.

A: checkout jquery scrollable if it can help

A: I used this a while back, it's ~5kb ungziped + unClosure'd - and it works well.

A: There is the Ajax Control Toolkit...
http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/Slider/Slider.aspx


text:
Q: Google Maps JavaScript API Heatmap Layer- Limit of data points that can be displayed on the map? I'm new to the Google Maps JavaScript API and I'm applying a heatmap layer on google maps, similarly to the example in the maps heatmap documentation:
https://developers.google.com/maps/documentation/javascript/examples/layer-heatmap
I'm loading a lot of datapoints for the heatmap but only a limited amount are displaying.
I don't see any issues with the data; when I cut the dataset into smaller chunks the heatmap appears in different places each time I load the map.
But I can see in the usage documentation (https://developers.google.com/maps/documentation/javascript/usage) that there's a limit of 2,500 requests per day, and I don't know what the definition of one request is in this scenario.
Is it that when the map loads with initMap(), the entire HeatmapLayer being applied is considered one single request?
Or is it that, when I'm creating a heatmap with 4,000 datapoints, each call to new google.maps.LatLng() for each datapoint is considered 4,000 separate requests?

A: Following the example in the docs, I created an example that creates 10,000 points to plot on a heatmap, with no issue. So it can't be any kind of rate limit. There must be something else at play. This example does not even have an API key, so on the free plan.
Ten thousand heatmap point demo

A: Well, the Google Maps JavaScript API has these following quotas if you check your developer console.

It means that you can load your map 25,000 times per day and the user can only make 1 request per second.  While the unlimited here means that the maps can load simultaneosly.
So every time you call your API key like this, it count as a 1 load per day.
Note: The Daily quotas reset at midnight Pacific Time (PT)


text:
Q: Updating arrayAdapter with new data in AsyncTask I have the following AsyncTask in my activity that updates an ArrayAdapter that populates my ListView. It seems to work ok because i call notifyDataSetChanged within the onPostExecute.
My question is why does it only update the listview if i call notifyDataSetChanged inside runOnUIThread with onPostExecute?
I thought that onPostExecute runs on the UIThread, so my do i need to wrap it in the Runnable?
@Override
protected void onPostExecute(LoginWebservice.TwoDimentionalArrayList<String> result) {
    super.onPostExecute(result);

    if (progressDialog != null) {
        progressDialog.dismiss();
    }

    listView = (ListView) findViewById(R.id.rotalist);

    arrayAdapter = new MySimpleArrayAdapter(GetRota.this, array);
    listView.setAdapter(arrayAdapter);
    listView.setOnItemClickListener(GetRota.this);

    runOnUiThread(new Runnable() {
        public void run() {
            arrayAdapter.notifyDataSetChanged();
        }
    });

}

A: You shouldn't even need to invoke notifyDataSetChanged().  You are creating a new adapter and setting it to the ListView.  You make no modifications afterwards, so there's no need to call that method. It is redundant.


text:
Q: jquery blur not working on "exiting" text input even though "click" does I'm trying to make a custom dropdown be able to be "tabbed into" using jquery. That is, it is made of a ul, and I want the text input directly above it, when tabbed out of give some sort of focus to the ul. But for some reason this
var input = $("ul.dropdown_ul").prev("input");
$("#container").on("blur", input, function(){
     alert("test");
 });

does not work. With click as the event, the alert fires. But blur is not working.
JSBIN
Any ideas on why this doesn't work? Thanks.

A: Your #container is a div. Typically blur is used on inputs, thats why it not working. The following works fine.
$("#container input").on("blur", function () {
    alert("test");
});`

Update Regarding Comment:
If your looking to have a specific element have the on blur event. Just make sure you select it properly and apply the listener to it. I think this is what you're trying to accomplish.
var $input = $("ul.dropdown_ul").prev('input')
$input.on("blur", function () {
    alert("test");
});

Example


text:
Q: Most efficient way to fill out a matrix of elements given by function f(i,j) in R? I have a function of two scalar values x_i, y_j.  I have a vector of n x_i values, X and n y_j values, e.g.
myfunction <- function(x,y) min(x,y)
X <- 1:3
Y <- 2:4

I want to fill out the $n$ by $n$ matrix whose elements (i,j) are given by myfunction(x_i, y_j).  There's a lot of ways to do this in R, and I'm curious about their relative performance.
For instance, this seems like a task for outer, but it seems to get confused whether it is passing a vector or scalar to myfunction.  First consider:
r
    outer(X, Y, paste)

gives me each of the pairs
     [,1]  [,2]  [,3]
[1,] "1 2" "1 3" "1 4"
[2,] "2 2" "2 3" "2 4"
[3,] "3 2" "3 3" "3 4"

Looks good.  But
outer(X, Y, myfunction)

throws the error:
Error: dims [product 9] do not match the length of object [1]

Meanwhile other possible functions seem to behave as I expected with scalars, such as:
myfunction <- function(x,y) exp((x-y)^2)

which works fine
outer(X, Y, myfunction)

         [,1]      [,2]        [,3]
[1,] 2.718282 54.598150 8103.083928
[2,] 1.000000  2.718282   54.598150
[3,] 2.718282  1.000000    2.718282

In a few quick numerical experiments, it seems this is slightly faster than expand.grid, and the function call more compact, but I don't seem to understand why some functions appear to work as I anticipate and others do not.
The classic expand.grid solution also requires the function to work with vector arguments, which means a very different thing for my example with min; a different version of the same problem.  Is there a way to enforce the fact that the arguments to my function must be scalars rather than vectors?

A: The function passed to outer must be vectorized,
From the source code
   FUN <- match.fun(FUN)
        Y <- rep(Y, rep.int(length(X), length(Y)))
        if (length(X))
            X <- rep(X, times = ceiling(length(Y)/length(X)))
        robj <- FUN(X, Y, ...)
        dim(robj) <- c(dX, dY)

min will return a single number, you would want pmin.
More generally you could use Vectorize.


text:
Q: Google spreadsheet to html and filtering function thru web apps Recently, my company changed office ware to G Suite from MS office. To organize the spreadsheet data, i am using the web apps. So I am newbie here.
I am exporting the spreadsheet to html and trying to make filter function but it doesn't work well. Maybe there is some clear steps to cleansing the codes. So i am here to have your supports. Please advise.
Q1) There might be the simple way however i don know how to integrate the filter function with the parsed data.
Q2) The date column should be changed to text to import html. Is there any other way to display the date column?
Q3) Is there any way to show the page number in the html page if there is long thread?


text:
Q: Why is nginx redirecting assets to home page? I got the same nginx config in development and in production, and the production server keeps re-directing assets links (and only assets links) to home page. Other links, that are served by blade view route are fine.
So a link to https://subdomain.example.com/test will work fine, providing there is a view in the routes of Laravel.
But, a link to https://subdomain.example.com/img/picture-of-a-cat.png will be redirected back to home screen, but the address bar will still show https://subdomain.example.com/img/picture-of-a-cat.png. This behaviour is only observed in production.
Sever details: Ubuntu 18.4, Nginx, Laravel latest
Where is the catch?
Production config:
server {
        listen 80;
        listen [::]:80;
        server_name subdomain.example.com
        return 301 https://$server_name$request_uri;
}

server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name subdomain.example.com;

        root /var/www/html/public;

        index index.php index.html index.htm index.nginx-debian.html;

        location / {
                try_files $uri $uri/ /index.php?$query_string;
        }

        ssl_certificate /etc/ssl/certs/example-cert.cer;
        ssl_certificate_key /etc/ssl/private/example-private-key.key;

        location ~ \.php$ {
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

                fastcgi_intercept_errors off;
                fastcgi_buffer_size 16k;
                fastcgi_buffers 4 16k;
                fastcgi_connect_timeout 300;
                fastcgi_send_timeout 300;
                fastcgi_read_timeout 300;
        }
   location ~ /\.ht {
                deny all;
        }
}


text:
Q: Python Pandas For loop I am trying to create a column, in my dataframe, which will calculate values on behalf of certain categories in another column.
Lets say, I have a column X, which has materials of different types, and there is a price of each of the types. Now, I want to append a column, based on each group along with Materials column, stating the Median of that particular type of materials.
Columns would be like Materials|Prices| Median_Prices
Help me in generating Column Median Prices.
Material,Prices,Median _Prices
a,12,12.5
a,13,12.5
b,34,34
b,565,34
b,8,34
c,87,66
c,66,66
c,7,66

A: No need for loops to do this.  Let use groupby and transform:
df['Median_Prices_Calc'] = df.groupby('Material')['Prices'].transform('median')

Output:
  Material  Prices  Median_Prices  Median_Prices_Calc
0        a      12           12.5                12.5
1        a      13           12.5                12.5
2        b      34           34.0                34.0
3        b     565           34.0                34.0
4        b       8           34.0                34.0
5        c      87           66.0                66.0
6        c      66           66.0                66.0
7        c       7           66.0                66.0


text:
Q: How to reverse a string and replace chars? I have been asked by an interviewer for a test:
$string = "This is sample string";
// Output: "string_sample_is_This";

what does this question mean..?
I assumed that he was asking about a simple echo, am I right or would he expected something else from me ?
<?php
    $string = "This is sample string";
    echo $string;
?>

A: He definetly asked for something else ...
<?php

    $string = explode(" ","This is sample string");
    $string = array_reverse($string);
    $string = implode("_",$string);
    echo $string;

?>

More :
PHP explode()
PHP array_reverse()
PHP implode()

A: That looks more like you are being asked to reverse the order of the tokens in the string and replace the delimiter from single spaces to the _ character. I would assume that or something similar to such was being asked.

A: No he told to reverse the sentence and echo the string.
<?php
    $string = "This is sample string";
    $string1 = '';
    $string_array = explode(' ',$string);
    $count = count($string_array) - 1;
    for($i=$count; $i>=0; $i--)
    {
    if($i == 0)
    {
    $string1 .= $string_array[$i];
    }
    else
    {
    $string1 .= $string_array[$i]."_";
    }
    }
    echo $string1;
?>


text:
Q: Unity 2017.3: Preview script created UI elements in editor I have a canvas with attached script that creates an UI programmatically. What I would like to achieve is to be able to see the UI in editor. I've tried to mark this class as [ExecuteInEditMode] but the problem with that is that the Awake method where I create the UI is called every time I enter play mode, therefore creating new and new copies of the UI elements and never deleting them.
Here is a sample code I'm using:
[ExecuteInEditMode]
public class InGameCanvas : MonoBehaviour {
    protected InGameCanvas() { }

    private Canvas canvas;

    private void Awake() {
        if ((canvas = gameObject.GetComponent<Canvas>()) == null) {
            Debug.LogError("InGameCanvas script not connected to a Canvas.");
            return;
        }

        var balanceTextObject = new GameObject("BalanceText");
        balanceTextObject.transform.SetParent(gameObject.transform);
        var balanceText = balanceTextObject.AddComponent<Text>();
        var balanceTextTransform = balanceTextObject.GetComponent<RectTransform>();

        balanceText.text = "Balance: 0";
        balanceText.font = Defaults.consolasFont;

        balanceTextTransform.sizeDelta = new Vector2(100, 20);
        balanceTextTransform.pivot = new Vector2(0, 1);
        balanceTextTransform.anchorMin = new Vector2(0, 1);
        balanceTextTransform.anchorMax = new Vector2(0, 1);

        balanceTextTransform.anchoredPosition = new Vector2(10, -10);
    }
}

I would like to be able to also preview some other objects created by scripts as they will be on play mode run, but I'm having same problem. [ExecuteInGameMode] also says, it will run other code of the script as well, which I don't really need. All I need is to run the Awake function in editor to preview the object.

A: void Awake () {
    if (!Application.isPlaying) {
        // Your Code Here.
    }
}

EDIT: Or
#if UNITY_EDITOR
    // Your Code Here.
#endif

This executes the block only when Unity is in "Editor" mode and not "Playing".


text:
Q: SQL server 2008 - Charting problems I'm trying to create a chart from the below table and ideally would like a line chart with weeks across the bottom, one static sales target line ( Average would work ) and then 4 curve lines for the people. Note: The country and year do not need to be displayed.
Easy to do with a pivot chart in excel, but I am really confused on this one and very new to SQL. Any advise/help would be appreciated.
http://i.stack.imgur.com/PjuSt.jpg

A: SQL itself cannot make charts, it can only provide data which other tools can use to make charts from. Using Excel is one solution; other depend on what DBMS you are using and what tools you have available. For example, if you are using SQL Server, then SQL Server Reporting Services (SSRS) makes this easy (once you've set it up).
But with just SQL - no, no charts.


text:
Q: Is there a chance to change the build variants run time in android I used the product flavors to build the different apps. If I select free flavor in the build variant before running the app the free flavor will be run if I select paid flavor the paid will be run.
I want to change in the run time means after running the app if we click on button it has to change paid app. Is there any chance to change the build variant selection run time through programming.
class productFlavors {
    free{

    }

    paid{

    }
}

I used these as flavors.
If anyone knows the solution please help me to solve my problem.
Thanks in advance.

A:
I want to change in the run time means after running the app if we click on button it has to change paid app

That is not possible. Product flavors are something applied at compile time. Your free app does not have the resources, Java code, manifest entries, dependencies, etc. that are solely in your paid product flavor.
You will need to get rid of your product flavors and have a single build, where you have runtime logic to decide whether to offer the free or the paid set of features.


text:
Q: Prove or disprove: If $A\in \mathbb{R}^{m\times n}$ is a matrix and it's columns are basis for $\mathbb{R}^m$.. then it's rows are basis for $\mathbb{R}^n$.

I encountered this question and I answered wrong, and here's what I did:
I took a counter example: $A = \begin{bmatrix}1&0&0\\0&1&0\end{bmatrix}_{2\times 3}$.
the columns $\{(1,0),(0,1)\}$, and they're a basis for $\mathbb{R}^2$, but the rows aren't a basis for $\mathbb{R}^3$.
Now I can't understand what's wrong with my counter example and why this is true.
I would appreciate it if someone can point out my mistakes and why my example doesn't work, and why the sentence is true.  Thanks in advance.

A: The linearly independent columns are those columns with leading $1$'s when the matrix is brought into $RREF$. Thus if the columns form a basis for $\mathbb{R}^m$, then necessarily there must be $n$ vectors, and so $m = n$.
For $m=n$ then the $RREF$ of $A$ is $I_{n\times n}$, the columns and rows are a basis for $\mathbb{R}^n$.

A: It is true because your matrix $A$ has to in fact be square.
If the columns of $A$ are a basis for $\Bbb{R}^m$, then $A$ has $m$ linearly independent columns. But there are actually $n$ columns so it follows $m=n$.
Now recall that the column rank (which is $m$) is equal to row rank so there are $n$ linearly independent rows of $A$. They form a basis for $\Bbb{R}^n$.


text:
Q: ElasticSearch Painless script: Not able to access nested objects using script score I want to search for keywords from the specific field and return the documents. On top of these documents, I want to iterate through each nested object and search for keywords again from the same specific field on selected documents.
If a keyword exists, then check:
if boolean isCurrent = True, set isCurrent=0 and append this value to list
else if isCurrent = False, take the difference of current datetime, end datetime and get the value in terms of months and append this value to the list.
Finally, get the minimum value from that list of each document and sort the documents based on the minimum value.
I am able to do this custom login through script_fields and sort the documents based on the minimum value. When I use this same login in script_score it does not work. When I debug I see a problem accessing the nested field using params._source.
Any help will be much appreciated.
Please find the below elastic search query using script_fields. Here I am passing the current_milliseconds value from a python script.
    query = {
        'query': {
            "nested": {
                "path": "person.experiences",
                "query": {
                    "query_string": {
                        "query": keywords,
                        "fields": ["person.experiences.description"],
                        "default_operator": "AND"
                    }
                }
            }
        },
        "script_fields": {
            "recency": {
                "script": {
                    "lang": "painless",
                    "inline": """
                            def myString = "";
                            def isCurrent = 0;
                            def isFound = false;
                            def index_position = 0;
                            def recency_num = 0;
                            def result = 0;
                            def list = new ArrayList();

                            // for loop starts here
                            for(int i=0; i<params._source.person.experiences.size(); i++){
                            myString = params._source.person.experiences[i].description;

                            // string match starts here
                            if(myString != null && myString != ''){
                            def matcher1 = /electric/.matcher(myString.toLowerCase());
                            def matcher2 = /vehicle/.matcher(myString.toLowerCase());
                            //if(wordMatcher.find()){
                            if (matcher1.find() || matcher2.find()){
                            isFound = true;
                            }

                            if (isFound == true){
                            // recency check starts here
                            isCurrent = params._source.person.experiences[i].isCurrent;
                            if(isCurrent == true){
                            isCurrent=0;
                            result+=isCurrent;
                            list.add(isCurrent);
                            } else{
                            ZonedDateTime now = ZonedDateTime.ofInstant(Instant.ofEpochMilli(params['current_datetime']), ZoneId.of('Z'));
                            ZonedDateTime end_date = ZonedDateTime.parse(params._source.person.experiences[i].end);
                            isCurrent = end_date.until(now, ChronoUnit.MONTHS);
                            list.add(isCurrent);
                            result+=isCurrent;
                            recency_num = isCurrent;
                            }
                            }

                            }
                            }
                            def min = list.get(0);
                            for (int i : list){
                            min = min < i ? min : i;
                            }
                            return min;
                            """,
                    "params": {
                        "search_keywords": "Machine Learning",
                        "current_datetime": current_milliseconds
                    }

                }
            }
        }
    }

Thanks in advance.

A: A valid script_score query in your case would look something like this:
GET my-index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "function_score": {
            "functions": [
              {
                "script_score": {
                  "script": {
                    "source": """
                      def myString = "";
                      def isCurrent = 0;
                      def isFound = false;
                      def index_position = 0;
                      def recency_num = 0;
                      def result = 0;
                      def list = new ArrayList();

                      def experiences = params._source.person.experiences;

                      // for loop starts here
                      for (int i=0; i<experiences.length; i++){
                        def experience = experiences[i];

                        myString = experience.description;

                        // string match starts here
                        if(myString != null && myString != '') {
                          def matcher1 = /electric/.matcher(myString.toLowerCase());
                          def matcher2 = /vehicle/.matcher(myString.toLowerCase());

                          if (matcher1.find() || matcher2.find()){
                            isFound = true;
                          }

                          if (isFound == true){
                            // recency check starts here
                            isCurrent = experience.isCurrent;

                            if (isCurrent == true){
                              isCurrent=0;
                              result += isCurrent;
                              list.add(isCurrent);
                            } else {
                              def now = ZonedDateTime.ofInstant(Instant.ofEpochMilli(params['current_datetime']), ZoneId.of('Z'));
                              def end_date = ZonedDateTime.parse(experience.end);
                              isCurrent = end_date.until(now, ChronoUnit.MONTHS);
                              list.add(isCurrent);
                              result += isCurrent;
                              recency_num = isCurrent;
                            }
                          }
                        }
                      }

                      if (list.length === 0) {
                        return 0;
                      }

                      def min = list.get(0);

                      for (int i : list){
                        min = min < i ? min : i;
                      }

                      return min;
                    """,
                    "params": {
                        "search_keywords": "Machine Learning",
                        "current_datetime": 1643036066000
                    }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

Note that loads of regexes, iteration, and (date) parsing can drastically increase the query resolution.


text:
Q: Create a numpy array from a line I have the follwing issue: I read a line using realines, the line is the following:
Reference Coordinates: Xref = 0.00000E+000, Yref = -1.20982E-002
i want this line to be converted into a numpy array, so that:
         array=[nan nan nan nan 0.0 nan nan -1.20982E-002]

than i want to be able to access this array:
        number1=array[0][4]
        print(number1)
        0.00000E+000
        number2=array[0][6]
        print(number2)
        -1.20982E-002

Problem is when im using e.g. np.fromstring (i tried i think all similar numpy routines) I cannot access the array like this. Either I get:
        Enter file name: ERIS-NIX_106_-FOLDED-Grid_Distortion-cam2-wl3.txt
        ["['Reference" 'Coordinates:' 'Xref' '=' '0.00000E+000,' 'Yref' '='
         "3.00947E-003\\r\\n']"]
       [

       Traceback (most recent call last):
       File "/home/sebo/Documents/Linear Transform For Eris C1/ERIS-NIX_106_-FOLDED-Grid_Distortion(1)/Open_shift.py", line 51, in <module>
      main()
       File "/home/sebo/Documents/Linear Transform For Eris C1/ERIS-NIX_106_-FOLDED-Grid_Distortion(1)/Open_shift.py", line 9, in main
       reader_affine(file_name,d)
       File "/home/sebo/Documents/Linear Transform For Eris C1/ERIS-    NIX_106_-FOLDED-Grid_Distortion(1)/Open_shift.py", line 35, in reader_affine
       print(line[0][i][i])
       IndexError: string index out of range

OR:
      Enter file name: ERIS-NIX_106_-FOLDED-Grid_Distortion-cam2-wl3.txt

      Traceback (most recent call last):
      File "/home/sebo/Documents/Linear Transform For Eris C1/ERIS-                 NIX_106_-FOLDED-Grid_Distortion(1)/Open_shift.py",        line 50, in <module>
      main()
      File "/home/sebo/Documents/Linear Transform For Eris C1/ERIS-           NIX_106_-FOLDED-Grid_Distortion(1)/Open_shift.py", line 9, in main
      reader_affine(file_name,d)
      File "/home/sebo/Documents/Linear Transform For Eris C1/ERIS-NIX_106_-FOLDED-Grid_Distortion(1)/Open_shift.py",               line 29, in reader_affine
      line=np.fromstring(critical_line,dtype=float)
      ValueError: string size must be a multiple of element size

OR I can seperatily access my array but than I get something like this:
      Enter file name: ERIS-NIX_106_-FOLDED-Grid_Distortion-cam2-wl3.txt
      [
      C
      X
      =
      0
      Y
      =
      3

For a loop that goes like this:
        while i in range(0,line.size):
        print(line[0][i])
        i=i+1

A: Similar questions have been asked before (Python: Extract numbers from a string). I copied your input list(string) from the question, except removing double quotation marks.
s=['Reference' 'Coordinates:' 'Xref' '=' '0.00000E+000,' 'Yref' '=''3.00947E-003\\r\\n']

Then you can first extract remove the non-number characters, which creates a list of numbers as strings:
 import re
 x=array(re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", s[0]))

Output: ['0.00000E+000' '3.00947E-003']
Convert it to float array:
import numpy as np
y = x.astype(np.float)
print y

Output: [ 0.          0.00300947]


text:
Q: Minimizing ZeroMQ round trip latency My question is about minimizing the latency between a ZMQ client and server
I have the following modified Hello World ZMQ (JeroMQ 0.5.1)
import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;

public class server {
    public static void main(String[] args) {
        try (ZContext context = new ZContext()) {
            // Socket to talk to clients
            ZMQ.Socket socket = context.createSocket(SocketType.REP);
            socket.bind("tcp://*:5555");

            while (!Thread.currentThread().isInterrupted()) {
                byte[] reply = socket.recv(0);
                System.out.println(
                        "Received " + ": [" + reply.length+ "]"
                );

                String response = "world";
                socket.send(response.getBytes(ZMQ.CHARSET), 0);
            }
        }
    }
}

and client:
import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;

public class client {
    public static void main(String[] args)
    {
        try (ZContext context = new ZContext()) {
            //  Socket to talk to server
            System.out.println("Connecting to hello world server" + args[0] + args[1] + args[2] );

            ZMQ.Socket socket = context.createSocket(SocketType.REQ);
            socket.connect("tcp://"+args[0]+":"+args[1]);

            for (int requestNbr = 1; requestNbr != 10; requestNbr++) {
                byte[] request = new byte[requestNbr*(Integer.parseInt(args[2]))];
                System.out.println("Sending Hello " + requestNbr);
                long time = System.nanoTime();
                socket.send(request, 0);

                byte[] reply = socket.recv(0);
                double restime = (System.nanoTime() - time)/1000000.0;
                System.out.println(
                        "Received " + new String(reply, ZMQ.CHARSET) + " " +
                                requestNbr + " " + restime
                );
            }
        }
    }
}

I'm running the server and the client over a network with latency (160ms round trip). I create the latency using tc on both the client and the server:
tc qdisc  del dev eth0 root
tc class  add dev eth0 parent 1: classid 1:155 htb rate 1000mbit
tc filter add dev eth0 parent 1: protocol ip prio 1 u32 flowid 1:155 match ip dst 192.168.181.1/24
tc qdisc  add dev eth0 parent 1:155 handle 155: netem delay $t1 $dt1 distribution normal

Now when I run java -jar client.jar 192.168.181.3 5555 100000 I get the following output:
Sending Hello 1
Received world 1 1103.392783
Sending Hello 2
Received world 2 322.553512
Sending Hello 3
Received world 3 478.10143
Sending Hello 4
Received world 4 606.396567
Sending Hello 5
Received world 5 641.465041
Sending Hello 6
Received world 6 772.961712
Sending Hello 7
Received world 7 910.848674
Sending Hello 8
Received world 8 966.694224
Sending Hello 9
Received world 9 940.645636

which means that as we increase the size of the message, it takes more round trips to send the message and receive the ack (you can play with the message size to see for yourself). I was wondering what I need to do to prevent that from happening, that is: send everything in one go and minimize the latency to the roundtrip time.
Note: In my original application, I'm using a REQ-ROUTER pattern as I have multiple clients, but the issue with the latency and large messages lingers on


text:
Q: Python C API function arguments How can I define a function, or a contructor for a class with specified arguments using the C API?
By default function takes PyObject* args, and later in the code the linter won't show real arguments.
If it's not possible, is there a way to bypass it? I came up with two possible options:

*

*Wrap every function in python code
def f(x: int, y: int) -> int:
    return _c_module(x, y)

*Maybe .pyi files could somehow do the trick(?)

A: The best way to do this is to use .pyi files and distribute them with your package (look at the docs), i.e. if you have a module my_mod with class Baz with member foo and method bar, then you would want to have my_mod.pyi like this:
class Baz:
    foo: float

    def bar(self, param_a: str, default_one: int = ...) -> str:
        pass

And then most linters, type checkers, etc. would catch this up and work with it.
Additionally: about stubs from mypy.


text:
Q: PHP, MySQL and a large nummer of simple queries I'm implementing an application that will have a lot of clients querying lots of small data packages from my webserver. Now I'm unsure whether to use persistent data connections to the database or not. The database is currently on the same system as the webserver and could connect via the socket, but this may change in the near future.
As I know a few releases of PHP ago mysqli_pconnect was removed because it behaved suboptimally. In the meantime it seems to be back again.
Based on my scenario I suppose I won't have an other chance to handle thousands of queries per minute but with loads of persistent connections and a MySQL configuration that reserves only little resources per connection, right?
Thanks for your input!

A: Are PHP persistant connections evil?

The problem is there can be only so
  many connections active between Host
  "Apache" and Host "MySQL"

Persistant connections usually give problems in that you hit the maximum number of connections. Also, in your case it does not give a great benefit since your database server is on the same host. Keep it to normal connections for now.

A: What happened when you tested it?
With the nest will in the world, there's no practical way you can convey all the informaton required for people to provide a definitive answer in a SO response. However usually there is very little overhead in establishing a mysql connection, particularly if it resides on the same system as the database client (in this case the webserver). There's even less overhead if you use a filesystem rather than a network socket.
So I'd suggest abstracting all your database calls so you can easily switch between connection types, but write your system to use on-demand connections, and ensure you code explicitly releases the connection as soon as practical - then see how it behaves.
C.

A: As they say, your mileage may vary, but I've never had good experiences using persistent connections from PHP, including MySQL and Oracle (both ODBC and OCI8). Every time I've tested it, the system fails to reuse connections. With high load, I end up hitting the top limit while I have hundreds of idle connections.
So my advice is that you actually try it and find out whether your set-up is reusing connections properly. If it isn't working as expected, it won't be a big lose anyway: opening a MySQL connection is not particularly costly compared to other DBMS.
Also, don't forget to reset all relevant settings when appropriate (whatever session value you change, it'll be waiting for you next time to stablish a connection and happen to reuse that one).


text:
Q: Get tx_news fal_media via TypoScript to use in fluid page template I want to use the first image out of a new entry to include in the page header.
Therefore i need the news fal_media data in TypoScript to pass it to my page fluid template.
I managed to get the first image as a file path by this TypoScript code:
lib.newsimage = FILES
lib.newsimage {
    references {
        table = tx_news_domain_model_news
        uid.data = GP:tx_news_pi1|news
        fieldName = fal_media
    }
    maxItems = 1
    renderObj = IMG_RESOURCE
    renderObj.file {
        import.data = file:current:publicUrl
    }
    stdWrap.ifEmpty = {$settings.ext.news.imageDummy}
}

But is there a better way to do it, especially to get the data as an array of FileReferences? With a FAL FileReference i could also take crop an meta data into account.

A: You might use a FilesProcessor

example based on the manual:
    10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
    10 {
       as = news_images
       references {
          fieldName = fal_media
          table = tx_news_domain_model_news
       }
       sorting = datetime
       sorting.direction = descending
    }

Although I can't imagine that this will be the correct way as there is no guarantee that the first news you select by this is the first news shown on the page. News have multiple conditions to be shown aside of basic visibility: ordering by publishing time, archived state, top-news state, groups or categories, ...
Maybe it would be easier if you use a news plugin with a special template and don't forget to enable showing of news multiple times (by default each news gets shown only once in a page)


text:
Q: Move a file that failed to import to a different folder in SSIS? I found this link that describes how to move a file after it has been imported using SSIS:
How do I move files to an archive folder after the files have been processed?
I would like to set up some error handling such that a file that fails to 100% successfully import gets moved into a different folder for manual review.
Can anyone help with this?

A: Follow the same steps as in the question/answer you referenced, but change the destination if the import wasn't 100% successful.


text:
Q: Detect string in Outlook Attachment filename I'm trying to detect if there is a specific string in the filename.
For example, an attached file is named "myimportantplaylist.xlsx" (file extension does not matter) and my keyword is playlist (plus or minus spaces or any combination of the word).
I thought about doing this by regexp. I have the following construct that I was hoping to throw a keyword into.
Public Sub AttachmentQuery(ByVal attachment As Outlook.Attachment, _
  ByVal mailItem As Outlook.MailItem, ByRef Cancel As Boolean)

  Dim frm As New Form1()

  If (System.IO.Path.GetExtension(attachment.FileName) = ".xls") Or _
    (System.IO.Path.GetExtension(attachment.FileName) = ".xls") Or _
    (System.IO.Path.GetExtension(attachment.FileName) = ".doc") Or _
    (System.IO.Path.GetExtension(attachment.FileName) = ".docx") Or _
    (System.IO.Path.GetExtension(attachment.FileName) = ".txt") Or _
    (System.IO.Path.GetExtension(attachment.FileName) = ".pdf") Or _
    (System.IO.Path.GetExtension(attachment.FileName) = ".xfdl") Or _
    (System.IO.Path.GetFileNameWithoutExtension(attachment.FileName) = "*playlist.*")

Then Cancel=True

A: I would use String.Contains function (MSDN Documentation)
So your section that says
System.IO.Path.GetFileNameWithoutExtension(attachment.FileName) = "*playlist.*"

Could become (in c#)
System.IO.Path.GetFileNameWithoutExtension(attachment.FileName).Contains("playlist")

I also would suggest you make the extension checking a bit more manageable, eg by looking up a 'allowed extensions' table of some sort.


text:
Q: Should I send raw data or Html as an Ajax response? I have a site written in Asp.net webforms. It uses ajax heavily.
Most forms on the site are submited with javascript. Javascript validates the input and sends it to /ajax.ashx on the server. The server processes the request and sends back a JSON response. My javascript uses the JSON to create html, which it inserts into the Dom.
I'm making a new version of my website written using asp.net MVC3. I've been looking at tutorials on this subject, and some of them recommend doing ajax in a different way. Rather than sending data and then building + inserting html with javascript, they create html at the server, and use javascript only to insert it into the Dom. For instance, in this tutorial.
Which way should I use? Using the new method will be quicker, but is it better?

A: That's a subjective question. Both approaches are possible and there is no better way. There are pros and cons of each approach.
Building the HTML on the server is easier and will require you less efforts but consumes more bandwidth compared to the first approach.
If you decide to go the first way you could use some client side templating framework which might help you simplify the generation of DOM elements on the client.

A: Creating html code directly into the server and injecting it with an ajax call is very fast and simple, the real problem is that in that way your service is bound to be used with that specific application.  By sending RAW data you allow any app to use that data in any way, without bounding it to a specific application.

A: returning json feels more flexible to me; you can change what happens with your json response, like the layout it results in. If you return html you return data mixed with layout. This doesn't feel right to me.

A: I believe it is better to separate the layout from the actual data. That is why you should pass data between your scripts and not HTML.
If you go about it sending HTML, consider that you would have to build valid HTML and CSS, which might not sound hard at first but then you'll start using CSS that is not loaded in the file calling the ajax, etc.
Always separate content (data) from layout. That's why there is HTML and CSS, to separate layout from data. So why mess things up by mingling HTML between data?

A: Building the html serverside will probably be faster and not bog down the client which is important.  Rendering data into HTML with javascript takes time and not every browser is fast with js (i.e. older versions of IE) so things can slow down if you're doing a lot of this.
Like previous posters said, it's kinda subjective because it depends on how much you're offloading to the client.  I'm of the opinion that if you can do things serverside, you should.
If you are going to be using this service to return JSON to other applications/clients, then it's probably a good idea to just leave it as JSON and let the client do what it needs on their side.


text:
Q: Bit persistence on a Hard Disk Drive I was wondering if there was a time limit to the "persistence" of bits on a hard drive, a classical SATA for example.
If I'm correct, bits are written by a magnetizing head in some cells on the hard drive. Depending on the magnetization, It will be a 0 or a 1.
But my question is, for how long (possibly a very long time) will the bit keep its value?
Does this magnetization not loose his strength after a while (possibly from the other bits influences or simply external factors)? Is there some sort of battery that allows the re-magnetization of the "oldest" bits?

A: The magnetic domains of the HDD surface are designed by the manufacturer to hold their state for a long time. That said there is always a leveling effect where adjacent domains of opposite polarity can tend to pull the both of them to a similar level. The advanced techniques used on today's HDDs really try hard to minimize this effect whilst at the same time making the read back circuits sensitive enough to be able to still see the polarity reversals when the domain to domain changes are much less than when originally magnetized.
Additional techniques such as embedding additional Reed Soloman type error recovery data bits into the recorded tracks can help to allow data recovery when some domains have degraded too far.
I am sure that manufacturers of HDDs try to assure that there products will retain data for a long long time. They may even specify an MTBF number to a certain level of errors. But remember that is a mean specification and some failures could happen before that time and some after that time.
At the end of it all it is pretty certain that the archival storage of data on HDDs is best done using a combination of redundant storage on similar media, redundant storage on alternate media type and periodic copying of data to ensure fresh recordings. This also means cycling out older HDDs as they have been re-used a certain number of times.


text:
Q: How to Prove with n vertices it can be guarded with n/4 guards? Theorem:
Any orthogonal polygon with n vertices can be guarded with at most n/4 guards
This was proven by: Kahn, Klawa and Kleiman in 1982, but I can't find the proof of how they did this on the internet without paying $50 bucks.
Does anyone know how to solve this?


text:
Q: Python: Infinite loop with "with open" I have a huge file around 5 GB (with around 7.2 million trees) with particle ID (first column) and time (second column) as follows, which tells us how the IDs of the particles evolves
#Tree 0, Nbranches=2
1544212658   -1.0000
#Tree 1, Nbranches=2
2147749983   -1.0000
#Tree 2, Nbranches=7
1644822649   -1.0000
1611272315   17.6766
1594523770   10.2310
1661603959   10.0127
1661624438   10.7100
#Tree 3, Nbranches=8
252530795   -1.0000
319647854   10.7497
...

and I have a list of Ids as a form of list whose evolution I want to track following the above file. I wrote a code which works for a small dataset that I made, but everytime I run it with the actual dataset (on my university cluster), the code keeps on looping. I included a print statement to track the progress of the code and I can notice that when it hits around 7.2 millionth tree, it starts allover again from Tree 0. The thing that baffles me is that I simply don't understand why the code loops, Can anyone see any logical falacies in the code? Can anyone help me with this? Thanks
The code:
import numpy as np
pid=[]
pid_pass=[]
ids=np.loadtxt('C:\\Users\\Nin\\Downloads\\gg\\100kpc_cumulative_halo_ids.txt') #list of initial
halos as a list
id_final=[]
with open('C:\\Users\\Nin\\Downloads\\Sel_merg_hist.txt','r') as inf:
      for line in inf:
         if line.startswith("#"):
             print line
             del pid[:]

         else :
            parts = line.split() # split line into parts
            pid.append((int(parts[0]),float(parts[1])))
            for i in range(len(ids)):
                 if ids[i]==int(parts[0]) and float(parts[1]) == -1 :
                    id_final.append(int(parts[0]))
                    pid_pass.append(ids[i])

                 elif ids[i]==int(parts[0]) :
                    id_final.append(pid[0][0])
                    pid_pass.append(ids[i])

id_left=list(set(ids).difference(set(pid_pass)))  #list of ids not used,                                                                                which didn't merge until after z=10

id_left= map(int,id_left) #convert float to int to get rid of .0

id_final=id_final+id_left

file = open("100kpc_final_ids.txt", "w")
for index in range(len(id_final)):
        file.write(str(id_final[index]) +  "\n")
file.close()

Thanks to @szym, it seems the main loop which reads every line of the file doesn't quit, it keeps on looping. Any idea why that happens?