text:
Q: Should I have views in a .NET Core API At the company I work at we have a couple of different services

*

*API (.NET Core)

*Internal Frontend (React)

*External Frontend for customers (React)

I was asked to create some views which will be converted to PDF's by an API, but I can't decide where to put them as they are not related to our Internal- or External-facing projects.
My first thought was to put them in our .NET Core API. However this has previously been a strict json-only API, so I have an itch that this is not the intended use.
So internet, my questions are as follows

*

*Is it a big NO-NO to put Razor-views in our API?

*Should I dedicate a microservice to this?

*What is best practice?

Thanks in advance!

A: You're right, Razor views will be excess. I see two options:

*

*Backend: Create an endpoint which will return a PDF file based on passed data. Of course you can expand data. This way is similar with Razor: you have a view model and render it to PDF file. An example of library: iTextSharp.LGPLv2.Core

*Frontend: Convert HTML to PDF on client's side. Something like react-pdf
I prefer first option, because, first of all, there is already an option "Save as PDF" in browsers, so it will be some kind of duplication of functionality. And on the other hand back-end PDF generation seems more flexible (you can use all of your domain and you can create independent layout either) and you can organise some kind of file cache.


text:
Q: Pose proof in Coq I'm trying to prove a theorem in Coq. My current context is:
1 subgoal
s, x : Entity
Pssx : Ps s x
Fxs : F x s
IPssx : F x s /\ Ps s x
t : Entity
Ctss : C t s s
Pstx : Ps t x
Fxt : F x t
______________________________________(1/1)
C s s s

F, Ps and C are relations of the theory. I've also Axiom 4:
Axiom A4 : forall x s t,
  Ps s x /\ F x s /\ Ps t x /\ F x t -> s = t.

What I want to do, is to use A4 in the proof, as it will help me to say that s and t are equals. So I've tested: pose proof (A4 x s t). A new hypothesis is added : H : Ps s x /\ F x s /\ Ps t x /\ F x t -> s = t. I know I can destruct the hypothesis H, prove the premisses and use the conclusion. But I also know that I can give the premisses directly in the pose proof command. I want to do something like pose proof (A4 x s t Premisses). But I don't know what to put instead of Premisses.
I tried several solutions:

*

*composing the hypothesis with /, such as pose proof (A4 x s t (Pssx /\ Fxs /\ Pstx /\ Fxt)). but I got the error The term "Pssx" has type "Ps s x" while it is expected to have type "Ps s x /\ F x s /\ Ps t x /\ F x t".

*using the assert command and pose proof (A4 x s t H1).:

*

*assert (H1 := (Ps s x) /\ (F x s) /\ (Ps t x) /\ (F x t)). but I got The term "H1" has type "Prop" while it is expected to have type "Ps s x /\ F x s /\ Ps t x /\ F x t".

*assert (H1 := (Pssx) /\ (Fxs) /\ (Pstx) /\ (Fxt)). but I got The term "Pssx" has type "Ps s x" while it is expected to have type "Prop".
So my question is the following: what should I put instead of Premisses for my code to work? Is there a command to create new hypothesis based on other ones? I know how to destruct an hypothesis into two smaller hypothesis, but I don't know how to compose hypothesis to create bigger ones.

A: The standard in Coq would be to curry your A4 so that instead of receiving one large conjunction as a premise, it receives several different premises:
Axiom A4' : forall x s t,
  Ps s x -> F x s -> Ps t x -> F x t -> s = t.

