text:
Q: Display current post position in Elementor Posts widget I'm using Elementor 2.6.8 + Elementor Pro 2.6.2
I'm designing an Archive template to display a list of Custom Post Types filtered by custom taxonomy terms.
I'm using Posts Widget from Elementor Pro to do this without a line of code.
Also, thanks to Ele Custom Skin plugin (1.2.0), I can design each post skin in a custom way (hopefully Elementor Pro will provide this in the future)/
Now, I want to display, in each post, the post's current position in the list (=in the WP loop).
I tried with this code snippet that I added to each post with the ShortCode Widget.
add_shortcode( 'current_post_count', function () {
    global $wp_query;
    $out = $wp_query->current_post;
    return $out;
} );

But this always return -1.
I suppose the reason is that, in the context of the Posts Widget, the global $wp_query is not the one to get the info from. I suppose the widget use another variable.
But thenm I don't know how to achieve this. Maybe if I could get the actual $query variable in use ? Or maybe use the Query ID parameter offered by the Posts Widget?
I don't know how to get this to work.
Anything to point me towards the right direction guys?
thanks!

A: I have solved my issue by using a more recent version (1.1.1) of Elementor Custom Skin Pro plugin, which allows to use dynamic values directly in the template content, that are interpreted during the Loop.
In my case, {{index}} does the trick.


text:
Q: Understanding Local Notification in Codename one I implemented a local notification test per this example https://www.codenameone.com/blog/local-notifications.html
I have the following two questions:
1) can I test local notifications from CN1 simulator. In the link above, I see a local notification test screenshot using the iPhone 6 simulator. Is there a way to force the app to run in background form the simulator in CN1?
2) If a local notification is sent when the app is running in foreground, I understand that the notification will not fire. Is the message lost in this case or is it queued somewhere?

A: Currently you can only test this on the device, it will work in the native simulator for iOS as you saw in the screeshot. You can run on the native iOS simulator using a Mac and include source.
The message would be lost if you fire in the foreground on iOS as it's the assumption that this is something you can notify within your app more effectively. You can determine if your app is in the foreground using the Display.isMinimized() method. In the foreground case you can use a tool like ToastBar to show a notification.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java (latest version) Lambda: replace anonymous inner class by lambda I have got a class which contains the following:
slider.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            // creating font object and store textarea value font
            Font font = area.getFont();
            // setting size from getting slider value
            float size = ((JSlider) e.getSource()).getValue();
            // setting font size for textarea
            area.setFont(font.deriveFont(size));

        }
    });

VScode Insider tells me to replace the inner class with lambda,
Here is a screenshot if you want to see what I mean,
ChangeListener is underline as yellow
So I tried to think of ways and couldn't come up with any since I am not experienced enough, any one want to help me find other ways how to write this "ChangeListener" please...?

A: If you use Intellij IDEA it will do it for you.
slider.addChangeListener(e -> {
            // creating font object and store textarea value font
            Font font = area.getFont();
            // setting size from getting slider value
            float size = ((JSlider) e.getSource()).getValue();
            // setting font size for textarea
            area.setFont(font.deriveFont(size));
    });

A: I never like these long lambda methods. I prefer something like:
private void processSliderEvent(ChangeEvent ce) {
...
}
slider.addChangeListener(this::processSliderEvent);


text:
Q: Change position of tooltip on window resize I'm using jQuery UI to create a tooltip for a search input field. I then want to position the tooltip according to the size of the browser window (top if less than 768px, left if more).
I initialise the tooltip with:
$('#search').tooltip({'placement':'top'});

Then I have this function to change the placement depending on the window size:
$(window).on('resize', function() {
    if ($(window).width < 768) {
        $("#damSearch").tooltip({'placement':'top'});
    } else {
        $("#damSearch").tooltip({'placement':'left'});
    }
}).trigger('resize');

For some reason it's not working. The tooltip initialises fine but when I resize the browser above 768px it still appears positioned to the top.
[EDIT]
I've been away for a few days and have just come back to try and resolve this problem.
I've installed Modernizr because I intend using it elsewhere on the site and so I thought I'd use Modernizr.mq to detect the window resizing. I also read elsewhere that the code to reposition the tooltip should be in its own self contained function, so this is the function:
function positionTooltip() {
    if (Modernizr.mq('(min-width: 768px)')) {
        $("#damSearch").tooltip({'placement':'left'});
    } else {
        $("#damSearch").tooltip({'placement':'bottom'});
    }
}