Then you can do:
pose proof (A4' x s t Pssx Fxs Pstx Fxt).

If you absolutely need A4 with the conjunctions, you can use conj (which you can find with Print "_ /\ _"):
pose proof (A4 x s t (conj Pssx (conj Fxs (conj Pstx Fxt)))).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Histogram with specific colors I have as example two data sets and want to make a combined histogram.
When I do the following I can hardly distinguish which histogram belongs to which data.
SeedRandom["1"];
data1 = RandomInteger[{1, 5}, 100];
data2 = RandomInteger[{0, 6}, 150];
Histogram[{data1, data2}, {1}]

How can I achive the following combined histograms:
A.

histogram of data1: red, transparent, solid edges
histogram of data2: blue, transparent, solid edges

B.

histogram of data1: red
histogram of data2: blue
overlap: green

C.

histogram of data1: solid
histogram of data2: dashed

A: Cases A and C can be handled with appropriate ChartStyle settings:
Histogram[{data1, data2}, {1},
  ChartStyle -> {Opacity[.25, Red], Opacity[.25, Blue]}]

Histogram[{data1, data2}, {1},
  ChartStyle -> {Red, Directive[EdgeForm[{Thick, Dashed}], Blue]}]

Case B is difficult. The following trick uses HistogramList to get the bar heights and BarChart with appropriate inputs and options to get the desired look:
ClearAll[heightsF]
heightsF = Module[{binlims = {Union @@ (HistogramList[#, {1}][[1]] & /@ #)}, bars},
    bars = HistogramList[#, binlims][[2]] & /@ #;
    Transpose[Join[bars, {Min @@@ Transpose[bars]}]]] &;

barheights = heightsF[{data1, data2}];
BarChart[barheights, ChartBaseStyle -> Opacity[1],
 ChartStyle -> {Red, Blue, Green}, ChartLayout -> "Overlapped", BarSpacing -> {0, 0}]

A: If you don't want folks to understand two sets of data, overlapping histograms is probably the best way to do it.
If you do want folks to see the features of the data, here are two ways.  First generate two datasets:
SeedRandom["1"];
data1 = RandomVariate[NormalDistribution[0, 1], 100];
data2 = RandomVariate[NormalDistribution[0.5, 0.5], 150];

A smoothed histogram (nonparametric density estimate) allows one to overlap multiple distributions and still allow one to identify the individual datasets:
SmoothHistogram[{data1, data2}]

If there are just two datasets, then showing both histograms side-by-side can be a good choice:
PairedHistogram[data1, data2]

A: This is an answer from Wolfram Technical Support regarding histogram B in my question:
Styling Histograms
Using Options
Probably the easiest way to approach this is to use the option ChartStyle iwith opacity. The RGBColor function can be given with four arguments, with the fourth argument setting the opacity of the result. When there is overlap the colors will blend. Here is an example using your data sets.
SeedRandom["1"];
data1 = RandomInteger[{1, 5}, 100];
data2 = RandomInteger[{0, 6}, 150];
Histogram[{data1, data2}, {1},
 ChartStyle -> {RGBColor[1, 0, 0, .5], RGBColor[0, 1, 0, .5]}]

The difficulty here is that the user does not have control over the blend. With a careful choice of colors this can work well, but there are going to be cases where this does not give satisfactory results.
Creating Your Own Function
This approach is a little more work, but if you are intending to create a number of plots it can be worth the extra work. We will assume that the binning is consistent between sets and if you are dealing with set of integers this is not difficult to achieve.
HistogramList
The function HistogramList is a good place to start. This will return a list of bin boundaries and the counts for each of the intervals. Here we get the values for your example sets.
prts1 = HistogramList[data1]

{{0.5, 1.5, 2.5, 3.5, 4.5, 5.5}, {20, 13, 24, 16, 27}}

prts2 = HistogramList[data2]

{{-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5}, {21, 18, 22, 24, 25, 19, 21}}

Note that the lists indicate the bins are consistent from one data set to the next.
Modifying the Histogram Lists
We begin by modifying the histogram lists to give the bounds of each interval followed by the set those values come from and the counts for the bin.
brs1 = Thread[{Partition[prts1[[1]], 2, 1], 1, prts1[[2]]}]

{{{0.5, 1.5}, 1, 20}, {{1.5, 2.5}, 1, 13}, {{2.5, 3.5}, 1, 24}, {{3.5, 4.5}, 1, 16}, {{4.5, 5.5}, 1, 27}}

brs2 = Thread[{Partition[prts2[[1]], 2, 1], 2, prts2[[2]]}]

{{{-0.5, 0.5}, 2, 21}, {{0.5, 1.5}, 2, 18}, {{1.5, 2.5}, 2, 22}, {{2.5, 3.5}, 2, 24}, {{3.5, 4.5}, 2,
  25}, {{4.5, 5.5}, 2, 19}, {{5.5, 6.5}, 2, 21}}

Bringing the Sets Together
Here we use Join to bring the lists together and then create sublists for each bin.
totLs = GatherBy[Join[brs1, brs2], First]

{{{{0.5, 1.5}, 1, 20}, {{0.5, 1.5}, 2, 18}}, {{{1.5, 2.5}, 1, 13}, {{1.5, 2.5}, 2, 22}}, {{{2.5, 3.5}, 1,
   24}, {{2.5, 3.5}, 2, 24}}, {{{3.5, 4.5}, 1, 16}, {{3.5, 4.5}, 2, 25}}, {{{4.5, 5.5}, 1, 27}, {{4.5, 5.5},
   2, 19}}, {{{-0.5, 0.5}, 2, 21}}, {{{5.5, 6.5}, 2, 21}}}

Note that some of the lists have a single bin while most have two counts, one for each of the sets.
Creating the Bars
Next we take the information for each bin and create rectangles for each count. There are four possible situations, the situation when only one set is present in the bin, one where the counts are the same for that bin, the case where the first data set is greater than the second and finally the situation where the second set has a count greater than the first. These cases are easily handled using the Which function. We include a style to use for each of the cases, the first data set, the second and both together.
makeRecs[ls_List, colLs : {(_RGBColor | _Directive ..)}] := Which[
  Length[ls] == 1, {colLs[[2]], Rectangle[{ls[[1, 1, 1]], 0}, {ls[[1, 1, 2]], ls[[1, 3]]}]},

  ls[[1, -1]] - ls[[2, -1]] == 0, {colLs[[3]], Rectangle[{ls[[1, 1, 1]], 0}, {ls[[1, 1, 2]], ls[[1, -1]]}]},

  Min[ls[[All, -1]]] ==
   ls[[1, -1]], {{colLs[[3]],
    Rectangle[{ls[[1, 1, 1]], 0}, {ls[[1, 1, 2]], Min[ls[[All, -1]]]}]}, {colLs[[2]],
    Rectangle[{ls[[1, 1, 1]], Min[ls[[All, -1]]]}, {ls[[1, 1, 2]], Max[ls[[All, -1]]]}]}},

  Max[ls[[All, -1]]] ==
   ls[[1, -1]], {{colLs[[3]],
    Rectangle[{ls[[1, 1, 1]], 0}, {ls[[1, 1, 2]], Min[ls[[All, -1]]]}]}, {colLs[[1]],
    Rectangle[{ls[[1, 1, 1]], Min[ls[[All, -1]]]}, {ls[[1, 1, 2]], Max[ls[[All, -1]]]}]}}]

Using the makeRecs Function
Here we use the makeRecs function on your data and assign the colors red to the first set, green to the second set and blue to both sets. Note this is applied to the combined list created above using Map.
Graphics[makeRecs[#, {Red, Green, Blue}] & /@ totLs,
 AspectRatio -> 1/GoldenRatio,
 Axes -> True]

A More Advanced Example
Here we use graphics options to dress up the plots. Framed and Legended are used to finish things off.
Framed[Legended[
  Graphics[makeRecs[#, Directive[#, EdgeForm[{Black, Thickness[Tiny]}]] & /@ {Yellow, Green, Orange}] & /@
    totLs,
   AspectRatio -> 1/GoldenRatio,
   Axes -> True,
   Frame -> True], SwatchLegend[{Yellow, Green, Orange}, {"data 1", "data 2", "both"}]],
 RoundingRadius -> 10]

Observations
The above steps can be combined into a single function to have a function similar to the built-in function. If more than two data sets are involved the number of cases increases quite rapidly so one should expect observable slowdowns as the number of sets increases. Because of that I have limited the number of sets to two. Also the above code requires the style of the bars to use RGBColor or the styles to be set using Directive as seen in the second example. If one wishes to take colors from the Color Schemes palette the RGBColor values can be obtained as illustrated below.
{ColorData[32][3], InputForm[ColorData[32][3]]}

 {RGBColor[0.7490196078431373, 0.43529411764705883`, 0.24705882352941178`], InputForm[
RGBColor[0.7490196078431373, 0.43529411764705883`, 0.24705882352941178`]]}

{ColorData["Rainbow"][.7], InputForm[ColorData["Rainbow"][.7]]}

{RGBColor[0.8083415999999999, 0.7110806000000001, 0.255976], InputForm[
RGBColor[0.8083415999999999, 0.7110806000000001, 0.255976]]}


text:
Q: Google Drive SDK giving access to all users files I have a website that uses the Google Drive SDK to create and save files.  I have the permissions set to only have access to files created by my website.
Today all of the users Google Drive files are now visible from within my website even those not created by my app.  I had a few other users report this to me.
Anyone else seeing this behavior on their website?  Is this a bug or did Google change the behavior of these permissions?

A: We've isolated a Google Drive server issue and have implemented a temporary fix. You should no longer be able to see the issue.
Thanks for the report!


text:
Q: Cygwin Bash, loading a history file I use Cygwin's bash shell (bash -i) daily for common tasks.
In my .bashrc file, I have the following:
history -rc bashcommands.history
history

Above the first prompt line, I see the list of history commands from bashcommands.history, so it looks like the history has been changed.
However, if I now enter "history" at the prompt, it shows my original history, not what's in bashcommands.history.
If I enter "history -rc bashcommands.history" at the prompt, the history file loads as expected, and then "history" will show the commands.
Is there some environment or shell settings being reset after .bashrc is processed?  I don't see anything in the man pages that would explain it.
How can I get the history file loaded before the first prompt?

A: Have you tried putting it in your .bash_profile?

A: For those who are interested, this worked:

*

*I set my ENV environment variable to ~/.bashrc

*I ran the command bash --posix


text:
Q: "... a little less problems" — is this phrase grammatically correct? Is this sentence, "I wish I had a little less problems" grammatically correct? Especially the phrase, "... a little less problems". I know there are other ways to say the same thing like, "I wish I didn't have as much problems" or "I wish I had less problems" but it changes the feel of the sentence. The feel I'm tryna give off with this sentence is that the person has so many issues that he's wishing that AT LEAST something was right.
Btw, is the title grammatically correct?
Edit: Thanks Juhasz, this surely is an issue of countable and uncountable thing. But that didn't solve my problem cause in the sentence I'm not only using 'less' but 'a little' also.
Edit: So, this is what I'm actually writing: "It's hard to live in a world where everyone seems perfect and you spend your day wishing you had a little less problems". Now, I can't find something that quite goes with the flow.

A: I would write "I wish I had fewer problems".
In theory, less is supposed to be used to describe a smaller amount of a single entity, while fewer is supposed to be used to describe a smaller number of entities.
In practice, what you have written is likely to be understood, if a little awkward.
For more casual speech, I might also suggest:

*

*"I wish I didn't have quite so many problems." (the reversal feels more natural to me, and the use of quite indicates that there is only a small adjustment needed)

*"I wish I had a little less on my plate" (on my plate is an idiom for things to do, so might not be a direct translation, but certainly understandable)

*"I wish I didn't have quite so much on my plate" (a combination of the two is also valid)

After question edit #1:

The feel I'm tryna give off with this sentence is that the person has so many issues that he's wishing that AT LEAST something was right.

"I wish I didn't have quite so many problems." infers this well enough.

"I wish I didn't have as much problems"

no; use "I wish had fewer problems" (fewer not less)

"I wish I didn't have as much problems"

again, no; use "I wish I didn't have as many problems" (many not much)

After question edit #2:

So, this is what I'm actually writing: "It's hard to live in a world where everyone seems perfect and you spend your day wishing you had a little less problems". Now, I can't find something that quite goes with the flow.

*

*It's hard to live in a world where everyone seems perfect and you spend your day wishing you had fewer problems.

*It's hard to live in a world where everyone seems perfect and you spend your day wishing you didn't have quite so many problems.

PS: There is nothing wrong with the the title of your question (assuming it still reads "… a little less problems" – is this phrase grammatically correct?).  Quoting the problematic phrase makes it clear that we are referring to the the phrase, and the question at the end is fine.

A: The following would apply to normal phrasing:

✔ fewer problems
  ✘ less problems
✘ fewer of a problem
  ✔ less of a problem

The use of adjectives should not be influencing the word used.
In other words, I would say one of the following:

*

*a little less of a problem

*a little fewer problems

However, the specific phrase a little fewer problems, while analytically correct, seems idiomatically strange.
In short, I would pick 1. over 2.
So:

I wish I had fewer problems.  OR
  I wish I had a little less of a problem.


text:
Q: Why can't we dope the intrinsic semiconductors with sixth or second group elements? Suppose we want to make an n-type  silicon semiconductor why do we use arsenic or phosporous as an impurity? Why cant we use selinium or terellium?
Infact my doubt is when we use sixth group element it can donate two free electrons so that we can have higher carrier concentration even with lesser doping concentration . Why it is not done so?

A: On theoretical grounds, there is the issue of dopant "depth". You can look online for a table of ionization energies of dopants in Si, for example here: Dopant Energy Levels.
In terms of this table, what you want is the highest energy level (for donor) or lowest energy level (for acceptor). The ionization energies listed are relative to the band where the electron goes to/comes from. "Shallow dopants" have a small ionization energy which is important for a couple of reasons.

*

*A small ionization energy makes it very easy for the electron to leave the dopant, in fact it is often said that shallow dopants are guaranteed to be thermally ionized under normal conditions. The probability of ionization depends on the location of dopant energy level in respect to the Fermi level (filling), however the Fermi level is almost always within the band gap.
Phosphorus is a classic shallow dopant in silicon, only having 0.045 eV ionization energy.
You can see with selenium however that there are two ionization levels, indicating that, yes, it should be able to donate two electrons. The first, 0.25 eV, could provide some doping, but the second ionization, 0.4 eV, is unlikely occur if there are already too many conduction electrons -- if the Fermi level is already sitting too high in the band gap. This means we cannot use Se to obtain high doping levels.

*Another closely related factor with dopant depth is that deep dopants act as more powerful scattering sites. Although it's not a perfect relationship, the ionization energy can be thought of as the depth of the potential well that binds the electron. Once the electron leaves the dopant it leaves behind that potential well like a gaping hole. Moreover the deep dopants can also act as recombination centers, literally sucking out the minority carriers that need in devices like bipolar transistors.
To make an analogy, imagine you (electron in conduction band) are driving along a road (potential landscape). Shallow dopants are like little pot holes here and there, whereas deep dopants are like giant pits where there you can probably get out, but there is the chance that you will fall through all the way down into the sewer (valence band). :)
In practice, other issues may intervene such as the practicality of dissolving the dopant nicely into the silicon melt, or tendencies of the dopants to clump together into inert clusters or to initiate crystal faults during crystal growth. Dopants have very different diffusion rates, which must be balanced together in diffusion doping. Also, scattering is not strictly proportional to ionization energy. I suppose one of these practical reasons is why manufacturers never use lithium, for example.
See also http://ecee.colorado.edu/~bart/book/extrinsi.htm


text:
Q: Is there a way to lookup refcount for a kobject? I expected to find a function along the lines of kobject_check_refcount, that returned the current refcount without altering it, in kobject.c, but as far as I can see there isn't one. Is there such a function existing in the kernel source somewhere? I can see it being useful for debugging purposes at points.
Edit: found kref_read which sounds like it fits the bill. Just testing to see if it works as I'm expecting.

A: Yes, looks like kref_read is the right way to go.
static inline unsigned int kref_read(const struct kref *kref)
{
    return refcount_read(&kref->refcount);
}


text:
Q: update textbox on 2nd form from threaded sub not working VB.Net I have two forms: Form1, and StreamFrm.
From a threaded sub on Form1 I need to update textboxes on StreamFrm.
I tried the following:
Private Sub timerTicks() Handles EventTimer.Tick
    If IsCheckingTable = False Then
        StreamFrm.Puts7.Text = "test from Form1 : timerticks"
        Threading.ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf CheckTableForNewRecords), IsCheckingTable)
    End If
    Timertxt.Text = Date.Now
End Sub
Private Sub CheckTableForNewRecords(IsCheckingTable)
    IsCheckingTable = True
    swR.Restart()
    swR.Start()
    PR = LR
    SQL.GETlastrcrd(QueryLR, LR)
    NR = LR - PR
    strm()
    UpdateLastrcrdFrm(LR)
    UpdatePrvLrcdrFrm(PR)
    UpdateNewrcrdFrm(NR)
    If NR > 0 Then
        Dim QueryRR As String = "SELECT * from(select ROW_NUMBER() over (Order by StreamingID ) as row, " & _
                                "StreamingID,WatchlistID,symbol,Bid,Ask,Last,High,Low,PrevClose,Volume,TradeTime," & _
                                "QuoteTime,TradeDate,QuoteDate,Volatility,OpenInterest,UnderlyingSymbol,CallPut,TradeVolume,TradeAmount,Trade,LastSize from optionstream) " & _
                                "as StreamingID where StreamingID between " & (PR + 1) & " AND " & LR
        SQL.GetTrades(QueryRR)
    End If
    UpdateTEchecktrades()
    IsCheckingTable = False
End Sub
Private Sub strm()
    If StreamFrm.Puts6.InvokeRequired Then
        StreamFrm.Puts6.Invoke(New action(AddressOf strm))
    Else
        StreamFrm.Puts6.Text = "test from Form1 : ChecktableFornewrecords"
    End If
End Sub
Private Sub UpdateLastrcrdFrm(LR)
    If LastrcrdFRM.InvokeRequired Then
        LastrcrdFRM.Invoke(New Action(Of Integer)(AddressOf UpdateLastrcrdFrm), LR)
    Else
        LastrcrdFRM.Text = LR
    End If
End Sub

It updates StreamFrm.Puts7.Text = "test from Form1 : timerticks"  just fine; it's in the same thread.
From sub CheckTableForNewRecords(IsCheckingTable) which is threaded, I call sub strm() which checks whether StreamFrm.Puts6 needs an invoke before writing text to it.
This does not work, no errors, but no text in the text box.
However  LastrcrdFRM.Text = LR does work. But this text box is on Form1.
So how do I update the text box on Form StreamFrm?
I am using the same invoke method as with Form1, so why doesnt it work?

A: From what I recall, InvokeRequired doesn't work as expected when called on the control.  You need to call it on the Form.
Private Sub strm()
    If StreamFrm.InvokeRequired Then
        StreamFrm.Invoke(New action(AddressOf strm))
    Else
        StreamFrm.Puts6.Text = "test from Form1 : ChecktableFornewrecords"
    End If
End Sub


text:
Q: How the below code with Lambda expressions is compiling? I am reading a Lambda example from Herbert Shildt book- Java the complete reference. The code is written in side of LambdasAsArgumentsDemo.java file
interface StringFunc {
String func(String n);
}

class LambdasAsArgumentsDemo {

public static void main(String args[]){
    String inStr = "Lambdas add power to Java";
    String outStr;
    // Here, a simple expression lambda that uppercases a string is passed to stringOp( ).
    outStr = stringOp((str) -> str.toUpperCase(), inStr);
    System.out.println("The string in uppercase: " + outStr);

//This method has a functional interface as the type of its
// first parameter. Thus, it can be passed a reference to
//any instance of that interface, including the instance
//created by a lambda expression.
//The second parameter specifies the string to operate on.

        static String stringOp(StringFunc sf, String s) {
            return sf.func(s);
        }
    }

Now my question is at the line
outStr = stringOp((str) -> str.toUpperCase(), inStr);

How come it is  true that when you pass (str) -> str.toUpperCase() as argument, an instance of the functional interface StringFunc is created and a reference to that object is passed as the
first parameter of stringOp() ?? How does it know to instantiate StringFunc ?

A: StringFunc defines an interface for a function which takes a string as argument and returns a string. Your lambda expression (str) -> str.toUpperCase() does the same. It takes a string ((str) and returns a string (str.toUppercase()), so it matches the interface.
Think like this: there's no need to instantiate an object of that interface, since the lambda already is the instance. It's sufficient to cast it to the interface. str would then be the name of the argument.
You can achieve the same result by using a regular method with that signature:
public static void main(String args[]){
    String inStr = "Lambdas add power to Java";
    String outStr;
    outStr = stringOp(LambdasAsArgumentsDemo::mymethod, inStr);
    System.out.println("The string in uppercase: " + outStr);
}

public static String mymethod(String str) { return str.toUpperCase(); }
              ^                 ^                  ^
              |                 |                  implementation
              |                 String argument called str
              String return type

From the comments:

BTW, I have some other related question. What if there is similar 2 other functional interfaces like interface StringFunc2 { String func2(String n); } and interface StringFunc3 { String func3(int n); } In such case, how would it get resolved ? What is the explanation ? BTW, it is still compiling OK and producing the same output.

The code calls stringOp(). stringOp() takes  either StringFunc, StringFunc2 or StringFunc3. So the compiler knows at compile time, which one to choose.
If, however, you define three interfaces and three functions, the code cannot compile and fails with an error message that the call is ambiguous, because the lambda could be either one.
import java.util.*;
import java.lang.*;
import java.io.*;

interface StringFunc {
    String func(String n);
}
interface StringFunc2 {
    String func(String n);
}
interface StringFunc3 {
    String func(String n);
}

class LambdasAsArgumentsDemo {

    public static void main(String args[]){
        String inStr = "Lambdas add power to Java";
        String outStr;
        outStr = stringOp((str) -> str.toUpperCase(), inStr);
        System.out.println("The string in uppercase: " + outStr);
    }

    static String stringOp(StringFunc sf, String s) {
        return sf.func(s);
    }

    static String stringOp(StringFunc2 sf, String s) {
        return sf.func(s)+"2";
    }

    static String stringOp(StringFunc3 sf, String s) {
        return sf.func(s)+"3";
    }
}


text:
Q: Bulk INSERT for records that don't exist, returning ID I'm using pg-promise to process an array of data that I want to insert in table A. I'm having a hard time figuring out how to dynamically create this query that should only INSERT those values not already present in the table, while returning the ID of all those who are already present or were newly created.
I'm doing the following to do the above, but for a single element:
WITH s as
  ( SELECT *
   FROM fruits
   WHERE fruit_name = 'Apple' ),
       i AS
  ( INSERT INTO fruits(fruit_name) SELECT 'Apple'
   WHERE NOT exists
       (SELECT 1
        FROM s) RETURNING fruit_id)

But say that I have an Array of fruits = ['Banana', 'Apple']. How would I use the helpers to generate a query that would return the existing ID for apple, and the one for Banana?


text:
Q: responseJSON getting no response I am using Alamofire to try and put an image on image shack server using the image shack API. I am not getting a response back and get the error:

FAILURE: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value
  around character 0.

I have highlighted where the error is referring too in the code also:
        let imageName = "pano.jpg"
        let postImage = UIImage(named: imageName)
        let urlStr = "https://post.imageshack.us/upload_api.php"
        let theUrl:NSString = urlStr.stringByRemovingPercentEncoding!
        let url = NSURL(string: theUrl as String)!
        let imgData = UIImageJPEGRepresentation(postImage!, 0.2)!
        let keyData = "0345CHKMad115dd32980b363be5f2d34731b8110".dataUsingEncoding(NSUTF8StringEncoding)!
        let keyJSON = "json".dataUsingEncoding(NSUTF8StringEncoding)!

Alamofire.upload(.POST, url, multipartFormData: { MultipartFormData in

                MultipartFormData.appendBodyPart(data: imgData, name: "fileupload", mimeType: "image/jpg")
                MultipartFormData.appendBodyPart(data: keyData, name: "key")
                MultipartFormData.appendBodyPart(data: keyJSON, name: "format")

            }) {encodingResult in

                switch encodingResult {
                case .Success(let upload, _, _):
                    upload.responseJSON(completionHandler: { response in

                        print(response) //ERROR HERE
                        guard let data = response.result.value
                            else{
                                print("Request failed with error data)")

                            return
                        }

                        if let info = data as? Dictionary<String, AnyObject> {
                            if let links = info["links"] as? Dictionary<String, AnyObject> {
                                if let imgLink = links["image_link"] as? String {
                                    print(imgLink)
                                }
                            }
                        }
                    })

I am completely lost what this problem means any help would be great.

A: Try this, before passing your url into the function do:
//Convert the NSURL to a NSString
let urlString:NSString = url.absoluteString() as! NSString

//Remove Percent Encoding
let theUrl:NSString = urlString.stringByRemovingPercentEncoding()

//Place Back into NSURL
let newUrl = NSURL(string:theUrl)

And pass newUrl instead of url. It would be better to do this before instantiation of the original url, but try that and see if that helps.
EDIT
try this too where you are having the issue:
var jsonError:NSError?
let json = NSJSONSerialization.JSONObjectWithData(response, options: nil, error: &jsonError) as NSDictionary {

    print(json)
}

A:    switch encodingResult {
                    case .Success(let upload, _,_):
                        upload.responseJSON(completionHandler: {response in

                            if let data = response.result.value as? Dictionary<String, AnyObject>{

                                if let links = data["links"] as? Dictionary<String, AnyObject> {
                                    if let imgLink = links["image_link"] as? String {
                                        print(imgLink)
                                    }
                                }
                            }

                        })
                    case .Failure(let error):
                        print(error)
                    }


text:
Q: Detecting text overflow using javascript I have a component where I am displaying a colon (:) separated list of text. I only need to display that part of the text up to the colon from the start which will be completely visible without over flowing. The rest needs to be truncated. I am using the following code to check for overflow.

function checkOverflow(el) {
  var curOverflow = window.getComputedStyle(el).overflow
  if (!curOverflow || curOverflow === 'visible') {
    el.style.overflow = 'hidden'
  }
  var isOverflowing = el.clientWidth < el.scrollWidth
  el.style.overflow = curOverflow
  return isOverflowing
}

const tableComponent = () => {
  const view = document.getElementById('outer-view')
  console.log(checkOverflow(view))
  console.log(view.scrollWidth, view.clientWidth)
}

document.addEventListener('readystatechange', () => {
  if (document.readyState === 'complete') {
    tableComponent()
  }
})
#outer-view {
  height: 100%;
  width: 100%;
  background-color: lightpink;
  overflow: hidden;
}

{status}

*

*Here status is the variable containing the string of colon separated texts.
(eg. XQV:HGAHGCDHD:KJDGKDGKDHGD.....).

*Also for more clarity lets assume that this div is inside another div whose max-width is set to 300px.

*The text will always be single line. It will never be multiline.

*It is not clamped with elipsis. I am not adding elipsis at the end if it overflows. I have a different logic to run and to change the ui if overflow occurs.

*I will need to detect overflow change on browser resize as well (which should not be a problem as I can call this function again on resize event.)

This code is based on this article but for every case whether the text overflows or not the checkOverflow() always returns false. I also tried checking the scrollWidth and the clientWidth but in every case their value is same. I also tried enclosing the string within a p tag and then try to get the width difference of the div and p tag but they are also the same in every case, irrespective of the fact whether the text overflows or not.
I have tried all the solutions mentioned but none of them seem to work.
Any help in this matter will be greatly appreciated.
I know that there are multiple answers for my issue, but I wrote this article because none of the solutions seem to work in my case.
Thanks to @vsync for pointing out the missing details.


text:
Q: How to restrict/eliminate some records that meet the condition? (right syntax) The question is How many interviews were there in 1995 and 1996.  You must use the IN keyword for your comparison.  Also there is a function called YEAR() that will return the year portion of a date.
TABLE:
mysql> SELECT interviewdate "Date"
    -> FROM interview;

+------------+
| Date       |
+------------+
| 1995-06-01 |
| 1995-06-01 |
| 1995-06-30 |
| 1995-06-30 |
| 1995-07-01 |
| 1995-08-01 |
| 1995-08-01 |
| 1995-08-02 |
| 1995-12-01 |
| 1995-12-02 |
| 1995-12-04 |
| 1996-01-21 |
| 1996-02-01 |
| 1996-02-02 |
| 1996-07-01 |
| 1996-07-01 |
| 1996-08-01 |
| 1996-08-08 |
| 1996-08-11 |
| 1997-01-01 |
| 1997-01-01 |
| 1997-01-31 |
| 1997-02-01 |
| 1997-03-24 |
| 1997-03-31 |
| 1997-04-20 |
| 1997-04-22 |
| 1997-05-01 |
+------------+
28 rows in set (0.00 sec)

OUTPUT:
The condition is to count only those with the Date of 1995 and 1996 into a new table AS "Count(*)". Does anyone know how to do this? I am new to mySQL and trying to understand the syntax. I tried something like this:
SELECT interviewdate, COUNT(interviewdate) AS "COUNT(*)"
FROM interview
GROUP BY interviewdate
HAVING COUNT(interviewdate) == 1995 AND 1996;

+----------+
| COUNT(*) |
+----------+
|       19 |
+----------+
1 row in set (0.00 sec)

A: Try:
SELECT COUNT(*) AS number FROM interview WHERE (interviewdate > 1995-12-31 AND interviewdate < 1997-01-01)

A: This should work:
select count(*)
from interview
where year(interviewdate) in (1995,1996)

*

*SQL Fiddle Demo
And if you need to insert the results into a new table, then use create table as -- more fiddle.


text:
Q: How to do Empty Cache and Hard Reload from js in Angular? When I publish updates of my application I wish to be sure that all files .js, .png and so on will be downloaded with status 200, not 304.
I tried to use this method:
window.location.reload(true);

But after it one can see that some files are still downloaded with 304 status.
How to do Empty Cache and Hard Reload from js in Angular to force all files be downloaded with 304 status?

A: You can force a reload by using output-hashing when creating a Production build see the documentation https://angular.io/cli/build.
The documentaion states it as:

Define the output filename cache-busting hashing mode.

If you set it to all, a unique hash is added to the genrated build files, forcing a client browser to reload the files from the http server.


text:
Q: how to join two csv without crashing the system I asked a question in
Setting a new column based in a dataframe based on condition of other df
But what's happenning is the 1st df contains 300 values and the 2nd one contains 900000 values.
If I cross it using
def preprocess(x):
    data=pd.merge(grid,x, how='cross')
    data.to_csv("outletsWithGrid.csv",mode="a",header=False,index=False)

reader = pd.read_csv("C://Users//A-101//Downloads//Outlets.csv", chunksize=75000) #

[preprocess(r) for r in reader]

The csv files is going to 80gb, and then the system is crashing.
Can anyone help me at any point of the whole series, What change could make it easy.


text:
Q: WP_Query for attachments without duplicating post_parent and displaying tagged image I've tagged a number of media uploads on my site with the various products' names which are featured in them. The goal is to get a list of the posts which have been tagged with each product name, but without duplicating the parent post.
Ideally I would be able to display one of the attachments from Loop 1 (which actually displays the tagged product) with a link to its post_parent, but I have only been able to get the post thumbnail from Loop 2 (these don't always show the product)  to work up to this point.
My brain is fried. Any thoughts?
Loop 1 - querying for attachments with a particular tag.
$media_args = array(
    'post_type' => 'attachment',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'products',
            'field' => 'term_id',
            'terms' => $product_tag
                    )
                )
            );
$media_items = new WP_Query($media_args);

if ($media_items->have_posts()) {
    $parent = array();
    while ($media_items->have_posts()) : $media_items->the_post();
        // getting the post_parent and cleaning to weed out duplicates
        $parent[] = get_post_field('post_parent', $post->ID);
        $parent_clean = array_unique($parent);
    endwhile;
}

Loop 2 - querying for the list of unique posts
$product_post_args = array(
    'post_type' => 'post',
    'posts_per_page' => -1,
    'post__in' => $parent_clean
    );
$product_posts = new WP_Query($product_post_args);

if ($product_posts->have_posts()) { ?>
   while ($product_posts->have_posts()) : $product_posts->the_post();

   $img = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'browse' );

   echo $img[0];

   endwhile;
   }

A: After giving it another look with some fresh eyes, I decided to add a third loop within Loop 2 and not have it working as desired:
$media_args = array(
    'post_type' => 'attachment',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'products',
            'field' => 'term_id',
            'terms' => $product_tag
                )
            )
        );

// Loop 1 - To get the images with the desired tags

$media_items = new WP_Query($media_args);

if ($media_items->have_posts()) {
    $parent = array();
    while ($media_items->have_posts()) : $media_items->the_post();

        // getting the post_parent and cleaning to weed out duplicates

        $parent[] = get_post_field('post_parent', $post->ID);
        $parent_clean = array_unique($parent);
    endwhile;
}

$product_post_args = array(
    'post_type' => 'post',
    'posts_per_page' => -1,
    'post__in' => $parent_clean
);

// Loop 2 - Get the posts which have the images from Loop 1 as attachments without duplicating the same post

$product_posts = new WP_Query($product_post_args);

if ($product_posts->have_posts()) {
   while ($product_posts->have_posts()) : $product_posts->the_post();

       $product_image_args = array(
           'post_type' => 'attachment',
           'posts_per_page' => 1,
           'post_parent' => $post->ID,
           'tax_query' => array(
               array(
                   'taxonomy' => 'productcats',
                   'field' => 'term_id',
                   'terms' => $product_tag
                   )
               )
       );

       // Loop 3 - To get the first attachment with the desired tag for each post

       $product_images = new WP_Query($product_image_args);

       while ($product_images->have_posts()) : $product_images->the_post();
           $img = wp_get_attachment_image_src( $post->ID, 'browse' );
           echo $img[0];
       endwhile;

  endwhile;
}


text:
Q: Go template won't display slice of structs I'm fetching data from postgresql using this:
type Todo struct {
ID int
Body string
AuthorID int
Done bool
}

err := rows.Scan(&todo.ID, &todo.Body, &todo.AuthorID, &todo.Done)

I return this from the function, is a slice of *Todo structs.
In the handler, the output of for
_, todo := range todos {
fmt.Fprintf(w, "%d, %s, %d, %t\n", todo.ID, todo.Body, todo.AuthorID, todo.Done)
}

is:
2018/10/03 20:09:00 &{1 buy carrots 123 true}
2018/10/03 20:09:00 &{2 cook carrots 123 false}
2018/10/03 20:09:00 &{3 eat carrots 125 false}
the output of
fmt.Printf("%#v", todos)

is:
[]*models.Todo{}
When I pass this as data to template.execute,

  {{ range . }}

                {{ .AuthorID }} wrote:

{{ .Body }}

        {{ end }}

Displays nothing.
I am really puzzled here, there are no errors anywhere, and googling brings me nothing.

A: I simply forgot to append the new todo insantiation to the todos slice
Sigh, three hours of my life


text:
Q: How check value existence in a deeply nested array in MongoDB.Driver C#? As the following image, the collection is Posts. The _ids for the post and the comment are known.
So, How to check if a given value d exists in the AgreedUserIds?

A: Try this for single character search:
db.Posts.find(
    {
        _id: "b4d5...ff79",
        Comments: {
            $elemMatch: {
                _id: "c1ea...d45",
                AgreedUserIds: "d"
            }
        }
    }
);

And this for multi character search:
db.Posts.find(
    {
        _id: "b4d5...ff79",
        Comments: {
            $elemMatch: {
                _id: "c1ea...d45",
                AgreedUserIds: { $in: ["c", "d"] }
            }
        }
    }
);

A: If you want to keep it BsonDocument you have options to combine filters like this>
var client = new MongoClient();
var database = client.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("posts");
var postId = new BsonObjectId(new ObjectId("604b5ff389ff6887d1b91a93"));
var commentId = new BsonObjectId(new ObjectId("604b5ff389ff6887d1b91a92"));
var userId = "a";
//var userId = "e"; // not found
var postIdMatches = Builders<BsonDocument>.Filter.Eq("_id", postId);
var commentIdMatches = Builders<BsonDocument>.Filter.Eq("_id", commentId);
var userIdInside = Builders<BsonDocument>.Filter.AnyEq("AgreedUserIds", userId); // "a" in checking
var commentCheck = Builders<BsonDocument>.Filter.ElemMatch("Comments", userIdInside & commentIdMatches); // & combines filters. Also ElemMatch on any of the Comments is passing the criteria
var rows = (await collection.FindAsync<BsonDocument>(postIdMatches & commentCheck)).ToList();

You could also GetCollection<Post> with C# Post class describing the Post business object, and use .Any Linq query on that.


text:
Q: Problem with Spring Batch reader from PostgreSQL DB1 to write in PostgreSQL DB2 I have a problem when I want to read data from PostgreSQL Author DB and write to the PostgreSQL Book DB.
I create configurations for the two DB and this is work well.
My problem is in ItemReader.
 This is my error:
Encountered an error executing step ETL-file-load in job ETL-Load
error: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: author is not mapped [select id,firstname,lastname from author]

This is my SpringBatchConfig configuration class:
@Configuration
@EnableBatchProcessing
public class SpringBatchConfig {

     @Autowired
      private EntityManagerFactory entityManagerFactory;

     @Bean
        public Job job(JobBuilderFactory jobBuilderFactory,
                       StepBuilderFactory stepBuilderFactory,
                       ItemReader<Author> itemReader,
                       ItemProcessor<Author, Book> itemProcessor,
                       ItemWriter<Book> itemWriter
        ) {

            Step step = stepBuilderFactory.get("ETL-file-load")
                    .<Author, Book>chunk(100)
                    .reader(itemReader)
                    .processor(itemProcessor)
                    .writer(itemWriter)
                    .build();

            return jobBuilderFactory.get("ETL-Load")
                    .incrementer(new RunIdIncrementer())
                    .start(step)
                    .build();
        }

     @Bean
        public ItemReader<Author> itemReader() throws Exception {
            JpaPagingItemReader<Author> reader = new JpaPagingItemReader<Author>();
            reader.setEntityManagerFactory(entityManagerFactory);
                        reader.setQueryString("select id,firstname,lastname from author");

            reader.setPageSize(5);
            reader.afterPropertiesSet();

            return reader;
        }

}

This is my Processor class:
@Component
public class Processor implements ItemProcessor<Author, Book> {

@Override
public Book process(Author item) throws Exception {

    Book book = new Book();
    book.setName(item.getFirstname());

    return book;
}

}
This is my DBWriter Class:
   @Component
public class DBWriter implements ItemWriter<Book> {

    @Autowired
    private BookRepository bookRepository;

    @Override
    public void write(List<? extends Book> book) throws Exception {
         System.out.println("Data Saved for Users: " + book);
            bookRepository.save(book);

    }

}
This is my Author JPA:
@Entity
@Table(name = "author")
public class Author implements Serializable {

    private static final long serialVersionUID = -1848119459950659679L;

    @Id
    @Column(name = "id")
    private Long id;

    @Column(name = "firstname")
    private String firstname;

    @Column(name = "lastname")
    private String lastname;

This is my application.properties file:
spring.postgresql.datasource.url=jdbc:postgresql://localhost:5432/book_db
spring.postgresql.datasource.username=admin
spring.postgresql.datasource.password=admin
spring.postgresql.datasource.driver-class-name=org.postgresql.Driver

# ------------------------------
# POSTGRESQL DATABASE 2 CONFIGURATION
# ------------------------------
spring.mysql.datasource.url=jdbc:postgresql://localhost:5432/author_db
spring.mysql.datasource.username=admin
spring.mysql.datasource.password=admin
spring.mysql.datasource.driver-class-name=org.postgresql.Driver

This is Auhtor in DB:

This is my full output:
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: author is not mapped [select id,firstname,lastname from author]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1679) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1608) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:294) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:347) ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at com.sun.proxy.$Proxy80.createQuery(Unknown Source) ~[na:na]
    at org.springframework.batch.item.database.JpaPagingItemReader.createQuery(JpaPagingItemReader.java:112) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.item.database.JpaPagingItemReader.doReadPage(JpaPagingItemReader.java:203) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.item.database.AbstractPagingItemReader.doRead(AbstractPagingItemReader.java:108) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.read(AbstractItemCountingItemStreamItemReader.java:88) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.item.SimpleChunkProvider.doRead(SimpleChunkProvider.java:91) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.item.SimpleChunkProvider.read(SimpleChunkProvider.java:157) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.item.SimpleChunkProvider$1.doInIteration(SimpleChunkProvider.java:116) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:374) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.item.SimpleChunkProvider.provide(SimpleChunkProvider.java:110) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:69) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133) ~[spring-tx-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:271) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:81) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:374) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:200) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:392) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at com.sun.proxy.$Proxy89.run(Unknown Source) [na:na]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.execute(JobLauncherCommandLineRunner.java:216) [spring-boot-autoconfigure-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.executeLocalJobs(JobLauncherCommandLineRunner.java:233) [spring-boot-autoconfigure-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.launchJobFromProperties(JobLauncherCommandLineRunner.java:125) [spring-boot-autoconfigure-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.run(JobLauncherCommandLineRunner.java:119) [spring-boot-autoconfigure-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:800) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:784) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:771) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at com.roufid.tutorial.Application.main(Application.java:10) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.4.2.RELEASE.jar:1.4.2.RELEASE]
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: author is not mapped [select id,firstname,lastname from author]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:218) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:76) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:302) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:240) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1894) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:291) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
    ... 62 common frames omitted
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: author is not mapped
    at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:171) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:76) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:321) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3687) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3576) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:716) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:572) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:309) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:257) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    ... 70 common frames omitted

A: Your query is not a valid JPA Query.
This would be a valid query:
select a.id, a.firstname, a.lastname from Author a

BUT you want to select the whole Author so it must be
select a from Author a

A: I don't know if your problem is solved, but I found the solution.
"select id,firstname,lastname from author"

replace
"from id,firstname,lastname from author"


text:
Q: windows store submission issue for privacy policy After Submission to Windows Store I am Getting the Following Issues :-
App Policies: 10.1 Inaccurate Functionality
Your app and its associated metadata must accurately and clearly reflect the source, functionality, and features of your app.
All aspects of your app should accurately describe the functions, features and any important limitations of your app, including required or supported input devices. Your app may not use a name or icon similar to that of other apps, and may not claim to be from a company, government body, or other entity if you do not have permission to make that representation.
Your app must be fully functional and must provide appropriate functionality for each targeted device family.
Keywords may not exceed seven unique terms and should be relevant to your app.
Your app must have distinct and informative metadata and must provide a valuable and quality user experience.
Tested OSes: Windows 10 Mobile
Tested Devices: Acer Iconia W700, Lumia 650
Notes To Developer
The app contains placeholder content that impairs access to core functions of the app.
App Policies: 10.5.1 Privacy Policy
The following requirements apply to apps that access personal information. Personal information includes all information or data that identifies or could be used to identify a person, or that is associated with such information or data. Examples of personal information include: name and address, phone number, biometric identifiers, location, contacts, photos, audio & video recordings, documents, SMS, email, or other text communication, screen shots, and in some cases, combined browsing history.
If your app accesses, collects or transmits personal information, or if otherwise required by law, you must maintain a privacy policy. You must provide users with access to your privacy policy by entering the privacy policy URL in Dev Center when you submit your app. In addition, you may also include or link to your privacy policy in the app. The privacy policy can be hosted within or directly linked from the app. Your privacy policy must inform users of the personal information accessed, collected or transmitted by your app, how that information is used, stored and secured, and indicate the types of parties to whom it is disclosed. It must describe the controls that users have over the use and sharing of their information and how they may access their information, and it must comply with applicable laws and regulations. Your privacy policy must be kept up-to-date as you add new features and functionality to your app.
Additionally, apps that receive device location must provide settings that allow the user to enable and disable the app's access to and use of location from the Location Service API. For Windows Phone 8 and Windows Phone 8.1 apps, these settings must be provided in-app. For Windows Mobile 10 apps, these settings are provided automatically by Windows within the Settings App (on the Settings->Privacy->Location page).
You may publish the personal information of customers of your app to an outside service or third party through your app or its metadata only after obtaining opt-in consent from those customers. Opt-in consent means the customer gives their express permission in the app user interface for the requested activity, after you have:
described to the customer how the information will be accessed, used or shared, indicating the types of parties to whom it is disclosed, and
provided the customer a mechanism in the app user interface through which they can later rescind this permission and opt-out.
If you publish a person's personal information to an outside service or third party through your app or its metadata, but the person whose information is being shared is not a customer of your app, you must obtain express written consent to publish that personal information, and you must permit the person whose information is shared to withdraw that consent at any time. If your app provides a customer with access to another person's personal information, this requirement would also apply.
If your app collects, stores or transmits personal information, it must do so securely, by using modern cryptography methods.
Your app must not collect, store or transmit highly sensitive personal information, such as health or financial data, unless that information is related to the primary purpose of the app.
Your app must not collect, store or transmit personal information unrelated to its primary purpose, without first obtaining express user consent.
Tested OSes: Windows 10 Mobile
Tested Devices: Acer Iconia W700, Lumia 650
Notes To Developer
The privacy policy provided for this app fails to inform users of the personal information transmitted by your app and how that information is used, stored, secured, and disclosed. See policy 10.5.1 for details about the requirements for a privacy policy.
I have already stated the privacy policy indicating the use of names ,private data etc. What needs to be done for this type of issue? Any help. Thank you.