This is then followed in my Javascript file with:
$(document).ready(function() {

    positionTooltip();
    // Fire the function on page load

    $(window).resize(positionTooltip);
    // Fire function on window resize event

Unfortunately it's still not working correctly.
The tooltip appears correctly positioned when the page is first loaded, but if I then resize the browser the position is not updated. If I reload the page however the tooltip's position is changed accordingly.
It's as if the resize event is not triggering the function.
[/EDIT]
As ever all help and advice is greatly appreciated.
Tony.

A: you need to call the width function
if ($(window).width() < 768) {

notice the parentheses ()


text:
Q: Visual diff software compatible with svn 1.7 for mac osx Does anyone know of any software that can do a visual diff on an svn 1.7 repo (preferably free or free trial)?

A: There are several tools that can be integrated  with SVN.
Check out this question:
https://stackoverflow.com/questions/187064/graphical-diff-for-mac-os-x


text:
Q: How can I replace a key-value pair in a nested dictionary with the value from the same key-value pair? I want to replace the key-value pair in a directory with the value from the same key-value pair. In simple words, I want to replace
{k1:{key1:value1},k2:{Key2:value2}} with {k1:value1,k2:value2}
in simple words: {key1:value1} gets replaced with value1
My input is {'times': {0: 3284566678.449864},
 'C0PLUSA': {0: 2.4529042386185244e-06},
 'C1PLUSA': {0: 2.215571719760855e-06},
 'I0PLUSA': {0: 1200.000000000029},
 'M1BA': {0: 1.1971391933999447e-05},
 'M1DA': {0: 2.5217060699404884e-06},
 'M1GA': {0: 1.0922075194286918e-05},
 'M1SA': {0: 0.0006776339108859284},
 'M2BA': {0: 1.7152638293476106e-05}}

Code:
for i, key,value in a.items:
    a[key][value] = value.values()

But I get an error saying this object is not iterable.
for node,value in a.items():
    a = a.replace(node.values(), value.values())

but it still gives me an error.
I am expecting to get an output as:
{'times':3284566678.449864,
     'C0PLUSA': 2.4529042386185244e-06,
     'C1PLUSA': 2.215571719760855e-06,
     'I0PLUSA': 1200.000000000029,
     'M1BA':  1.1971391933999447e-05,
     'M1DA':  2.5217060699404884e-06,
     'M1GA':  1.0922075194286918e-05,
     'M1SA':  0.0006776339108859284,
     'M2BA':  1.7152638293476106e-05}

A: If all the keys in the inner dictionaries are 0 you can just do:
{k:v[0] for k,v in data.items()}

In case you want to ignore the keys of the inner dictionaries without knowing the value, you can see how this example works:
>>> data={'k1': {'key1': 'value1'}, 'k2': {'key2': 'value2'}}
>>> {k:list(v.values())[0] for k,v in data.items()}
{'k1': 'value1', 'k2': 'value2'}


text:
Q: Wrapping very long functions in RExcel VBA? When you want to use R functions in VBA via RExcel, you have to use
RInterface.RRun "..."

Then, if you'd like to define your own R function, you can simply
RInterface.RRun "y <- function(x) { ... }"

If y is made up by more than one command line, you can separate each line with ;, as you're used to do in R environment.
But... what if your y function is very very long?
A 20 ~ 30 rows R function is damn difficult to be written in such a way in VBA; and there's a limit to the length of VBA sentences.
So: how may I wrap?
Here's an example of a quite long R function: can you show me how to put in VBA using RExcel?
bestIV <- function(dT, IVTS.t, Spot, r) {
  b <- r
  xout <- seq(0, max(T), dT)
  sfm <- matrix(NA, nrow = length(K), ncol = length(xout))
  for(i in 1:length(K)) {
    sfm[i,] <- approx(x = T, y = IVTS.t[i,], xout = xout, rule = 2)$y
  }
  sfm[,1] <- sfm[,1] + sfm[,2] - sfm[,3]
  rownames(sfm) <- K
  colnames(sfm) <- xout
  Option <- matrix(NA, nrow = length(K), ncol = length(xout))
  for(i in 1:length(K)) {
    for(j in 1:length(xout)) {
      TypeFlag <- ifelse(K[i] < Spot, 'p', 'c')
      Option[i,j] <- GBSOption(TypeFlag = TypeFlag, S = Spot, X = K[i],
                               Time = xout[j] / 365, r = r, b = b,
                               sigma = sfm[i,j] / 100)@price
    }
  }
  rownames(Option) <- K
  colnames(Option) <- xout
  dP <- (cbind(0, -t(apply(X = Option, MARGIN = 1, FUN = diff))) / Option)[,-(1:2)]
  dV <- dP / dT
  min.V <- which(dV == min(dV), arr.ind = TRUE, useNames = TRUE)
  Strike <- as.numeric(dimnames(min.V)[1])
  Maturity <- as.numeric(unlist(dimnames(dV)[2]))[min.V[2]]
  Days <- dT
  Mat <- c(dV[which(dV == min(dV))], Strike, Maturity, Days)
  names(Mat) <- c('Value', 'Strike', 'Maturity', 'Days')
  return(Mat)
}

Thanks,

A: Put your R code in your spreadhseet (in a range of cells) and use this function instead:

RInterface.RunRCodeFromRange range
Executes the commands in range on a worksheet
          (allows to use commands prepared for interactive execution with R to be run in macro code)

A: You are passing a string as an argument to a VBA function. Thus your question reduces to "how can I concatenate strings in VBA".
The answer is to use the concatenation operator &, like this:
"a" & "b"

Say you have an R function:
y <- function(x, a, b){
  return(x)
}

Then you can do this in VBA:
RInterface.RRun "y <- function(x, a, b) {" &
  "return(x)" &
  "}"


text:
Q: What are the permutations of 6 different variables with multiple values? Apologies if this is better explained in another question; perhaps I'd better get up to speed with mathematics terminology so I may find it...
There are the following 6 options for searching on a website:

*

*Countries: 228

*Regions: 456

*Genders: 2

*Payment: 4

*Age: 8

*Sort: 3

You can choose zero or one of each option per URL. Assume each country has "ownership" of two regions. A region may only be included when its parent country is selected.
How would I begin to calculate how many possible permutations (URLs) there are here? I've used specific online calculators but I don't think I'm inputting the correct numbers, and I've read some of the permutation questions on here but I can't seem to compare them to my own use-case.
Example URLs:
/Australia/Actors-wanted/Females/Age-34/Paid/Sort-by-p/
/New-Zealand/Wellington/Actors-wanted/Sort-by-p/

A: Since you can choose zero or one countries, you have $229$ choices for country.  Similarly you have $457$ choice for region.  The number of choices for country plus region is then $229 \cdot 457=104653$  Keep multiplying to include the other options.


text:
Q: Error unable to convert data type nvarchar to float I have searched both this great forum and googled around but unable to resolve this.
We have two tables (and trust me I have nothing to do with these tables). Both tables have a column called eventId.
However, in one table, data type for eventId is float and in the other table, it is nvarchar.
We are selecting from table1 where eventI is defined as float and saving that Id into table2 where eventId is defined as nvarchar(50).
As a result of descrepancy in data types, we are getting error converting datatype nvarchar to float.
Without fooling around with the database, I would like to cast the eventId to get rid of this error.
Any ideas what I am doing wrong with the code below?
SELECT
    CAST(CAST(a.event_id AS NVARCHAR(50)) AS FLOAT) event_id_vre,

A: The problem is most likely because some of the rows have event_id that is empty. There are two ways to go about solving this:

*

*Convert your float to nvarchar, rather than the other way around - This conversion will always succeed. The only problem here is if the textual representations differ - say, the table with float-as-nvarchar uses fewer decimal digits, or

*Add a condition to check for empty IDs before the conversion - This may not work if some of the event IDs are non-empty strings, but they are not float-convertible either (e.g. there's a word in the field instead of a number).

The second solution would look like this:
SELECT
     case when a.eventid <> ''
            then cast(cast(a.event_id as nvarchar(50)) as float)
          ELSE 0.0
     END AS event_id_vre,

A: Convert float to nvarchar instead of nvarchar to float. Of course!


text:
Q: Prometheus Blackbox exporter unknown timeouts Im having an issue with the Prometheus Blackbox exporter. Somehow i receive a lot of timeouts since i updated to the most recent version.
As you can see in below screenshot there is a massive spike on one of the endpoints and probe duration. However there is no such spike in the HTTP duration where that should reflect the actual http call to the application?

Im stuck on where to look next though so i hope that someone has an idea where to look and point me to the right direction.
Best,
Pim


text:
Q: start second setInterval after x seconds I need to build a page that is scrolling up and down after x seconds. I just need to know how to start the second setInterval after a delay. Or if people got other solutions i'm open for anything!
here is the code:
setInterval(function() {
    scrollDown();
},8000);

setInterval(function() {
    scrollUp();
},8000);

function scrollDown() {

    $('html, body').animate({
        scrollTop: $("#page2").offset().top
    }, 2000);
}

function scrollUp() {

    $('html, body').animate({
    scrollTop: $("#page1").offset().top
    }, 2000);
}

A: Cleaner and more precise to do this with just one timer like so:
setInterval(scrollDown, 8000);

function scrollDown() {
    $('html, body').animate({
        scrollTop: $("#page2").offset().top
    }, 2000);

    setTimeout(scrollUp, 4000);
}

function scrollUp() {
    $('html, body').animate({
        scrollTop: $("#page1").offset().top
    }, 2000);
}

A: You can use a setTimeout that sets itself?
function setNext(up){
  setTimeout(function(){
     if(up) scrollUp();
     else scrollDown();
     setNext(!up);
  }, 8000);
}

scrollDown() //first time
setNext(true);

Disclaimer : I haven't tested it. (yet)
Here's the working demo.

A: the easiest solution, try this:
setInterval(function() {
    scrollDown();
},8000);

setTimeOut(function(){
    setInterval(function() {
        scrollUp();
    },8000);
},1000);

because the setTimeOut function calls just once

A: Others have already answered so I will only add that this:
setInterval(function() {
    scrollDown();
}, 8000);

setInterval(function() {
    scrollUp();
}, 8000);

Is the same as this:
setInterval(scrollDown, 8000);

setInterval(scrollUp, 8000);

You don't need an anonymous function for a callback if all you do in that anonymous function is call another named function - you can just pass the named function.

A: setInterval(function() {
    scrollDown();
},8000);

setInterval(function() {
    scrollUp();
},8000 + 2000);

For what its worth, the above will have the exact same effect. But for code worded like your requirement, you could just:
setInterval(function() {
    scrollDown();
},8000);

setInterval(function() {
    setInterval(function() {
        scrollUp();
    },8000);
2000);


text:
Q: What is the maximum length of a Dynamic SQL statement generate within a Snowflake stored procedure? I want to generate a SQL statement within a stored procedure that will contain a "BIG" Case statement.
I honestly don't how how many bytes "BIG" is, but lets say I might have several thousands of "WHEN ... THEN " lines and each line could be reasonable big (WHEN this... AND that... THEN ... END).
From the documentation, I can see that there is a 1 MB limit on any statement submitted by a client tool but I suppose this does not apply to dynamic SQL generated within a stored procedure... since it is server side.
Any idea?

A: I wrote and modified a stored procedure to test this. It built a simple SQL statement that did a select 'xxxx' and increased the fill on the x characters. The code caught any SQL errors and returned the size of hitting the first error. It never did. It kept working and I kept increasing the increment size until finally the JavaScript (not SQL) reported a string size exceeded limit, which is 256 MB.
That didn't convince me that statements that long would necessarily do anything meaningful, so I modified the SP to test it with your cited example of a large case statement. That's when I hit what is probably a more significant limit. It reported "maximum number of expressions in a list exceeded. Expected at most 16,384.
I then tested it in blocks of 1000 when clauses (XS warehouse, took a few minutes), and unexpectedly it hit the limit between 8000 and 9000 when clauses. Even though the case statement had 9000 when clauses, the error said it had 18,002 expressions in the list, so it appears that's including each literal value in the when statement as one expression.
Based on this testing, you may be more likely to encounter the expression limitation in the case block before you hit the internal size limit for a statement.
Test SP code is here (monitor results in Query History):
create or replace procedure TEST_SQL_LEN()
returns float
language javascript
execute as caller
as
$$

    var sql = "";
    var caseBlock = "";

    for (var i = 1000; i < 100000; i = i + 1000) {
        sql =
`select
    ${i} as I,
    case ` + buildCase(i) + "\end as result";

        try {
            // To show in history page how many case statements
            getResultSet('select ' + i);
            // To test that many conditions in a case block
            getResultSet(sql);
        }
        catch(e) {
            return i;
        }
    }
    return -1;

function buildCase(n) {
    var s = "";
    for (var i = 1; i <= n; i++) {
        s += "when I = " + i + " then " + i + "\n";
    }
    return s;
}

function getResultSet(sql){
    cmd1 = {sqlText: sql};
    stmt = snowflake.createStatement(cmd1);
    var rs;
    rs = stmt.execute();
    return rs;
}

$$;

call TEST_SQL_LEN();

A: have in mind, that on top of the actual code you have compilation memory limitations - so the fact you CAN write 256 meg line of code doesn't mean you will be able to execute it. Also, Snowflake compilation also depends on the data, not just the code itself, so the same code might still run on a 10-row table and then fail on a 1000-row.
Are you sure there's no easier way to solve the actual problem?


text:
Q: Iphone Speaker Buttons used as App Controls Is it possible to use the external speaker volume controls of iphone as a control for an App you have developed?
For example as a control of a timer app for which the enable button for the timer to start counting is the top external volume button and disable timer is the lower external button.
If so, which classes of iOS 4 sdk can override those external buttons for an application or those external buttons are locked only for volume controls and nothing else?

A: I have seen a video of the Camera+ app that supposedly uses the volume key to snap a picture (instead of touching the button on the screen). http://taptaptap.com/blog/volumesnap/
I, myself, was pretty confused when I saw that and thought it must have been a mock up or something. But I asked around and apparently, if you're running an audio player, you get notifications when the volume keys are pressed.
The idea was put forward that if you can run a silent audio on a loop and hook into the volume key notifications to do what you want.
However, I've looked at both the AVAudioPlayer and the MPMoviePlayerController class documentation and can't see any such notifications. I suspect they're private, which isn't very useful.


text:
Q: MEF register EntityFramework.SqlServer for provider System.Data.Client We have a multi tier app that have a lot of dependencies. We use Autofac and MEF so that all the components can register their own dependencies in init modules. That way, the "higher" components doesn't have to know all the dependencies graph. It just register the component it needs, and the rest comes along. At the higher level, there is a WCF facade app that imports almost all of our DLL and register them with Autofac. It works fine, but since the repository layer depends on EntityFramework, I get the infamous error :

No Entity Framework provider found for the ADO.NET provider with
  invariant name 'System.Data.SqlClient'. Make sure the provider is
  registered in the 'entityFramework' section of the application config
  file

The only way I found not to have this error is to directly reference EntityFramework.SqlServer in the WCF facade project. But I'd like to leave the responsabllity of this to the repo layer itself. So I would need a way to somehow load the dll and register the System.Data.SqlClient. Does anyone know a way to do so or am I just dreaming ? It's my first time with both Autofac and MEF and I'm far from an expert in DI.
Since it is highly conceptual, here is a little schema with source code to help you understand better :

Get readeable version here

A: Perhaps you could take a look at Code-Based Configuration.

*

*Create a custom DbConfiguration
public class MyDbConfiguration : DbConfiguration
{
    public MyDbConfiguration()
    {
        // Other configuration stuff like SetDefaultConnectionFactory
        SetProviderServices(
            "System.Data.SqlClient",
            System.Data.Entity.SqlServer.SqlProviderServices.Instance);
    }
}

*Add a DbConfigurationTypeAttribute to your DbContext
[DbConfigurationType(typeof(MyDbConfiguration))]
public class MyDbContext : DbContext
{ }

or
[DbConfigurationType("MyNamespace.MyDbConfiguration, MyAssembly")]
public class MyDbContext : DbContext
{ }

*Remove entityFramework configuration from the app.config file
Edit
For your top level project to find assemblies referenced by your MEF components, if you're able/willing to add something to the app.config, maybe you could use something like:
<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <probing privatePath="Libs"/>
  </assemblyBinding>
</runtime>

It would still be a dependency, in a sense, but you do have to add a search path for MEF...
https://msdn.microsoft.com/en-us/library/823z9h8w%28v=vs.110%29.aspx
How can MEF resolve dependencies of assemblies that don't live at the root of the application?


text:
Q: Mi ejecutable no abre Estoy usando Pyinstaller para generar un ejecutable de mi programa.

Uso el siguiente comando en el terminal de Jupyter:
pyinstaller --windowed --onefile --icon=./BASCULAICO.ico Dinamometro2.0.ipynb
Todo bien hasta ahi, me crea el .exe y todo como se ve en la siguiente imagen.

Pero cuando le doy click para finalmente poder abrirlo solo se pone la ruedita de cargando encima del cursor por un segundo y no pasa nada, como si no tuviese nada adentro. No salta ningún error, solo no reacciona
He intentado abrirlo desde el terminal pero me arroja el siguiente error. Ya me  he asegurado de escribirlo correctamente:


text:
Q: Determining Runge-Kutta Order Given the Runge-Kutta Method given by:

$y_{i+1} = y_{i} + \frac{h}{9}(2 K_1 + 3 K_2 + 4K_3)$

with:

$K_1 = f(x_i, y_i) \qquad K_2 = f(x_i + \frac{h}{2}, y_i + \frac{h}{2} K1) \qquad K_3 = f(x_i + \frac{3}{4}h, y_i + \frac{3}{4}h K_2)$

Prove that it's order 3.
If it's order 3 we'll have:

$T_3 - \Phi(xi,yi,h) = O(h^3)$

Where $T_3 = f(x,y(x)) + \frac{h}{2} [f_t + f_x f] + \frac{h^2}{2} [f_{tt} + 2f_{tx} +f_x f_t + f_{xx}f^2 + f_x f_x f]$ is the order 3 taylor expansion.
So my idea was to taylor expand each of the $K_i$:

$K_2 = f + f_t \frac{h}{2} + f_x K_1 \frac{h}{2} \qquad K_3 = f + f_t \frac{3}{4} h + f_x K_2 $

And in the expansion of $K_3$ plug in the expansion of $K_2$, doing that I can match between the two methods the first terms but I'm missing the terms that have $f_{tt}$. So what is missing?. Should I expand $K_3 = f + f_t \frac{3}{4} h + f_x K_2 + (\frac{3}{4}h)^2 [f_{tt} + f_{tx}f + K_2(f_{xt} + f_{xx}f)]$??

A: You should expand more as follows:
$$K_2=f+\frac{h}{2}f_x+\frac{h}{2}ff_y+\frac{1}{2}\left[\frac{h^2}{4}f_{xx}+2\cdot\frac{h}{2}\frac{h}{2}ff_{xy}+\frac{h^2}{4}f^2f_{yy}\right]+O(h^3)\\
K_3=f+\frac{3}{4}hf_x+\frac{3}{4}hf_yK_2+\frac{1}{2}\left[\frac{9}{16}h^2f_{xx}+2\cdot\frac{3}{4}h\frac{3}{4}hK_2f_{xy}+\frac{9}{16}h^2K_2f_{yy}\right]+O(h^3).$$


text:
Q: "3-way" Python subprocess pipeline: send stdout and stderr to two different processes? Can the "standard" subprocess pipeline technique (e.g. http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline) be "upgraded" to two pipelines?
# How about
p1 = Popen(["cmd1"], stdout=PIPE, stderr=PIPE)
p2 = Popen(["cmd2"], stdin=p1.stdout)
p3 = Popen(["cmd3"], stdin=p1.stderr)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
p1.stderr.close()
#p2.communicate()  # or p3.communicate()?

OK, it's actually a different use case, but the closest starting point seems to be the pipeline example. By the way, how does p2.communicate() in a "normal" pipeline drive p1? Here's the normal pipeline for reference:
# From Python docs
output=`dmesg | grep hda`
# becomes
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

I guess I'm ultimately interested in what kind of "process graphs" (or maybe just trees?) can communicate() support, but we'll leave the general case for another day.
Update: Here's the baseline functionality. Without communicate(), create 2 threads reading from p1.stdout and p2.stdout. In the main process, inject input via p1.stdin.write(). The question is whether we can drive a 1-source, 2-sink graph using just communicate()

A: You could use bash's process substitution:
from subprocess import check_call

check_call("cmd1 > >(cmd2) 2> >(cmd3)", shell=True, executable="/bin/bash")

It redirects cmd1's stdout to cmd2 and cmd1's stderr to cmd3.
If you don't want to use bash then the code in your question should work as is e.g.:
#!/usr/bin/env python
import sys
from subprocess import Popen, PIPE
from textwrap import dedent

# generate some output on stdout/stderr
source = Popen([sys.executable, "-c", dedent("""
    from __future__ import print_function
    import sys
    from itertools import cycle
    from string import ascii_lowercase

    for i, c in enumerate(cycle(ascii_lowercase)):
        print(c)
        print(i, file=sys.stderr)
""")], stdout=PIPE, stderr=PIPE)

# convert input to upper case
sink = Popen([sys.executable, "-c", dedent("""
    import sys

    for line in sys.stdin:
        sys.stdout.write(line.upper())
""")], stdin=source.stdout)
source.stdout.close() # allow source to receive SIGPIPE if sink exits

# square input
sink_stderr = Popen([sys.executable, "-c", dedent("""
   import sys

   for line in sys.stdin:
       print(int(line)**2)
""")], stdin=source.stderr)
source.stderr.close() # allow source to receive SIGPIPE if sink_stderr exits

sink.communicate()
sink_stderr.communicate()
source.wait()

A: The solution here is to create a couple of background threads which read the output from one process and then write that into the inputs of several processes:
targets = [...] # list of processes as returned by Popen()
while True:
    line = p1.readline()
    if line is None: break
    for p in targets:
        p.stdin.write(line)


text:
Q: Removing rows from even number columns if certain value is present I have a numpy array with the shape
(500,12)

All I want to do is to check whether the even number columns has a positive value, eg. value > 0. In that case I want to remove the whole row in my array.
I put this up:
a = a[a[:,1] < 0, :]

This eliminates the desired rows but looks at the second column. I want it to check for column 4, column 6, column 8 etc too.
Is there an way of doing that using my method above?

A: If you are dealing with NumPy arrays, then you could use fancy indexing approach (indexing an array with an array sequence of integers) as shown:
mask = (a[:, np.arange(1, a.shape[1], 2)] < 0).all(axis=1)
out = a[mask]

Explanation:
To select positions of odd numbered columns whose values are to be compared:
np.arange(1, a.shape[1], 2)         # a.shape[1] gives the number of columns
# array([ 1,  3,  5,  7,  9, 11])

Next we subset the array based on these indices and see if the values under these columns are lesser than zero by providing axis=1 which performs column-wise check and returns an array containing a reduced number of rows after dropping the remaining ones.

A: Although perhaps not the most efficient way, you can use the elementwise and & for all the rows:
a = a[(a[:,1]<0)&(a[:,3]<0)&(a[:,5]<0)&(a[:,7]<0)&(a[:,9]<0)&(a[:,11]<0),:]
So you mask out all items for which there exists an even column that is positive.
You can make it more elegantly (with a minor performance penalty) by using functools.reduce:
from functools import reduce

a = a[reduce(lambda x,y:x&y,(a[:,i]<0 for i in range(1,12,2))),:]
In case the shape is not fully known in advance, you can use .shape[1]:
from functools import reduce

a = a[reduce(lambda x,y:x&y,(a[:,i]<0 for i in range(1,a.shape[1],2))),:]

A: The general way is to build a list comprehension with a condition:
a = [row for row in a if all(row[j] <= 0 for j in range(0, len(row), 2))]

A: If you don't want a loop (as it iteratively shrinks your dataframe with some associated overhead):
m = (arr > 0) # check if positive; this is what you want to keep
m = arr.ix[:,1::2] # select only the even columns
m = arr.any(axis=1) # and check if any of them is true

So in one line:
 arr[(arr > 0)[:,1::2].all(axis=1),:]

A: Without using a loop, there is no single command that will help you with your motive. I suggest looping over all the rows and then doing this.


text:
Q: How to get Last entry of Particular ID Below is my query I want to fetch last entry of visitno ,of particular pid,this query works fine but selects all rows of pid ,visistNo is of Number Datatype
public int GetPatientID_visitNo(int pid)
    {
        int data = 0;
        try
        {
            string sql = "Select VisitNo From Patient_Visit_Details where Patient_ID = " + pid;
            cmd = new OleDbCommand(sql, acccon);
            rs = cmd.ExecuteReader();
            if (rs.HasRows)
            {
                data = Convert.ToInt32(rs[0]);
            }
        }
        catch (Exception err)
        {
        }
        return data;
    }

when I try below Query it gives me error no data exist since my table is new and it dosn't contain any row ,how I can Do this
string sql = "Select MAX(VisitNo) From Patient_Visit_Details where Patient_ID = " + pid;

A: string sql = string.Format(@"SELECT TOP 1 VisitNo
                             FROM patient_Visit_Details
                             WHERE Patient_ID = {0}
                             ORDER BY VisitNo DESC", pid);

Also, use cmd.ExecuteScalar() for this.  Check the return value for when there are no rows.
Note also,  that if pid has arrived from somewhere outside your application (e.g. a web page), your sql is open to Injection attack.
Now, as has been pointed out - what if there are no rows?  See this question here: Handling ExecuteScalar() when no results are returned, the ethos being - check for null and DbNull.Value before trying to convert to an Int32.

A: change SQL statement as beloe
string sql = "Select ISNULL(MAX(VisitNo), 0)  From Patient_Visit_Details where Patient_ID = " + pid;

use ExecuteScalar and add validation for null result
var maxVisit = cmd.ExecuteScalar();

if (maxVisit != null && maxVisit != DBNull.Value)
{
   data = Convert.ToInt32(maxVisit);
}


text:
Q: Print last occurrence of a tag in a log file using awk We need to do some monitoring of a large log file to find the last line that a tag (in this case a currency pair) appeared.
Log looks like this:
20141217-10:34:48.411: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=AUD/USD^A15=USD^A279=2^A269=1.245
20141217-10:34:48.415: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=GBP/AUD^A15=GBP^A279=2^A269=1.245
20141217-10:34:48.465: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=AUD/NZD^A15=AUD^A279=2^A269=1.245
20141217-10:34:48.466: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=EUR/NZD^A15=EUR^A279=2^A269=1.245
20141217-10:34:48.466: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=AUD/USD^A15=AUD^A279=2^A269=1.245
20141217-10:34:48.507: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=GBP/AUD^A15=CAD^A279=2^A269=1.245
20141217-10:34:48.526: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=AUD/USD^A15=EUR^A279=2^A269=1.245
20141217-10:34:48.528: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=USD/CAD^A15=USD^A279=2^A269=1.245
20141217-10:34:48.529: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=AUD/CAD^A15=AUD^A279=2^A269=1.245
20141217-10:34:48.544: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=EUR/AUD^A15=EUR^A279=2^A269=1.245
20141217-10:34:48.546: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=EUR/NZD^A15=USD^A279=2^A269=1.245
20141217-10:34:48.554: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=GBP/AUD^A15=GBP^A279=2^A269=1.245
20141217-10:34:48.563: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=AUD/USD^A15=CAD^A279=2^A269=1.245
20141217-10:34:48.563: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=EUR/NZD^A15=EUR^A279=2^A269=1.245
20141217-10:34:48.563: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=GBP/AUD^A15=AUD^A279=2^A269=1.245
20141217-10:34:48.563: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=EUR/NZD^A15=CHF^A279=2^A269=1.245
20141217-10:34:48.607: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=EUR/NZD^A15=CAD^A279=2^A269=1.245
20141217-10:34:48.615: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=GBP/AUD^A15=EUR^A279=2^A269=1.245
20141217-10:34:48.616: 8=FIX.4.2^A35=X^A56=ABCD_MD^A55=AUD/USD^A15=AUD^A279=2^A269=1.245

which matches the pattern:
\d{8}-\d\d:\d\d:\d\d\.\d\d\d.*35=X.*\w{3}/\w{3}

where
The date:                        \d{8}-\d\d:\d\d:\d\d\.\d\d\d
Denotes a price message:         35=X
A currency pair e.g. AUD/USD:    \w{3}/\w{3}

(Regex syntax is probably different in awk)
Would be great to have an awk script which outputs the last pricing message (line containing 35=X) for each currency pair, and the timestamp that was at the start of that line.  E.g.
20141217-10:34:48.529 AUD/CAD
20141217-10:34:48.465 AUD/NZD
20141217-10:34:48.616 AUD/USD
20141217-10:34:48.544 EUR/AUD
20141217-10:34:48.607 EUR/NZD
20141217-10:34:48.615 GBP/AUD
20141217-10:34:48.528 USD/CAD

The logs are naturally date ordered.  So I'd just need the last line per currency pair.  There would not need to be any sorting done on the actual date string.
The logs are very large.  Easily over 1GB.
Any help would be greatly appreciated.
Cheers

A: Here's the script:
awk -F' |=|\\^A' '{a[$9]=$1 " " $9} END{for(var in a)print a[var]}' File

Here we assign space and = and ^A as delimiters. Then 1st field will be time and 9th field will be your currency pair. With this 9th field as index, build up the array a (fill array with 1st field and currecny pair, latest values will be taken as the previous entry for the same index will be overwritten. Then in the END block, go through the array and print the array element.
Output:
SO$ awk -F' |=|\\^A' '{a[$9]=$1 " " $9} END{for(var in a)print a[var]}' File
20141217-10:34:48.528: USD/CAD
20141217-10:34:48.615: GBP/AUD
20141217-10:34:48.544: EUR/AUD
20141217-10:34:48.529: AUD/CAD
20141217-10:34:48.607: EUR/NZD
20141217-10:34:48.465: AUD/NZD
20141217-10:34:48.616: AUD/USD

A: You can use this awk command:
awk -F ': |[=^]' '{a[$9]=$1} END{for (i in a) print a[i], i}' file.log
20141217-10:34:48.615 GBP/AUD
20141217-10:34:48.528 USD/CAD
20141217-10:34:48.465 AUD/NZD
20141217-10:34:48.529 AUD/CAD
20141217-10:34:48.616 AUD/USD
20141217-10:34:48.607 EUR/NZD
20141217-10:34:48.544 EUR/AUD

This will change the order of output. If you want to maintain original order then use:
awk -F ': |[=^]' '!a[$9]{b[++n]=$9} {a[$9]=$1}
          END{for (i=1; i<=n; i++) print a[b[i]], b[i]}' file.log
20141217-10:34:48.616 AUD/USD
20141217-10:34:48.615 GBP/AUD
20141217-10:34:48.465 AUD/NZD
20141217-10:34:48.607 EUR/NZD
20141217-10:34:48.528 USD/CAD
20141217-10:34:48.529 AUD/CAD
20141217-10:34:48.544 EUR/AUD

A: This is far more memory efficient than the other answers and maintains order
tac test | awk 'match($0,/A55=([^^]+)\^/,a)&&!b[a[1]]++{print $1,a[1]}' | tac

It reverses the file and pipes into awk, which prints the last(now first) occurence of each currency, then pipes back into tac to restore original order
OP suggested this is quicker than the match
tac test | awk -F' |=|\\^A' '$5=="X"&&!a[$9]++{print $1,$9}' | tac


text:
Q: Android, Get gallery image and store in integer I am working on fetching images from gallery and i want to store the image selected in a integer.
I have tried everything but nothing is helping me,
my code is
private void getGalleyImage() {
    Intent fileChooserIntent = new Intent();
    fileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
    fileChooserIntent.setType("image/*");
    fileChooserIntent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(
            Intent.createChooser(fileChooserIntent, "Select Picture"), 1);

}

i am getting images but i am not able to store that image in integer, i have tried uri and bitmap then bytearray,
I want to store them in integer.
thanks in advance.


text:
Q: Finding Average amount in excel for two values I have a question regarding an excel sheet. I'm trying to find how many times something occurs on a specific date. For example:
Date                    User
1/1/2014 0:00           Michael Albanese
1/1/2014 0:00           Linus Nienstadt
1/1/2014 0:01           Omar Albanese

I want to find how many times Michael Albanese occurred in 2014
I've tried the following, but it returns an error.
=COUNTIFS(F2:F482240,"=Michael Albanese",E2:E482240,"=1/1/2014")

... it then says one, but there's at least three

A: Use SUMPRODUCT():
=SUMPRODUCT((YEAR($A$2:$A$4)=2014)*($B$2:$B$4="Michael Albanese"))

If your dates are text that looks like dates then use this:
=SUMPRODUCT((ISNUMBER(SEARCH(2014,$A$2:$A$4)))*($B$2:$B$4="Michael Albanese"))

A: The COUNTIFS function may be more efficient than the SUMPRODUCT function in this case.
=COUNTIFS(F:F, "Michael Albanese", E:E,">="&DATE(2014, 1, 1), E:E,"<"&DATE(2015, 1, 1))

A: =SUMPRODUCT((YEAR(L2:L4)=2014)*(M2:M4="Michael Albanese"))

L2:L4 is your date stored in an Excel date serial format but can be formatted as text.
M2:M4 is your list of names
If your date time is stored as text you could try
=SUMPRODUCT((MID(L2:L4,FIND(" ",L2:L4)-4,4)*1=2014)*(M2:M4="Michael Albanese"))

A: Findwindow is correct.  Here is a quick example.
=COUNTIFS(A2:A10,"<1/1/2015",A2:A10,">12/31/2013",B2:B10,"=Michael Albanese")


text:
Q: CSS Word Break and Word Wrap is not working May I seek help,
Word Wrap or Word break is not working on my string,
This is the text,
The company's revenue has been increasing for the last five years with an overall growth of 49% between 2015 and 2019. Revenue increased 7% to $426.4 million for the year ended December 29, 2019, as compared to $398.2 million for the year ended December 30, 2018. The increase was primarily driven by $28.5 million in incremental revenue from an additional 359 operating weeks provided by new restaurants opened during and subsequent to the year ended December 30, 2018 as well as an increase in its comparable restaurant sales. Net income increased by $0.7 million and 12% to $6.2 million for the year ended December 29, 2019 as compared to $5.5 million during the comparable period in 2018. This was due to the increase in depreciation and amortization costs, as well as the increase in income tax benefits. The company's cash equivalents at the end of 2019 totaled $10.1 million, an increase of $2 million from the previous year. Operating activities generated $43.4 million, while investing activities used $33.3 million. Financing activities used another $8.3 million primarily for common stock repurchases and line of credit payments.
This is my CSS
.txt {
  word-break: break-all;
  word-wrap: break-word;
  min-height:150px;
  max-width:150px;
  overflow-x: auto;
}

Here is my HTML

{{ $value }}

What happens is

The string is not breaking it shows in one line, even if overflow is hidden or not,

A: It seems to work fine:

.txt {
  word-break: break-all;
  word-wrap: break-word;
  min-height:150px;
  max-width:150px;
  overflow-x: auto;
}

The company's revenue has been increasing for the last five years with an overall growth of 49% between 2015 and 2019. Revenue increased 7% to $426.4 million for the year ended December 29, 2019, as compared to $398.2 million for the year ended December 30, 2018. The increase was primarily driven by $28.5 million in incremental revenue from an additional 359 operating weeks provided by new restaurants opened during and subsequent to the year ended December 30, 2018 as well as an increase in its comparable restaurant sales. Net income increased by $0.7 million and 12% to $6.2 million for the year ended December 29, 2019 as compared to $5.5 million during the comparable period in 2018. This was due to the increase in depreciation and amortization costs, as well as the increase in income tax benefits. The company's cash equivalents at the end of 2019 totaled $10.1 million, an increase of $2 million from the previous year. Operating activities generated $43.4 million, while investing activities used $33.3 million. Financing activities used another $8.3 million primarily for common stock repurchases and line of credit payments.

Did you "inspect" your div to see if some other css rule is messing the thing?

When you hit F12 in your browser and then select your div either by clicking on it (1 or 2), you'll see what styles are applied to it in 3.
You'll likely see word-break: break-all; or the same with word-wrap because it is overriden by some other rule.

A: you can do this instead of nesting div into td

.txt {
  word-break: break-all;
  word-wrap: break-word;
  min-height:150px;
  max-width:150px;
}

    skdjfhskadjfhsdlkajfhdsakljfhsdakjfhslkadjfhsdalkjfhsadlkjfhsdalkjfhsadlkjfhsdakljfhsdalkjfhsadlkjfhsdalkjfhsladkjfhslakjfhlskadjfh


text:
Q: Saving out a javascript object? Is it possible to save out some javascript object purely on client-side?
My question come from the following workflow: a user enters and posts a text, i do some processing on the server side and return processed text to the user. The user can do some modifications to the returned text, if he doesn't like some processed parts of it. Is there any client-side javascript functionality so the user pressed the button 'save' and it pops a save file dialog as if the user downloaded this file from a server? Or I need a server interaction for example to post the results and return them to the users as a file?

A: No. Unassisted JavaScript cannot save files (IE with activeX/WHS can use the file system, mozilla products may have something here which I have not investigated)
But you can popup a window or write it to an iframe which can be printed to for example PDF which is saved on the client

A: with javascrpipt you don't have access to the filesystem on the clients pc (except of the cookies). so you have to send him a downloadable file.

A: You could implement this functionality with a server side functionality, but not with JavaScript. Pressing 'Save' would create an AJAX call to the server which responds with the file correct headers, making the browser respond with a "Save file" dialog.


text:
Q: Como limpiar un autocomplete de primefaces convirtiendolo a nulo dando click a un command button en jsf con primefaces? tengo un problema a la hora de querer dar click en un commandbutton lo que quiero hacer mas que nada es limpiar un autocomplete de primefaces cuando de click, tengo entendido que se tiene volver nulo, este es mi codigo del autocomplete:
                <p:autoComplete id="modelodispositivo"
                                placeholder="Buscar Dispositivo"
                                value="${controlVersionesBean.controlVersion}"
                                emptyMessage="No hay información con este criterio de búsqueda"
                                completeMethod="${controlVersionesBean.buscarDispositivo}"
                                var="modelodispositivo"
                                itemLabel="${modelodispositivo.device_name}"
                                itemValue="${modelodispositivo}"
                                scrollHeight="250"
                                required="true"
                                converter="entityConverter"
                                forceSelection="true"
                                requiredMessage="¡Campo requerido!"
                                onkeypress="return alfanumerico(event)"
                                style="width: 20%;"
                                >
                </p:autoComplete>

Y este es mi codigo java quiero usar para borrar:
  public void Reset() {
        controlVersion = new ControlVersionesDTO();
        controlVersion = null;
        listControlVersionesFiltradas = new ArrayList<>();
        listaDispositivos = new ArrayList<>();
        listaDispositivosFilter = new ArrayList<>();
//        listControlVersionesFiltradas=null;
//        listaDispositivos=null;
//        listControlVersiones=null;
        //controlVersion.setDevice_name(null);

        RequestContext.getCurrentInstance().update("data_table");
        RequestContext.getCurrentInstance().update("modelodispositivo");
        RequestContext.getCurrentInstance().execute("cancelar()");

    }

controlVersion es el nombre de mi objeto, espero y me puedan ayudar por favor, saludos y quedo al pendiente.

A: ya lo pude solucionar, dejo el codigo:
listControlVersiones.clear();

Solo busqué la lista que llena el autocomplete y solo usé el clear para borrar la lista y ya con eso desaparecio, espero y les sirvan, saludos.


text:
Q: Jwt Tymon laravel 5.1 + angularjs multiple async call error user_not_found I'm using a Laravel Api and AngularJs frontend.
I have a problem with a middleware JWT.auth (tymondesign library) because if I do multiple asynchronous request from my frontend angularjs to backend api Laravel, sometimes (yes not always return error), return a 404 error "user_not_found" by middleware.
But doesn't return error in all request but in some.
I have no idea why this happens.
More clearly:
I have 4 ajax call from Angularjs Service that return a promise and in back end I have a route group under middleware JWT.auth
In my angularjs controller 4 call from 4 different services:
User.findAll().then(function(data){ $scope.users = data },function(err){});
Alert.findAll().then(function(data){ $scope.alerts = data},function(err){});
Workgroups.findAll().then(function(data){ $scope.workgroups = data},function(err){});
Usergroups.findAll().then(function(data){ $scope.usergroups = data},function(err){});

And backend example (I'm sorry for syntax):
Route::group(['middleware'=>['jwt.auth']){
        Route::get('findAllUsers','userController@findAll');
        Route::get('findAlerts','alertController@findAll');
        Route::get('findAllWorkgroups','workgroupsController@findAll');
        Route::get('findAllUsergroups','usergroupsController@findAll');
    }

And someTimes one of this calls return exception from middleware Jwt : 404, "user_not_found".
For more information, I'm using Laravel 5.1 and Tymon JWT 0.5.6-master and The token is passed by header Authorization.
Is it a bug or am I doing something wrong?


text:
Q: adjusting the speed of movement My task is to convert a movement from a straight path to a curved path.
the starting and ending points are given as well as the starting time and speed.
$ns_ at 2.000000000000 "$node_(0) setdest 90.441179033457 44.896095544010
1.373556960010"
this line above defines that node_(0) at time 2.0s starts to move toward destination (90.44, 44.89) at a speed of 1.37m/s.

I have to change the movement to be along a curved path which will be 4 movements instead of one.

I need to adjust the speed in order to get the destination of fractal path at the same time of the straight path.
I am not sure about how to get at B in fractal path at the same time of straight path?
I am thinking of calculating the time first of the straight path by the formula Time= distance/ speed. and then divide the time by 4 (cz will be 4 movements instead of one) But then I am not sure how to adjust the speed.
any ideas to help me will be appreciated !!

A: You need to compute the total length of the second curve, which should be (if this is the von Koch snowflake construction) 4/3 of the original curve (hence, assuming AP=PQ=QR=RB).
So your first speed should be three quarters of the speed in the second curve so that both arrive in the same time (or conversely, four third if the reference curve is the first curve).
However, since you are mentioning fractals, you should be aware that repeating the subdivision process will result in a line of infinite length : your straight path speed should be infinitely slow because it will take an infinite amount of time to follow the second path. That's when you have an infinite number of subdivisions... it will not happen in practice though :)


text:
Q: How to copy an NSMutableArray to anotherNSMutableArray If i have 2 NSMutableArray declared in .h, synthesize in .m files,
how can i copy whole contents of array 1 to 2? actually the same array.
I tried using this code only:
[self.data addObjectsFromArray:self.temparray]
to copy data from temparray to data.
doesn't seems to work.....

A: Did you initialize your self.data at all? I.e. self.data = [NSMutableArray array]; somewhere.
If you did, please post some code.

A: - (NSArray *)arrayByAddingObjectsFromArray:(NSArray *)otherArray

is the method your looking for.


text:
Q: Why does adding ".map(a -> a)" allow this to compile? This is related to my answer to "stream reduction incompatible types". I don't know why what I suggested works, and Holger rightly pressed me on this. But even he doesn't seem to have a clear explanation for why it works. So, let's ask it as its own question:
The following code does not compile in javac (for the links to ideone below, this is sun-jdk-1.8.0_51, per http://ideone.com/faq):
public <T> Object with(Stream<Predicate<? super T>> predicates) {
  return predicates.reduce(Predicate::or);
}

And rightly so: or-ing together two predicates from this stream is like writing:
Predicate<? super T> a = null;
Predicate<? super T> b = null;
a.or(b);  // Compiler error!

However, it does compile in intellij, although with a raw type warning on the Predicate::or method reference. Apparently, it would also compile in eclipse (according to the original question).
But this code does:
public <T> Object with(Stream<Predicate<? super T>> predicates) {
  return predicates.map(a -> a).reduce(Predicate::or);
                // ^----------^ Added
}

Ideone demo
Despite the fact I thought to try this, it's not exactly clear to me why this would work. My hand-wavy explanation is that .map(a -> a) acts like a "cast", and gives the type inference algorithm a bit more flexibility to pick a type which allows the reduce to be applied. But I'm not sure exactly what that type is.
Note that this isn't equivalent to using .map(Function.identity()), because that is constrained to return the input type. ideone demo
Can anybody explain why this works with reference to the language spec, or if, as suggested by Holger, it is a compiler bug?

A bit more detail:
The return type of the method can be made a bit more specific; I omitted it above so that the nasty generics on the return type wouldn't get in the way:
public <T> Optional<? extends Predicate<? super T>> with(
    Stream<Predicate<? super T>> predicates) {
  return predicates.map(a -> a).reduce(Predicate::or);
}

This is the output of compiling with -XDverboseResolution=all. Not entirely sure if this is the most relevant output I can post to debug the type inference; please advise if there is something better:
Interesting.java:5: Note: resolving method <init> in type Object to candidate 0
class Interesting {
^
  phase: BASIC
  with actuals: no arguments
  with type-args: no arguments
  candidates:
      #0 applicable method found: Object()

Interesting.java:7: Note: resolving method map in type Stream to candidate 0
    return predicates.map(a -> a).reduce(Predicate::or);
                     ^
  phase: BASIC
  with actuals: <none>
  with type-args: no arguments
  candidates:
      #0 applicable method found: <R>map(Function<? super T#1,? extends R>)
        (partially instantiated to: (Function<? super Predicate<? super T#2>,? extends Object>)Stream<Object>)
  where R,T#1,T#2 are type-variables:
    R extends Object declared in method <R>map(Function<? super T#1,? extends R>)
    T#1 extends Object declared in interface Stream
    T#2 extends Object declared in method <T#2>with(Stream<Predicate<? super T#2>>)

Interesting.java:7: Note: Deferred instantiation of method <R>map(Function<? super T#1,? extends R>)
    return predicates.map(a -> a).reduce(Predicate::or);
                         ^
  instantiated signature: (Function<? super Predicate<? super T#2>,? extends Predicate<CAP#1>>)Stream<Predicate<CAP#1>>
  target-type: <none>
  where R,T#1,T#2 are type-variables:
    R extends Object declared in method <R>map(Function<? super T#1,? extends R>)
    T#1 extends Object declared in interface Stream
    T#2 extends Object declared in method <T#2>with(Stream<Predicate<? super T#2>>)
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Object super: T#2 from capture of ? super T#2

Interesting.java:7: Note: resolving method reduce in type Stream to candidate 1
    return predicates.map(a -> a).reduce(Predicate::or);
                                 ^
  phase: BASIC
  with actuals: <none>
  with type-args: no arguments
  candidates:
      #0 not applicable method found: <U>reduce(U,BiFunction<U,? super T,U>,BinaryOperator<U>)
        (cannot infer type-variable(s) U
          (actual and formal argument lists differ in length))
      #1 applicable method found: reduce(BinaryOperator<T>)
      #2 not applicable method found: reduce(T,BinaryOperator<T>)
        (actual and formal argument lists differ in length)
  where U,T are type-variables:
    U extends Object declared in method <U>reduce(U,BiFunction<U,? super T,U>,BinaryOperator<U>)
    T extends Object declared in interface Stream

Interesting.java:7: Note: resolving method metafactory in type LambdaMetafactory to candidate 0
    return predicates.map(a -> a).reduce(Predicate::or);
                          ^
  phase: BASIC
  with actuals: Lookup,String,MethodType,MethodType,MethodHandle,MethodType
  with type-args: no arguments
  candidates:
      #0 applicable method found: metafactory(Lookup,String,MethodType,MethodType,MethodHandle,MethodType)

Interesting.java:7: Note: resolving method metafactory in type LambdaMetafactory to candidate 0
    return predicates.map(a -> a).reduce(Predicate::or);
                                         ^
  phase: BASIC
  with actuals: Lookup,String,MethodType,MethodType,MethodHandle,MethodType
  with type-args: no arguments
  candidates:
      #0 applicable method found: metafactory(Lookup,String,MethodType,MethodType,MethodHandle,MethodType)

A: Unless I am missing something in how FunctionalInterface inferences occur, it seems pretty obvious that you can't call reduce on a Stream < ? super Predicate > because it does not have sufficient typing to be inferred as a BinaryOperator.
The method reference hides a very important part of the story, the second parameter.
return predicates.map(a->a).reduce((predicate, other) -> predicate.or(other));

If you remove the call to map, the compiler does not have the opportunity to type the stream appropriately to satisfy the second capture requirements.  With map the compiler is given the latitude to determine the types required to satisfy the captures, but without a concrete binding of the generics the two captures can only be satisfied with a Stream of Object which is likely what would result through map().
The Predicate interface as implemented now is simply building a chain, but the use is expected to be a composed entity.  It is assumed to take a single parameter, but in fact the nature of AND and OR require two parameters without a type guarantee because of the shortcomings of Java's generics.  In this way the API seems to be less than ideally designed.
The call to map() cedes the control of the typing, from the explicit Stream of Predicates, to one the compiler can guarantee will satisfy all captures.
The following both satisfy the compiler in IDEone, by directly inducing a flexible enough type in the case of Object, or a known type in the case of T.
public <T> Optional<? extends Predicate<? super T>> with(Stream<Predicate<Object>> predicates)
public <T> Optional<? extends Predicate<? super T>> with(Stream<Predicate<T>> predicates)

Java generics still need a way to force capture type equivalence, as the helper methods are clearly not enough.


text:
Q: Restart NodeJS app automatically after app crashes I want to add code to my NodeJS (Express) app so that it will restart automatically after crashes with some error. I know about forever npm package, but I found only examples with running app in development, while my goal is to use it in production (app is already on production server). Should I add some code inside app.js (main file for my application) or in different files?
Here's my app.js code:
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const path = require("path");
const con = require("./databaseConnection");

const app = express();

/* Middleware */
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

/* Redirect http to https */
app.enable('trust proxy');
app.use (function (req, res, next) {
    if (req.secure) {
        // request was via https, so do no special handling
        next();
    } else {
        // request was via http, so redirect to https
        res.redirect('https://' + req.headers.host + req.url);
    }
});

/* Routers */
const authRouter = require("./routers/authRouter");
const userRouter = require("./routers/userRouter");

app.use("/auth", authRouter);
app.use("/user", userRouter);

app.listen(5000);

A: I think the program you are looking for is pm2. https://pm2.keymetrics.io/docs/usage/quick-start/
You could listen for any unhandled exceptions/errors and handle them to stop the server crashing because of an uncaught error, but there are a bunch more problems that could happen with the process itself that would go unhandled such as memory leaks, which is why you need to use a process manager rather than something internal inside your express server.
It's better to use the pm2 daemon to manage the server processes for you, it also comes with a built-in dashboard, logging, and useful restarting configuration options such as

*

*Restart app at a specified CRON time

*Restart app when files have changed

*Restart when app reach a memory threshold

*Delay a start and automatic restart

*Disable auto restart (app are always restarted with PM2) when crashing or exiting by default)

*Restart application automatically at a specific exponential increasing time


text:
Q: Unexpected result in WHERE clause on AI ID field I have a table which's name is users in my MySQL database, and I am using this DB with Ruby on Rails application with ORM structure for years. The table has id field and this field is configured as AI (auto-increment), BIGINT.
Example of my users table;
+----+---------+
| id | name    |
+----+---------+
|  1 | John    |
|  2 | Tommy   |
|  3 | ...     |
|  4 | ...     |
|  5 | ...     |
|  6 | ...     |
+----+---------+

The problem I am facing is when I execute the following query I get unexpected rows.
SELECT * FROM users WHERE id = '1AW3F4SEFR';

This query is returning the exact same value with the following query,
 SELECT * FROM users WHERE id = 1;

I do not know why SQL let me use strings in WHERE clause on a data type INT. And as we can see from the example, my DB converts the strings I gave to the integer at position 0. I mean, I search for 1AW3F4SEFR and I expect not to get any result. But SQL statement returns the results for id = 1.
In Oracle SQL, the behavior of this exact same query is completely different. So, I believe there is something different on MySQL. But I am not sure about what causes this.

A: As has been explained in the request comments, MySQL has a weird way of converting strings to numbers. It simply takes as much of a string from the left as is numeric and ignores the rest. If the string doesn't start with a number the conversion defaults to 0.
Examples: '123' => 123, '12.3' => 12.3, '.123' => 0.123, '12A3' => 12, 'A123' => 0, '.1A1.' => 0.1
Demo: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=55cd18865fad4738d03bf28082217ca8
That MySQL doesn't raise an error here as other DBMS do, can easily lead to undesired query results that get a long time undetected.
The solution is easy though: Don't let this happen. Don't compare a numeric column with a string. If the ID '1AW3F4SEFR' is entered in some app, raise an error in the app or even prevent this value from being entered. When running the SQL query, make sure to pass a numeric value, so '1AW3F4SEFR' cannot even make it into the DBMS. (Look up how to use prepared statements and pass parameters of different types to the database system in your programming language.)
If for some reason you want to pass a string for the ID instead (I cannot think of any such reason though) and want to make your query fail-safe by not returning any row in case of an ID like '1AW3F4SEFR', check whether the ID string represents an integer value in the query. You can use REGEXP for this.
SELECT * FROM users WHERE id = @id AND @id REGEXP '^[0-9]+$';

Thus you only consider integer ID strings and still enable the DBMS to use an index when looking up the ID.
Demo: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=56f8ee902342752933c20b8762f14dbb


text:
Q: Ricci flow of the Torus Let us consider the torus  of revolution, say $T$, and consider a local parametrisation
\begin{aligned}x(\theta ,\varphi )&=(R+r\cos \theta )\cos {\varphi }\\y(\theta ,\varphi )&=(R+r\cos \theta )\sin {\varphi }\\z(\theta ,\varphi )&=r\sin \theta. \end{aligned}
Given $T$ the induced metric of $\mathbb E^3$, we have in local coordinates $(\theta,\varphi)$ that we can write the metric as
\begin{aligned} g|_T=r^2d\theta^2+(R+r\cos\theta)^2d\varphi^2.\end{aligned}
I know that
\begin{aligned} Ric_{g|_T}=\frac {r\cos\theta}{R+r\cos\theta}d\theta^2+\frac 1r\cos\theta(R+r\cos\theta)d\varphi^2.\end{aligned}
How can I, if it is even possible, find the explicit solution of the Ricci flow:
\begin{aligned} \partial_tg=-2Ric_g\\g(0)=g|_T~~~\end{aligned}
(I have seen how it is done for the sphere, cigar soliton, and the immortal solution stated in The Ricci Flow: An Introduction -- by Bennet Chow and Dan Knopf.)
If it is not possible, why? Thanks in advance.

A: Consider a point of negative curvature. Here metric is increasing so that $R,\ r$ goes to $\infty$. Hence a limit is flat metric.
Reference : Richard S. Hamilton. The Ricci flow on surfaces.


text:
Q: regex php multiple instances and pairs I have $user->id = '1{3}4{5}6';//could be any and more but {X}X are pairs

*

*1 represents a regular product_id but is not needed for the end
result.

*{3} and {5} represents $option

*4  and  6 represents $value

*{3}4 and {5}6 are pairs

I require for each pair a db insertion.
How can i take the values out and run the following db execution:
//Something like for each ?? as option and ?? as $value do:
$sth = $this->dbh->prepare("insert into customers_basket_attributes
(
products_id,
products_options_id,
products_options_value_id
)
values (?, ?, ?)");
$sth->execute(array($user->id, $option, $value));

Current code with the accepted answer from *Anubhava*
if ($user->attr = 1) {
if (preg_match_all('/\{(\d+)\}(\d+)/u', $user->id, $m )) {
 $option1 = $m[1];
 $value2 = $m[2];
 $output = array_combine ( $option1, $value2 );

$sth = $this->dbh->prepare("insert into customers_basket_attributes (customers_id, products_id, products_options_id, products_options_value_id) values ('1', ?, ?, ?)");
 foreach($output as $option => $value) {
$sth->execute(array($user->id, $option, $value));
}

}
}
return json_encode(1);

Seems to work for prepared statements.

A: You can use preg_match_all like this:
$str = '1{3}4{5}6';
if (preg_match_all('/\{(\d+)\}(\d+)/u', $str, $m )) {
   $output = array_combine ( $m[1], $m[2] );
   print_r($output);
}

OUPUT
Array
(
    [3] => 4
    [5] => 6
)


text:
Q: View Model not updating Im currently practicing how to use WPF on C#, ive gotten the basics of it but im facing an issue, ive set up my code to open a new window when a button is clicked however the view does not update to how window 2 is supposed to look it just shiws the same view as window1 but the changing from window to window is working just the content is not changing.
Window one cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PROG6221_POE_Tarisai_Gonah_18028480
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OpenWindow(object sender, RoutedEventArgs e)
        {
            Task1 f1 = new Task1();
            this.Visibility = Visibility.Hidden;
            f1.Show();
        }
    }
}

Window 2 cs:
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace PROG6221_POE_Tarisai_Gonah_18028480
{
    /// <summary>
    /// Interaction logic for Task1.xaml
    /// </summary>
    public partial class Task1 : Window
    {
        public Task1()
        {
            InitializeComponent();
        }

        private void OpenWindow(object sender, RoutedEventArgs e)
        {
            //Expenses objexp = new Expenses();
            //this.Visibility = Visibility.Hidden;
            //objexp.Show();

            MainWindow f1 = new MainWindow();
            this.Visibility = Visibility.Hidden;
            f1.Show();

        }

        private void ButtonClick(object sender, RoutedEventArgs e)
        {

        }
    }
}

Window 1 xaml and window 2 xaml are completely different but when i click the button it does show the windows 2 design.
window 1 xaml:
<Window x:Class="PROG6221_POE_Tarisai_Gonah_18028480.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PROG6221_POE_Tarisai_Gonah_18028480"
        mc:Ignorable="d" FontSize="18"
        Title="Finance Savings Calculator" Height="550" Width="900">
    <Grid RenderTransformOrigin="0.529,0.484" Background="{DynamicResource {x:Static SystemColors.ActiveCaptionBrushKey}}" OpacityMask="{DynamicResource {x:Static SystemColors.ActiveCaptionBrushKey}}">

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="46*"/>
            <ColumnDefinition Width="0*"/>
            <ColumnDefinition Width="179*"/>

        </Grid.ColumnDefinitions>
        <TextBlock HorizontalAlignment="Left" Text="                                                    Welcome to the finance calculator" TextWrapping="Wrap" Width="900" FontSize="24" FontWeight="Bold" Margin="0,10,0,486" Foreground="Black" Background="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" Grid.ColumnSpan="3" FontFamily="Imprint MT Shadow" TextDecorations="{x:Null}"/>

        <Button Content="HOME" HorizontalAlignment="Center" VerticalAlignment="Top" Width="184" Height="38" Click="Button_Click" Background="#FF20D6FF" FontWeight="Bold" BorderBrush="{DynamicResource {x:Static SystemColors.InactiveCaptionTextBrushKey}}" Margin="0,48,0,0"/>

        <Button Content="Task 1" HorizontalAlignment="Center" VerticalAlignment="Top" Width="184" Height="38" Click="OpenWindow" Background="#FF20D6FF" FontWeight="Bold" Margin="0,118,0,0" Foreground="{DynamicResource {x:Static SystemColors.ActiveCaptionTextBrushKey}}" BorderBrush="{DynamicResource {x:Static SystemColors.DesktopBrushKey}}"/>
        <TextBlock Grid.Column="2" HorizontalAlignment="Left" Height="59" Margin="39,89,0,0" Text="This is a finance calculator. This app is designed to track your monthly expenses and income" TextWrapping="Wrap" VerticalAlignment="Top" Width="677" FontFamily="Arial Black"/>

    </Grid>
</Window>

Window 2 xaml:
<Window x:Class="PROG6221_POE_Tarisai_Gonah_18028480.Task1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PROG6221_POE_Tarisai_Gonah_18028480"
             mc:Ignorable="d" FontSize="18"
        Title="Finance Savings Calculator" Height="550" Width="900">
    <Grid RenderTransformOrigin="0.529,0.484" Background="{DynamicResource {x:Static SystemColors.ActiveCaptionBrushKey}}" OpacityMask="{DynamicResource {x:Static SystemColors.ActiveCaptionBrushKey}}">

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="46*"/>
            <ColumnDefinition Width="0*"/>
            <ColumnDefinition Width="179*"/>

        </Grid.ColumnDefinitions>
        <TextBlock HorizontalAlignment="Left" Text="                                                    Welcome to the finance calculator" TextWrapping="Wrap" Width="900" FontSize="24" FontWeight="Bold" Margin="0,10,0,486" Foreground="Black" Background="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" Grid.ColumnSpan="3" FontFamily="Imprint MT Shadow" TextDecorations="{x:Null}"/>

        <Button Content="HOME" HorizontalAlignment="Center" VerticalAlignment="Top" Width="184" Height="38" Click="OpenWindow" Background="#FF20D6FF" FontWeight="Bold" BorderBrush="{DynamicResource {x:Static SystemColors.InactiveCaptionTextBrushKey}}" Margin="0,48,0,0"/>

        <Button Content="Task 1" HorizontalAlignment="Center" VerticalAlignment="Top" Width="184" Height="38" Click="ButtonClick" Background="#FF20D6FF" FontWeight="Bold" Margin="0,118,0,0" Foreground="{DynamicResource {x:Static SystemColors.ActiveCaptionTextBrushKey}}" BorderBrush="{DynamicResource {x:Static SystemColors.DesktopBrushKey}}"/>
        <Rectangle Grid.Column="2" HorizontalAlignment="Center" Height="427" Stroke="Black" VerticalAlignment="Center" Width="696"/>
        <TextBox Grid.Column="2" HorizontalAlignment="Left" Margin="305,195,0,0" Text="TextBox" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <TextBox Grid.Column="2" HorizontalAlignment="Left" Margin="305,291,0,0" Text="TextBox" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Label Content="Gross Income:" Grid.Column="2" HorizontalAlignment="Left" Margin="178,187,0,0" VerticalAlignment="Top"/>
        <Label Content="Tax:" Grid.Column="2" HorizontalAlignment="Left" Margin="261,287,0,0" VerticalAlignment="Top"/>
        <Button Content="Next" Grid.Column="2" HorizontalAlignment="Left" Height="33" Margin="261,408,0,0" VerticalAlignment="Top" Width="205" Background="{DynamicResource {x:Static SystemColors.ScrollBarBrushKey}}" Click="OpenWindow"/>

    </Grid>
</Window>

I was told that INOTIFYPROPERTY change is the code missing but i am completely lost to how i would implement it in my code.

A: Send the Wall window as a parameter to the second window, where you set the Visibility property to Visibile, and if Task1 is created once, there is no need to create multiple instances.
The full code of the changes is given below.
change MainWindow to this :
namespace PROG6221_POE_Tarisai_Gonah_18028480
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Task1 f1;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OpenWindow(object sender, RoutedEventArgs e)
        {
            if(f1 == null)
            {
               f1 = new Task1(this);
               f1.Show();
            }
            else
               f1.Visibility = Visibility.Visible;
            this.Visibility = Visibility.Hidden;
        }
    }
}

change Task1 to this :
namespace PROG6221_POE_Tarisai_Gonah_18028480
{
    /// <summary>
    /// Interaction logic for Task1.xaml
    /// </summary>
    public partial class Task1 : Window
    {
        MainWindow mainWindow;
        public Task1(MainWindow _mainWindow)
        {
            InitializeComponent();
            mainWindow = _mainWindow
        }

        private void OpenWindow(object sender, RoutedEventArgs e)
        {
            this.Visibility = Visibility.Hidden;
            mainWindow..Visibility = Visibility.Visible;
        }

        private void ButtonClick(object sender, RoutedEventArgs e)
        {

        }
    }
}


text:
Q: Convert and compare two date formats in JAVA In my application I am having two different types of date formats. One gives Thu Apr 19 12:10:26 GMT+05:30 2012 as out put and other one gives 1334654035000 as out put.
Can I change the first format to the second type (which has only numbers) ?
The reason is,I have to compare two different dates.

A: If you want to compare two dates formatted differently,

*

*parse the first string with the appropriate date format to transform the string into a Date

*parse the second string with the appropriate date format to transform the string into a Date

*compare the Date objects

A: using the parse method of java.text.SimpleDateFormat should do what you want

A: Yes. You could do it. If we assume the dates are under the same time zone, convert the dates using SimpleDateFormat class to Calendar and then invoke the methods on Calendar object to compare dates.

A: parse the date and and compare the date
                 if(!sToDate[Integer.valueOf(sChecked[i])].equalsIgnoreCase("")&&!sFromDate[Integer.valueOf(sChecked[i])].equalsIgnoreCase(""))

if(sToDate[Integer.parseInt(sChecked[i])].compareTo(sFromDate[Integer.parseInt(sChecked[i])])<0)


text:
Q: Qt5 cross-compilation with Texas Instruments DVSDK - undefined reference errors I am trying to compile Qt for Embedded Linux system with TI DVSDK.
http://www.ti.com/tool/linuxdvsdk-dm37x
So far everything went ok, I was able to build the root filesystem via buildroot with all the required libraries (I believe), Qt configure went fine, then I do "make".
Unfortunately in the end of compilation there are always linker errors:
.obj/release-shared/qguivariantanimation.o: In function `global constructors keyed to qguivariantanimation.cpp':
qguivariantanimation.cpp:(.text+0x18): undefined reference to `QVariantAnimation::registerInterpolator(QVariant (*)(void const*, void const*, float), int)'
qguivariantanimation.cpp:(.text+0x28): undefined reference to `QVariantAnimation::registerInterpolator(QVariant (*)(void const*, void const*, float), int)'
qguivariantanimation.cpp:(.text+0x38): undefined reference to `QVariantAnimation::registerInterpolator(QVariant (*)(void const*, void const*, float), int)'
qguivariantanimation.cpp:(.text+0x48): undefined reference to `QVariantAnimation::registerInterpolator(QVariant (*)(void const*, void const*, float), int)'
qguivariantanimation.cpp:(.text+0x58): undefined reference to `QVariantAnimation::registerInterpolator(QVariant (*)(void const*, void const*, float), int)'
.obj/release-shared/qguivariantanimation.o:qguivariantanimation.cpp:(.text+0xb0): more undefined references to `QVariantAnimation::registerInterpolator(QVariant (*)(void const*, void const*, float), int)' follow
collect2: ld returned 1 exit status
make[3]: *** [../../lib/libQt5Gui.so.5.1.1] Error 1
make[3]: Leaving directory `/home/alexey/tenzor/qt/qt-everywhere-opensource-src-5.1.1/qtbase/src/gui'
make[2]: *** [sub-gui-make_first] Error 2
make[2]: Leaving directory `/home/alexey/tenzor/qt/qt-everywhere-opensource-src-5.1.1/qtbase/src'
make[1]: *** [sub-src-make_first] Error 2
make[1]: Leaving directory `/home/alexey/tenzor/qt/qt-everywhere-opensource-src-5.1.1/qtbase'
make: *** [module-qtbase-make_first] Error 2

My configure line is:
./configure -prefix /usr/local/qt5 -release -make libs -xplatform linux-arm-gnueabi-ti-g++ -opengl es2 -confirm-license -opensource -icu -no-xcb -no-pch -no-fontconfig -no-c++11 -verbose

It's not clear for me what could cause this. Please help, any advise is appreciated :)


text:
Q: Variable needs to be declared as final but it needs to be declared as non-final too I have a case that my variable needs to be accessed as a final but it needs to be as non-final too.
Here's my code:
public class ShowViewModel extends ViewModel {
    public void setShows(final String type, boolean isFavorite, FavoriteHelper favoriteHelper) {
        AsyncHttpClient client = new AsyncHttpClient();
        ArrayList<Show> listItems = new ArrayList<>();
        listItems.clear();

        if (isFavorite) {
            Cursor cursor = favoriteHelper.queryAll(type);

            // this assignment needs listItems as a non-final variable
            listItems = MappingHelper.mapCursorToArrayList(cursor);
        } else {
            String url = String.format("http://api.dev");

            client.get(url, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    try {
                        String result = new String(responseBody);
                        JSONObject responseObject = new JSONObject(result);
                        JSONArray results = responseObject.getJSONArray("results");

                        for (int i = 0; i < results.length(); i++) {
                            JSONObject shows = results.getJSONObject(i);
                            Show show = new Show();
                            show.setImage(shows.getString("poster_path"));
                            ....
                            // this assignment needs listItems as a final variable
                            listItems.add(show);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}

Then, I tried to move the listItems as property of the class
public calss ShowViewModel extends ViewModel {
    private ArrayList<Show> listItems = new ArrayList<>();
    public void setShows(final String type, boolean isFavorite, FavoriteHelper favoriteHelper) {
        ...
    }
}

It doesn't show any error and worked perfectly. But it affect another part of my application.
Any solution? Thank you.

A: The normal solution is to use two variables.  For example:
int i = 0;
while (i < 10) {
   i++;
   executor.submit(new Runnable() {
           public void run() {
                System.out.println(i);  // Compilation Error
           });
}

becomes:
int i = 0;
while (i < 10) {
   i++;
   final int ii = i;
   executor.submit(new Runnable() {
           public void run() {
                 System.out.println(ii); // OK
           });
}

You should be able use this approach in your code.

A: Here's a simple solution:
List<Show> cursorList = MappingHelper.mapCursorToArrayList(cursor);
listItems.addAll(cursorList);


text:
Q: Advice on Windows Impersonation but changing to another user I have the following scenario where I'm planning in using windows authentication.
1.1)     I have a web server which will run within a domain.
1.2)    The web site will run under the credentials of a domain user with a set of configured permissions (One which will be allowed access to the file system,  SQL server database etc).
1.3)    Users visiting the web site will belong to the same domain, so I'm planning in using windows authentication.
So at this point, an authenticated user, would access the site, but I guess that from code, "CurrentUser" would be the one under which the site is running.
I'd like the following.
2.1)    To authenticate the user accessing the site with windows authentication. (Domain controller would be responsible for this).
2.2)    For the site to run under the configured user from step 1.2. So it would have all of its permissions.
2.3)    But I'd like to know the initial user used to authenticate from (step 2.1).
This way I could do the following:
3.1)    User "A" decides to access the site, as he belongs to the same domain as the web server, he authenticates successfully.
3.2)    From code I detect that "A" authenticated, so I'll go and fetch his roles. "Role1, Role2, Role3".
3.3)    I then want the code to run under the user configured in step 1.2, but I'll assign the Principal all of the roles retrieved from 3.2.
I've thought that maybe I could use Impersonation for this.
4.1)    So user "A" decides to access the site and authenticates.
4.2)    The site would initially run with "A" credentials, so the "CurrentUser" would be "A".
4.3)    Switch the user (somehow) back to the one from 1.2
4.4)    I could retrieve all of 4.1 configured Roles.
4.5)     Assign the Current Principal the roles retrieved from 4.4.
So in the end the web site will use Windows Authentication with Impersonation, but from code I'd switch back to user 1.2.
If you've reached this point thanks for reading! I'd like to know if this is possible and if it seems achievable or if I'm overcomplicating things.
Also suggestions in how can I plug into and where to do all the role retrieving and user switching.
Many thanks!
UPDATE 1
@ Code Jammr , you're right, no need to do any crazy stuff. But I think I still need to look into HttpModules,..
After doing a few tests, searching etc...
I've started to understand the difference between these IIdentity objects:
HttpContext.Current.User.Identity
Thread.CurrentPrincipal.Identity
WindowsIdentity i2 = WindowsIdentity.GetCurrent();
I posted another question to help me understand them:
Help understanding impersonation
I think this answers my question.

A: There are several code samples out there for doing Impersonation. Most involve dealing with tokens and Win API calls. But if you really must do it this way, I say this not knowing what your webserver type is. IIS 6 or IIS7, then there are many code samples out there to guide you along.
Here is one link for ya that pretty much gives you a starting point.
http://msdn.microsoft.com/en-us/library/aa331755(v=vs.71).aspx
Here is a link on AD authentication and you may not have to do anything crazy.
http://support.microsoft.com/kb/326340
You may want to look into asp.net impersonation, app pool settings, etc... to see if there is a better way.


text:
Q: Teradata: Insert Into Table results of Selects How do I insert into a table the values that result from various selects? For example, the code below comes out empty:
CREATE VOLATILE TABLE TEST (CAMPO1 INT, CAMPO2 INT);

INSERT INTO TEST VALUES ( (select 1), (SELECT 2) );

SELECT * FROM TEST;

The result is a table Test empty. The results of "select 1" and "select 2" were not inserted into Test. Is it possible to insert the values one by one as results of other selects?

A: The Inserts were successfull, but the table was emptied when they committed :-)
The syntax to create Volatile or Global Temporary tables is based on Standard and thus the default ON COMMMIT PRESERVE ROWS, which is quite useless in a Teradata session.
Youneed to switch to
CREATE VOLATILE TABLE TEST (CAMPO1 INT, CAMPO2 INT) ON COMMMIT PRESERVE ROWS;


text:
Q: Union can't match two string columns I have the following query.
var test = await DbContext.StorageAdjustments
    .Where(a => a.StorageId == id && a.TimeStamp >= start)
    .Select(a => new StorageUpdateModel
    {
        TimeStamp = a.TimeStamp,
        Change = a.Volume,
        Product = a.Product.Name,
        UpdateType = StorageUpdateType.Adjustment,
        Notes = "BOL",
    })
    .Union(DbContext.StorageTrucks
        .Where(t => t.StorageId == id && t.TimeStamp >= start)
        .Select(t => new StorageUpdateModel
        {
            TimeStamp = t.TimeStamp,
            Change = t.Volume,
            Product = "xxx",
            UpdateType = StorageUpdateType.Truck,
            Notes = "BOL",
        }))
    .ToListAsync();

But it throws an exception.
System.InvalidOperationException: 'Unable to translate set operation when matching columns on both sides have different store types.'
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.ApplySetOperation(SetOperationType setOperationType, SelectExpression select2, Boolean distinct)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateUnion(ShapedQueryExpression source1, ShapedQueryExpression source2)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0`1.<ExecuteAsync>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)
   at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.<ToListAsync>d__65`1.MoveNext()
   at Pegasus.Pages.Transloading.StorageLocations.DetailsModel.<OnGetAsync>d__15.MoveNext() in D:\Users\jwood\source\repos\Railtrax\Pegasus\Pages\Transloading\StorageLocations\Details.cshtml.cs:line 65

If I change Product = a.Product.Name, to Product = "xxx", it works without an exception.
I really don't understand this. a.Product.Name is defined in the database as (nvarchar(120), not null). Does anyone know why Union() can't combine two string columns, or how to coherce them to the same type?

A: It looks like a change to address the underlying issue was being considered for version 3.0 on GitHub.
I don't understand why it wasn't considered important enough to implement even in version 7.0.
It makes it extremely difficult to workaround such an issue with the only valid workaround being to perform the Union() on the client side, along with its obvious performance disadvantages.
Update
There was one workaround by using Product = Convert.ToString(a.Product.Name) and it actually works for me. However, it seems to be using NVARCHAR(MAX) and people posted comments that it can cause resource problems.


text:
Q: Using analog switches with ultrasonic sensors, what to look for? I am designing an anemometer for university project. I intend to use analog switches to switch between ultrasonic sensors. I use this circuit as my first stage - it adds offset to the signal and has high-pass filter. The input signal is centered around 0V I want to know if this could be a problem for the switch I am going to be using the signal not that large (tens of millivolts).
I have also read about charge injection and I learned that it is inversely proportional to the load capacitance I am not really sure if it's going to be a problem or not in this case.
This is the datasheet of the switch I plan to use : http://www.ti.com/lit/ds/symlink/ts3a5018.pdf

A: I would recommend that you use two separate op-amp gain stages and then put the switch at the outputs of these two stages. This way the switch can be used with the +5 and GND supply connections and the signal is centered in the supply range of the switch. This would typically be the optimum way to operate the analogue switch.
There are also some advantages of simplifying the circuit path that your lowest level signals pass through to keep circuit connections short and give a better chance of eliminating noise pickup in sensitive the amplifier front end.


text:
Q: why myPyQt5 project Update picture display in real time     from PyQt5 import QtCore, QtGui, QtWidgets
    import os
    path_of_image = './some_file.png'
    import sys
    from PyQt5 import QtWidgets
    from PyQt5 import QtCore, QtGui
    from PyQt5.QtWidgets import QApplication,QWidget,QLabel,QPushButton
    from PyQt5.QtGui import QPixmap

    class App (QtWidgets.QWidget):
        def __init__(self):
            super ().__init__ ()
            self.initUI ()

            # threading.Thread (target=self.initUI (), args=()).start ()
            # threading.Thread (target=self.update_image(), args=()).start ()

        def initUI(self):

                QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
                QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
                # QtWidgets.QApplication.processEvents ()
                self.w_ = QtWidgets.QMainWindow ()
                self.w_.resize (512, 360)

                self.w_.setWindowFlags (QtCore.Qt.SplashScreen | QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint)
                self.w_.setAttribute (QtCore.Qt.WA_TranslucentBackground)
                self.w_.setStyleSheet ("background:transparent;")

                self.label = QtWidgets.QLabel (self.w_)

                self.label.setGeometry (QtCore.QRect ( 615,292, 200, 200))

                self.label.lbl = QLabel ("photo", self.label)
                self.label.pm = QPixmap ("./some_file.png")

                self.label.lbl.setPixmap (self.label.pm)
                self.label.lbl.resize (200,200)

                self.w_.showFullScreen ()
                timer = QtCore.QTimer (self)
                timer.timeout.connect (self.update_image)
                timer.start (1000)
                # time.sleep(10)

                #self.update_image ()

        #
        def update_image(self):
            #
            pixmap = QtGui.QPixmap (path_of_image)
            try:
                if not pixmap.isNull ():
                    QApplication.processEvents ()

                    print(pixmap.isNull ())
                    self.label.pm = QPixmap ("./some_file2.png")
                    self.label.setPixmap (self.label.pm)
                    self.label.adjustSize ()
                    print( QPixmap ("./some_file2.png"))
                    self.resize (pixmap.size ())
                    self.w_.showFullScreen ()
            except Exception as err:
                    print ('An exception happened: ' + str (err))

    if __name__ == '__main__':
        app = QtWidgets.QApplication (sys.argv)
        ex = App ()

        sys.exit (app.exec_ ())

This is my code ,but i don't Realize Refresh photo
I tried to use Qtimer to implement time slots and multithreading, but none of them achieved the effect I wanted-refreshing the picture in real time (in my transparent borderless background),If you use Qtime and multithreading, you may encounter the following situations where thread congestion causes the Qt window to become unresponsive.
from PyQt5 import QtCore, QtWidgets, QtNetwork
from pyzbar import pyzbar as pyzbar
import sys
from PyQt5 import QtWidgets
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QApplication,QWidget,QLabel,QPushButton
from PyQt5.QtGui import QPixmap
class Loader (QtCore.QObject):
    def __init__(self, parent=None):
        super().__init__ (parent)
        manager = QtNetwork.QNetworkAccessManager()
        manager.finished.connect (self.onFinished)
        self._manager = manager

    def start(self, url, label):
        self._url = url
        self._label = label
        self.request()

    def request(self):
        manager = self._manager
        req = QtNetwork.QNetworkRequest(QtCore.QUrl(self._url)) #todo:
        res = manager.get (req)

    def onFinished(self, reply):
        data = reply.readAll()
        self.w_ = QtWidgets.QMainWindow()
        self.w_.resize (512, 360)

        self.w_.setWindowFlags(QtCore.Qt.SplashScreen | QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint)
        self.w_.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.w_.setStyleSheet("background:transparent;")

        self.label = QtWidgets.QLabel(self.w_)

        self.label.setGeometry (QtCore.QRect (615, 292, 200, 200))

        self.label.lbl = QLabel("qrcode", self.label)
        self.label.pm = QPixmap("./some_file.png")

        self.label.lbl.setPixmap (self.label.pm)
        self.label.lbl.resize(200, 200)
        self.label.pm.loadFromData(data)
        self._label.setPixmap(self.label.pm)
        QtCore.QTimer.singleShot(1000, self.request)
        self.w_.showFullScreen()
if __name__ == "__main__":
        app = QtWidgets.QApplication([])
        label = QtWidgets.QLabel()
        label.show()
        loader = Loader()
        url = "http://172.17.135.67:5421/api/download?filename=/some_file2.png"
        loader.start(url, label)
        app.exec()

I wrote a refresh function of my QR code based on the example of others, but his work was wrong and there were two windows showing pictures.


text:
Q: Mapbox deciding overlap order I have some features on the map displayed as icons. I want to decide which icons should be hidden and which should be displayed when they collide on a numeric field, that each feature on my map has (see picture). I've found a mapbox property called "symbol-sort-key", but I can't figure out if it's the right thing. symbol-sort-key takes a number, but I don't know to what this number should refer to. Any ideas how to solve this problem?

A: Yes, symbol-sort-key is probably what you want. It's used to determine the order in which symbols are drawn, which affects which one is drawn on top if they overlap and collisions are allowed (highest number wins) or which is the only one drawn if collisions aren't allowed (lowest number wins).
The number in the documentation refers to a numeric type. So if if you have a property called "priority", which is numeric, you'd specify something like:
"symbol-sort-key": ["to-number", ["get", "priority"]],


text:
Q: Magento 2 assign isSelected on new address book checkout page i need help on overriding shipping.js from core magento
i've create new mixing extend from Magento_Checkout/view/shipping.js
    var mixin ={

        saveNewAddress: function () {
            var addressData,
                newShippingAddress;

            console.log('save new address overriden');
            this.source.set('params.invalid', false);
            this.triggerShippingDataValidateEvent();

            if (!this.source.get('params.invalid')) {
                addressData = this.source.get('shippingAddress');
                // if user clicked the checkbox, its value is true or false. Need to convert.
                addressData['save_in_address_book'] = this.saveInAddressBook ? 1 : 0;

                // New address must be selected as a shipping address
                newShippingAddress = createShippingAddress(addressData);
                selectShippingAddress(newShippingAddress);
                checkoutData.setSelectedShippingAddress(newShippingAddress.getKey());
                checkoutData.setNewCustomerShippingAddress($.extend(true, {}, addressData));
                this.getPopUp().closeModal();
                this.isNewAddressAdded(true);
            }
        }
    };

    return function (target) {
        return target.extend(mixin);
    }

how can i select this new address book after save new address book added on checkout page before checkout process so i can process on my custom
shipping-address/address-renderer/default.js ?