A:
What needs to be done for this type of issue?

Without seeing your app, it's really hard to make detailed advice at forum. Regarding this type of question, it will be more appropriate to create a support ticket through your developer account so that support can give you specific suggestion after reviewing your submission.
You may rewrite your privacy policy following How To Add a Privacy Policy to Windows Phone Apps, which is old but you can still find some useful info within it.


text:
Q: How to t-test by group in a pandas dataframe? I have quite a huge pandas dataframe with many columns. The dataframe contains two groups. It is basically setup as follows:
import pandas as pd
csv = [{"air" : 0.47,"co2" : 0.43 , "Group" : 1}, {"air" : 0.77,"co2" : 0.13 , "Group" : 1}, {"air" : 0.17,"co2" : 0.93 , "Group" : 2} ]
df = pd.DataFrame(csv)

I want to perform a t-test paired t-test on air and co2 thereby compare the two groups Group = 1 and Group = 2.
I have many many more columns than just air co2- hence, I would like to find a procedure that works for all columns int the dataframe. I believe, I could use scipy.stats.ttest_rel together with pd.groupby oder apply. How would that work? Thanks in advance /R

A: I would use pandas dataframe.where method.
group1_air = df.where(df.Group== 1).dropna()['air']
group2_air = df.where(df.Group== 2).dropna()['air']

This bit of code returns into group1_air all the values of the air column where the group column is 1 and all the values of air where group is 2 in group2_air.
The drop.na() is required because the .where method will return NAN for every row in which the specified conditions is not met. So all rows where group is 2 will return with NAN values when you use df.where(df.Group== 1).
Whether you need to use scipy.stats.ttest_rel or scipy.stats.ttest_ind depends on your groups. If you samples are from independent groups you should use ttest_ind if your samples are from related groups you should use ttest_rel.
So if your samples are independent from oneanother your final piece of required code is.
scipy.stats.ttest_ind(group1_air,group2_air)

else you need to use
scipy.stats.ttest_rel(group1_air,group2_air)

When you want to also test co2 you simply need to change air for co2 in the given example.
Edit:
This is a rough sketch of the code you should run to execute ttests over every column in your dataframe except for the group column. You may need to tamper a bit with the column_list to get it completely compliant with your needs (you may not want to loop over every column for example).
# get a list of all columns in the dataframe without the Group column
column_list = [x for x in df.columns if x != 'Group']
# create an empty dictionary
t_test_results = {}
# loop over column_list and execute code explained above
for column in column_list:
    group1 = df.where(df.Group== 1).dropna()[column]
    group2 = df.where(df.Group== 2).dropna()[column]
    # add the output to the dictionary
    t_test_results[column] = scipy.stats.ttest_ind(group1,group2)
results_df = pd.DataFrame.from_dict(t_test_results,orient='Index')
results_df.columns = ['statistic','pvalue']

At the end of this code you have a dataframe with the output of the ttest over every column you will have looped over.


text:
Q: How can I use excel to create a multiple IF function? I have a spreadsheet comparing numbers of programmes sold by my company. I want to create a formula that will total several variables.
In one column I have the month then whether it is a "Finance" or an "Enterprise" programme, then I have the number of minutes sold. I want to create a formula for each month telling me how many minutes of each programme were sold.
e.g. in September we sold 200 minutes of Enterprise programmes.
How can I create a formula to do this when 3 columns are involved?

A: Assuming that you have the month in column A, the type of programme in column B and the minutes in column C, you can use SUMIFS:
=SUMIFS(C:C, A:A, "September", B:B, "Enterprise")

Put the formula in any cell that is not in columns A, B or C, or you'll likely get a circular reference warning.


text:
Q: Comparing and visualizing rates of subsystems I am trying to track the performance of a set of homogeneous subsystems vs the system as a whole. The performance metric is measured by a mean value based on a set of tasks performed by a the subsystem, for example, the mean wait time before scheduling task.
Each subsystem may be responsible for varying numbers of tasks. I can calculate the mean wait time for each subsystem and for the system as a whole.
My question is how to measure and visualize how each subsystem is performing compared to the whole system average (or maybe there's a better aggregate measure for the whole system?)
Obviously being below the mean shows the subsystem is performing relatively better and above the mean vice versa, and the distance from the whole system mean represents that, but I struggle to get real meaning or provide a good visualization from that.
Is there a better way? Or if I'm on the right track, how do I assign meaning / visualize the metric?

A: It sounds like you should lookup the topic of statistical process control. Its origins lie in manufacturing where deviations from expected process output are used to raise flags to ensure that quality of manufactured items is as per pre-established norms. In particular, see the wikipedia description for control charts which should get you started on the visualization aspect.


text:
Q: Как залить локальную версию git на GITHub привет...Создал у себя локальный Git- проект...
Есть созданный на GitHub branch который назыв. master..
Но получаю ошибку...В чем проблема?
Перед тем не выкачивал себе проэкт.

A: git pull --rebase не работает, потому что вы явно не указываете remote. Нужно
git pull --rebase mster master

или ещё лучше remote называть как-то типа origin или upstream:
git remote add origin git@...

и потом
git pull --rebase origin master


text: Q: Do red lasers shoot longer than green ones? I am aware of the fact that our eyes are most sensible to green color and therefore green lasers seem stronger than other colors when being scattered through the air. However, since red wavelength are longer than green and not as easily subjected to Reyleigh scattering as green, shouldn't red lasers be able to hit more distant surfaces?


text:
Q: New intent in LUIS for multi turn dialogs I am going to create a multi-turn dialog. I didn't get how it should be connected with LUIS models. I checked out documentation, but there are samples with only one turn dialogs. Also, I use Virtual Assistant template.
I want to do something like this.

User: I want to book a flight
Bot: What is the destination?
User: London
Bot: When?
User: 21st of September.
Bot: The ticket was bought.

The questions are what happens on the second step? Should I check out dispatcher? Should I add all possible phrases for all steps inside the intent?

A: General LUIS stuff
For your LUIS model you will need your intents - BookFlight and None. Under your BookFlight intent you will have your Utterances - all the phrases you want to be able to trigger the BookFlight intent.
MyLuisApp
--BookFlight
----I want to book a flight
----Book a flight
----I need a plane ticket
----etc
--None
----Utterances that don't match any of your intents

The none intent is VERY important as per this documentation.

Adding this functionality to a new bot or the core bot template
There are a couple different samples provided on how you could achieve this, but the best way is using Dialogs. What you want is a Waterfall Dialog. Inside this Dialog you can define each stage in the waterfall e.g. Ask for destination, ask for date etc.
In order to trigger the BookFlight waterfall you would have a MainDialog that handled every request, and checks with the LUIS dispatcher link1 and link2 to find out the users intent as per this example. If the intent is BookFlight then you would start the BookFlightDialog which contains the book flight waterfall.
...
// Check dispatch result
var dispatchResult = await cognitiveModels.DispatchService.RecognizeAsync<DispatchLuis>(dc.Context, CancellationToken.None);
var intent = dispatchResult.TopIntent().intent;

if (intent == "BookFlight")
{
    // Start BookFlightDialog
    await dc.BeginDialogAsync(nameof(BookFlightDialog));
}

General Waterfall Dialog stuff
You'd define your steps as something like:
var waterfallSteps = new WaterfallStep[]
{
    AskDestinationAsync,
    AskDepartureDateAsync,
    ConfirmStepAsync,
    FinishDialogAsync,
};

For your scenario there is actually a sample that has already been created with the BookFlight intent available here. There is a full guide on how to get this setup and working in the official documentation. So you can test to see how everything works then modify it as you need.
Other interesting links:

*

*Custom prompt sample - roll your own.

*Multi-turn sample - waterfall dialog.

Virtual Assistant stuff
Once you understand how the above works you will be able to modify the Virtual Assistant template to handle the BookFlight intent by taking the following actions:

*

*Adding a BookFlight intent to your existing LUIS DISPATCH app that is connected to your VA template.

*Adding utterances to the BookFlight intent.

*Save and train your LUIS app.

*Publish your LUIS app.

*Running the update_cognitive_models.ps1 script as per step 3 of the instructions here which will pull down the changes (your new intent and utterances).

*

*.\Deployment\Scripts\update_cognitive_models.ps1 -RemoteToLocal

*

*NOTE: This command must be run using PowerShell Core and from the root of your project Directory, i.e. inside your Virtual Assistant folder.

The result of running this script should be a bunch of files created locally, as well as the DispatchLuis.cs file being updated to include your new intent. You should also check the Summary.html file that is created to see that your new intent is there. You will now have to update the VA code to actually do something when your new intent is triggered - add another if/case statement inside the RouteAsync method of the MainDialog.cs file - see here for an example.
Something like this:
MainDialog.cs

protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
{
    // Call to dispatch to get intent

    if (intent == DispatchLuis.Intent.bookflight)
    {
        // Start BookFlightDialog
        await dc.BeginDialogAsync(nameof(BookFlightDialog));
    }
    ...
}


text:
Q: Convert HTML to PDF using PrimceFaces 7.0 (or higher) Text Editor and Quill I use PirmeFaces 7.0 and want to be able to convert the HTML generated by the PrimeFaces TextEditor component
https://primefaces.github.io/primefaces/7_0/#/components/texteditor
into PDF using a Java library, such as itext or apache-fop
Since the above TextEditor component is based on Quill and uses stylesheets from Quill I would like to ask if somebody has experience generating high-quality PDFs based on its input.
Any experience / examples / feedback will be appreciated
NOTE: In the comments some of you suggest an answer with itext converting from HTML with styles.
This does not help me, because I tried to extract the css file used in the PrimeFaces TextEditor component. And, yes, I extarct it, but... somehow the browser does not recognize it. I do not know why, the file is deliberately made human-unreadable


text:
Q: QCustomPlot: Plotting 2 Colormaps - Axes and Ticks Dissappear I want to plot two colormaps. I want to plot them into the same window but into different axisrects. On top of each other. What happens is that the first color map is plotted nicely, but the second one is overlapping most of the axes and ticks and looks just awful.
Here is a minimal working example:
    QCustomPlot * pCstmPlt = new QCustomPlot;
    pCstmPlt->show();
    QCPAxisRect *axisRect = pCstmPlt->axisRect(0);
    axisRect->setupFullAxesBox(true);

    QCPColorMap *colorMap = new QCPColorMap(axisRect->axis(QCPAxis::atBottom),axisRect->axis(QCPAxis::atLeft));
    int Clrny = 100;
    int Clrnx = 100;
    colorMap->data()->setSize(Clrnx, Clrny);
    colorMap->data()->setRange( QCPRange( 1,100 ), QCPRange( 1,100 ) );
    double x, y, dVal;
    for (int xIndex=0; xIndex<100; ++xIndex)
    {
        for (int yIndex=0; yIndex<100; ++yIndex)
        {
            colorMap->data()->cellToCoord(xIndex, yIndex, &x, &y);
            dVal = ( xIndex * yIndex );
            colorMap->data()->setCell(xIndex, yIndex, dVal);
        }
    }
    // add a color scale:
    QCPColorScale *pmycolorScale = new QCPColorScale(pCstmPlt);
    pCstmPlt->plotLayout()->addElement(0, 1, pmycolorScale);
    pmycolorScale->setType(QCPAxis::atRight);
    colorMap->setColorScale(pmycolorScale);
    colorMap->setGradient( QCPColorGradient::gpPolar );

    axisRect = new QCPAxisRect(pCstmPlt,true);
    axisRect->setupFullAxesBox(true);
    pCstmPlt->plotLayout()->addElement(1,0,axisRect);
    QCPColorMap *colorMap2 = new QCPColorMap(axisRect->axis(QCPAxis::atBottom),axisRect->axis(QCPAxis::atLeft));
    colorMap2->data()->setSize(Clrnx, Clrny);
    colorMap2->data()->setRange( QCPRange( 1,100 ), QCPRange( 1,100 ) );
    for (int xIndex=0; xIndex<100; ++xIndex)
    {
        for (int yIndex=0; yIndex<100; ++yIndex)
        {
            colorMap2->data()->cellToCoord(xIndex, yIndex, &x, &y);
            dVal = ( xIndex * yIndex );
            colorMap2->data()->setCell(xIndex, yIndex, dVal);
        }
    }
    // add a color scale:
    QCPColorScale *pmycolorScale2 = new QCPColorScale(pCstmPlt);
    pCstmPlt->plotLayout()->addElement(1, 1, pmycolorScale2);
    pmycolorScale2->setType(QCPAxis::atRight);
    colorMap2->setColorScale(pmycolorScale2);
    colorMap2->setGradient( QCPColorGradient::gpPolar );
    colorMap->rescaleDataRange();
    colorMap2->rescaleDataRange();
    pCstmPlt->rescaleAxes();
    pCstmPlt->setMinimumSize(QSize(500,500));

The result looks like this:

So, clearly, the lower plot misses ticks and axes.

A: In case any one else will be wondering about this: The question was answered somewhere else,
https://www.qcustomplot.com/index.php/support/forum/2269
The trick was to put all axes on the "axes" layer with
      axis->setLayer("axes");


text:
Q: How to develop a theme while having another show up The title is the question : How to develop a theme while having another show up
I already have a DB and a theme.... i like, when log as admin see another theme... just for the time making it clean and final... and then, remove the old one and have the new one able to be see for everybody...
any plugin that do that ?

some research and result : http://wordpress.org/extend/plugins/theme-test-drive/
 and http://wordpress.org/extend/plugins/nkthemeswitch/
not sure what it's worth....

A: Perhpas you can keep the theme live you want others to see and for your self use url theme switcher to switch theme like : `

http://www.you_site.com/index.php?wptheme=WordPress+Classic

replace www.you_site.com with your own site url.

A: Based on this question
<?php
/* SWAP THEME ACCORDING TO USER */
function wpse50258_change_theme( $template = '' ) {
    global $current_user;
    get_currentuserinfo();
    if ( $current_user->user_login === 'YOUR-USER-NAME' ) {
        $template = 'twentyten';
    }
    return $template;
}
add_filter('template', 'wpse50258_change_theme');
add_filter('option_template', 'wpse50258_change_theme');
add_filter('option_stylesheet', 'wpse50258_change_theme');

[UPDATE]
PS: this only works if fired from a plugin, not from functions.php

A: I used this one a while ago and it worked. Hasn't been updated in a while...but should still work.
http://wordpress.org/extend/plugins/parallels-themes-switcher

A: You can clone the site to your computer (running XAMPP or some other local server software) and work locally while developing the new theme. When it's tested and ready, upload the new theme and make the switch.
Alternately, copy the site to a subfolder and use that or a subdomain like dev.yoursite.com to develop. Usually you'll want to use a plugin like Maintenance Mode to hide the dev site.
I use BackupBuddy for moving the site down and back up. It's a bit faster than a manual move, but neither is particularly hard.


text:
Q: osCommerce: custom price based on user input I am writing a simple JavaScript which will update my price automatically (I know there are addons but they dont work with the nature of my products) when the user enters amount, size etc etc. I want to know how do I override the product price before/after it is sent to the shopping cart?
Example: The product price is 10€. The user select some variatons and then the price is 22,40€. I want to send that price to the checkout instead of the 10€.
So far I have written my JavaScript which updates the price based on user input and selections. I just need to know how to pass that new price variable and more important WHERE.
Any tips or help would be appreciated.

A: You mention "variations".  Are you using attributes?  If so, you can simply attach a price adjustment to each option value.  That would be the quickest and most proper way to handle variation-specific pricing.


text:
Q: Get only values of dynamic JSON in comma separated string in Typescript I have this dynamic JSON -
    {
    "SMSPhone": [
        "SMS Phone Number is not valid"
    ],
    "VoicePhone": [
        "Voice Phone Number is not valid"
    ]
}

I need only values as comma separated string. Also, its dynamic so, i do not know the key names.
Desired result - SMS Phone Number is not valid,Voice Phone Number is not valid
Code i tried -
let res=JSON.parse(Jsondata);
   res.forEach(element => {
    console.log(element)
    //logic
  });

I am getting following error

A: I don't know what you want to achieve here. But you can't use forEach on an object. forEach is used to loop through data in an array.
In your case, I would use object.entries() as shown below to achieve my goal.

const data = {
    "SMSPhone": [
        "SMS Phone Number is not valid"
    ],
    "VoicePhone": [
        "Voice Phone Number is not valid"
    ]
};

for (const [key, value] of Object.entries(data)) {
  console.log(`${key}: ${value}`);
}

A: res is an object, so you can't use forEach.  If you want to iterate over an object's values, you need to do something like:
for (const [key, value] of Object.entries(Jsondata)) {
  console.log(value);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries


text:
Q: TypeError: Cannot read property '0' of undefined in nodejs mongoose Here is the code
const {validationResult} = require('express-validator');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/user');

exports.login = (req, res, next) => {
const email = req.body.email;
const password = req.body.password;
let loadedUser;
User.findOne({email:email})
.then(user => {
    if(user){
        loadedUser = user;
        return bcrypt.compare(password, user.password);
    } else{
        const error = new Error('EMAILID_NOT_FOUND');
        error.statusCode = 401;
        throw error;
    }

})
.then(
    isEqual => {
        console.log(isEqual);
        if(!isEqual){
            const error = new Error('WRONG_PASSWORD');
            console.log(error)
            error.statusCode = 401;
            throw error;
        }
        const token = jwt.sign({
            email: loadedUser.email,
            userId: loadedUser._id.toString()
        },'somesecrekey',{expiresIn:'7d'}
        );
        res.status(200).json({
            token: token,
            userId: loadedUser._id.toString()
        });
        })
        .catch(err => {
            if(!err.statusCode){
                err.statusCode =500;
            }
            next(err);
        });
};

app.js

const express = require('express');
const bodyparser = require('body-parser');
const mongoose = require('mongoose');

const path = require('path');

const eventRoutes = require('./routes/eventRouter');
const companyRoutes = require('./routes/companyRouter');
const authrouter = require('./routes/authrouter');

const app = express();

// app.use(bodyparser.urlencoded());

app.use(bodyparser.json()); //application/json
app.use('/images',express.static(path.join(__dirname, 'images')));

app.use((req, res, next)=>{
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH,
DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
})

app.use('/auth', authrouter);
app.use('/event', eventRoutes);
app.use('/company',companyRoutes);

app.use((error, req, res, next)=>{
const status = error.statusCode || 500;
const message = error.message;
const data = error.data;
const errmsg = data[0].msg;
res.status(status).json({ error: message, errmsg: errmsg, data: data });
});

mongoose.connect('mongodb://localhost:27017/scope').then(result=>{
app.listen(8080)
}).catch(err => console.log(err));

I'm trying to do authentication in nodejs and mongoose
when the user presses log in the api will get called with the body of email and password when the control comes to the login function it will check for email exists or not in the database and checks for password is correct or not
Here I'm getting the error as TypeError: Cannot read property '0' of undefined
with the error message
Error: WRONG_PASSWORD
at User.findOne.then.then.isEqual (F:\Codebase\Ack
Codebase\SCOPE\scope_server\controllers\authcontroller.js:63:31)
App Error: WRONG_PASSWORD
TypeError: Cannot read property '0' of undefined
at app.use (F:\Codebase\Ack Codebase\SCOPE\scope_server\app.js:34:24)
at Layer.handle_error (F:\Codebase\Ack
Codebase\SCOPE\scope_server\node_modules\express\lib\router\layer.js:71:5)
at trim_prefix (F:\Codebase\Ack
Codebase\SCOPE\scope_server\node_modules\express\lib\router\index.js:315:13)
at F:\Codebase\Ack
Codebase\SCOPE\scope_server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (F:\Codebase\Ack
Codebase\SCOPE\scope_server\node_modules\express\lib\router\index.js:335:12)
at Immediate.next (F:\Codebase\Ack
Codebase\SCOPE\scope_server\node_modules\express\lib\router\index.js:275:10)
at Immediate.<anonymous> (F:\Codebase\Ack
Codebase\SCOPE\scope_server\node_modules\express\lib\router\index.js:635:15)
at runCallback (timers.js:706:11)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)

Please help
thanks


text:
Q: Not getting XY image size after using "zoom to rect" in a matplotlib figure when using GUI I am trying to get a ROI (region of interest) from a loaded image. Using the "Zoom to rect" option from the matplotlib figure and sing a GUI with 2 buttons:
Zoom to rect
Button1: "LoadImage"- load and plot the image and should also save into 2 list the new XY size of the zoomed image
Button2: "RunimgeAnalisis" should read the information of the 2 list in order to crop the ROI out of the original image
Problem: my code is not saving in the lists (xlist/ylist) the new XY information after using the "Zoom to rect". Whe running the code WITHOUT the GUI(bottons), I do obtain the XY size after selecting the zoom with the mouse but when implementing the code into a GUI-buttons, the new XY values of the zoom are not passed to the list. Right after selecting the zoom area in the image with the mouse,  the values are never passed to the execution of the program.
My code:
import numpy as np
import scipy.signal
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import BOTH, END, LEFT
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import os

xlist =[]
ylist =[]
image_path = 'C:/Users/Desktop/Images/TestImage1.raw'

# Load image, the image is ploted and the user will select with the mouse a ROI with the
#zoom rectangle option from matplotlib a new (x1, x2) and (y1,y2) will be saved on xlist ylist
def LoadImage(image_path):
    InputImage = np.fromfile(image_path, dtype='uint16', count=3840 \* 2160)
    InputImage = np.reshape(InputImage, (2160, 3840))
    xlist = []
    ylist = []
    plt.figure(1)
    plt.imshow(InputImage, interpolation_stage='rgba')

    #A ROI form the image is selected with the zoom rectantgle from matpotlib (Declare and register  callbacks)
    def on_xlims_change(event_ax):
        xlist.append(event_ax.get_xlim())
        print("updated xlims: ", event_ax.get_xlim())

    def on_ylims_change(event_ax):
        ylist.append(event_ax.get_ylim())
        print("updated ylims: ", event_ax.get_ylim())
    plt.colorbar()

#with the information from xlist and ylist, the ROI is croped and saved in ImageRegion for
#further analisis
def RunImageAnalisis(xlist, ylist):
     x1 = int(xlist[0])
     x2 = int(xlist[1])
     y1 = int(ylist[0])
     y2 = int(ylist[1])
     ImageRegion = ImageToProcess[y1:y2, x1:x2]

#GUI with 2 buttons: LoadImage and RunAnalisis
root = tk.Tk()
root.title("Image Tool")
MainForm = tk.Canvas(root, width=145, height=320)
MainForm.grid(columnspan =3, row=2)

bottom_Name = tk.StringVar()
Run_btn = tk.Button(root, text='Run', command=lambda:RunImageAnalisis(xlist, ylist), height=1, width=9, fg="black", bg="grey")
bottom_Name.set("Run")
Run_btn.grid(column=1, row=1, sticky='nw', padx=15, pady=15)

bottom_Name1 = tk.StringVar()
GetData_btn = tk.Button(root, text='LoadIm', command=lambda:LoadImage(image_path),  height=1, width=9, fg="black", bg="grey")
bottom_Name.set("LoadIm")
GetData_btn.grid(column=2, row=1, sticky='nw',pady=15)

root.mainloop()

I tried: I ran the code without using the GUI-implementation and this is working  correctly. The new xy values are correctly saved in the xlist and ylist after selecting the zoom area with the mouse
But when I ran the GUI implemented code on debug mode, I could corroborate that after selecting with the mouse the image zoom area, the values are never passed to the xlist/ylist. Seems like program execution is hanging on the image and data never return to the program and thus variable explorer is empty
Expected Result : Button "Load" should load and plot the image. then the user should select with the mouse the zoom area and new xy values should be saved in xlist and ylist
Then, button "RunImageAnalisis" should use new XY values saved on xlist and ylist to crop the ROI out of the original image. This new ROI image array will be used for further analysis
thank you for your help


text:
Q: Google Nest subscriptionWithMessageFoundHandler fires once? I am trying to code around the fact that the messageLostHandler doesn't fire for many minutes after a device is out of range using Audio (or Earshot for Android).
I was hoping that every few secs a message would be received from another device. It fires once. Is this expected? Since I can't rely on the messageLost handler - how do I know when a device is truly out of range of the ultrasonic?
I coded up a timer after receiving the subscriptionWithMessageFoundHandler hoping another message coming in I could just invalidate or restart the timer. If the timer fired, I'd know that x seconds passed and that the other device must be out of range. No such luck.
UPDATE: Here is the code in question:
let strategy = GNSStrategy.init(paramsBlock: { (params: GNSStrategyParams!) -> Void in
    params.discoveryMediums = .Audio
})

publication = messageMgr.publicationWithMessage(pubMessage, paramsBlock: { (pubParams: GNSPublicationParams!) in
    pubParams.strategy = strategy
})

subscription = messageMgr.subscriptionWithMessageFoundHandler({[unowned self] (message: GNSMessage!) -> Void in
    self.messageViewController.addMessage(String(data: message.content, encoding:NSUTF8StringEncoding))

    // We only seem to get a 1x notification of a message. So this timer is folly.
    print("PING") //Only 1x per discovery.

}, messageLostHandler: {[unowned self](message: GNSMessage!) -> Void in
    self.messageViewController.removeMessage(String(data: message.content, encoding: NSUTF8StringEncoding))
}, paramsBlock: { (subParams: GNSSubscriptionParams!) -> Void in
    subParams.strategy = strategy
})

Notice that the "PING" only prints once.

A: When a device goes out of range, Nearby waits for 2 minutes before flushing the other device's token from its cache.  So if you wait for 2 minutes, the messageLost handler should be called.  Can you verify this?  Also, is it safe to assume that you'd like to have a timeout shorter than 2 minutes?  This timeout has been a topic of discussion, and there's been some talk of adding a parameter so apps can choose a value that's more appropriate for its use case.


text:
Q: TFS clone build link other branch I use VS2010 builds. I create build containing multiple solution and custom properties (custom template).
When I clone a build definition, like it should, it keep all path to the "branch" of the build. So if I want to create a build for a new branch, it could be long because I need to change like 20 path/properties. Is there a way to create a button that create a build, based on existant build but with properties based on another branch? Maybe there's a way to edit the build definition xml file after cloning it?

A: I don't think it is possible for you to do these adjustments automatically, you have to do it manually.


text:
Q: Заменить все символы на пробелы Я считываю строку, состоящую из чисел, разделенных различными символами, как удалить из строки все символы, заменив их на пробелы. (хочу посчитать сумму этих чисел в конечном итоге). Ограничу условия - числа целые, но могут быть отрицательными, примеры входных последовательностей : "1,2,._3" Итог суммы : 6

A: Если это char* -
for(char * c = s; *c; ++s)
    if (!isdigit(*c)) *c = ' ';

Если это строка string - то, в принципе, так же:
for(size_t i = 0; i < s.length(); ++i)
    if (!isdigit(s[i])) s[i] = ' ';

Update
Ага, раз вопрос не в замене всех символов на пробелы (см. заголовок вопроса), то вот другое решение:
#include <string>
#include <iostream>
#include <iomanip>
#include <sstream>

using namespace std;

string s = "123vbn12g12hj321.nb3jk.123-ftfy21tf-1.3e2bjh";

int main(int argc, const char * argv[])
{
    cout << s << endl;

    istringstream is(s);
    double sum = 0.0;
    for(double x;;)
    {
        is >> x;
        if (!is.fail())
        {
            cout << "get " << x << endl;
            sum += x;
            continue;
        }
        if (is.eof()) break;
        is.clear();
        is.ignore(1);
    }
    cout << sum << endl;

}

A: https://ideone.com/QDatJA
#include <cstdio>

int main()
{
  char s[256], *p;
  int x;
  int n;

  fgets(s, sizeof s, stdin);

  // add n after check p to allow last iteration when the number is at the end
  for (p=s; sscanf(p, "%*[^-0-9]%n", &(n=0)), sscanf(p+=n, "%d%n", &x, &(n=0)), *p; p+=n)
    if (n)
      printf("%d ", x);
    else
      ++p; // skip '-'

  return 0;
}


text:
Q: I'm getting an implicit declaration error only when using -std=c99 For some reason, -std=c99 is keeping gcc from seeing the declaration of function wborder_set() (which lives in <curses.h>)
#include <curses.h>
#include <locale.h>

int main(int argc, char* argv[]){
  initscr(); // start ncurses
  cbreak();  // don't wait for lf to getch
  noecho();  // don't copy entered characters
  nonl();    // use /r/l
  clear();   // clear the screen!

  setlocale(LC_CTYPE, "");

  int ySize, xSize;
  getmaxyx(stdscr, ySize, xSize);
  WINDOW *upperWin = newwin(ySize, xSize, 0, 0);

  // magic utf encodings for window border
  wborder_set( upperWin, "\u1234", "\u1234", "\u1234", "\u1234",
           "\u1234", "\u1234", "\u1234", "\u1234" );
  wrefresh(upperWin);
  getch();
  return 0;
}

Compiling with gcc test.c -lncursesw -o cursestest works fine! If, however, I compile with
gcc test.c -std=c99 -lncursesw -o cursestest
it replies,
cursescurses.c: In function 'main':
cursescurses.c:18:7: warning: implicit declaration of function 'wborder_set' [-Wimplicit-function-declaration]
       wborder_set( upperWin, "\u1234", "\u1234", "\u1234", "\u1234",
which leads me to believe that I can't trust that it is properly linking wborder_set.
Why would this happen?

A: Your <curses.h> doesn't seem to include a prototype for the function. The rules changed in C99: using functions without a declaration is not allowed anymore. Before, they would be assumed to return int.
This has nothing to do with linking, but this a question about the compiler expecting a certain return type for a function.

A: Defining _XOPEN_SOURCE_EXTENDED would help, but Linux (like most systems) has pitfalls in the form of extensions which conflict with the standards, and differing interpretations of the standards.  So... for Linux, the universal band-aid for this is to start by defining _GNU_SOURCE (which turns on the appropriate X/Open defines as an afterthought).
If your ncurses configuration includes a reasonably current ncursesw5-config script it will add that -D option.

A: It turns out the problem was that I had included the wrong version of <curses.h>. The function wborder_set implements unicode and needed the unicode/wide char extension of the ncurses library, which I included with #include <ncursesw/curses.h>. With this substitution, the program compiled as expected.