text:
Q: I'm trying to debug a mergesort program that I wrote to sort binary input files FIRST TIME POSTING I'm trying to debug a program that reads an input file, copies its values to an array, sorts the array using mergesort, and then writes that sorted array to an output file. I've reached the point where my makefile will compile the code without any warnings or errors, but will not create an output file for any of the test cases. I am 99% sure that my makefile is set up correctly. So, I figured that I would use gdb to try and gain any more details about the problem but when I set a breakpoint in any of the functions and try to run, it exits with code 01. I suspect this has something to do with main, but I have no idea where to start modifying code without any more details. I also think that think that the error could occur when trying to read the values and store them in an array, or when trying to write to the output file at all. That being said, I've written everything to the best of my ability and I've spent some time here searching for a solution.
The code is being run in an ssh shell, so I don't have access to anything administrative, and I shouldn't need to. The error has to be within my code. The necessary libraries and headers are not shown but are guaranteed to be correct. Any help would be greatly appreciated, as well as any explanation as to why I am doing something wrong as I would like to make as few future mistakes as possible.
int main(int argc, char * * argv)
{
        // argv[1]: name of input file (binary)
        // argv[2]: name of output file (binary)
        if (argc != 3)
        {
                return EXIT_FAILURE;
        }

        int arrsize;

        bool rtv;
        rtv = readData(argv[1], &arr, &arrsize);

        if (rtv == false)
        {
                return EXIT_FAILURE;
        }

        mergeSort(arr, 0, arrsize - 1);

        rtv = writeData(argv[2], arr, arrsize);
        free(arr);

        if (rtv == false)
        {
                return EXIT_FAILURE;
        }
        return EXIT_SUCCESS;
}

_____________________________________________________________________

bool readData(char * filename, int * * arr, int * size)
{

        FILE * filepointer;
        filepointer = fopen(filename, "rb"); // open file for reading binary

        if (filepointer == NULL)
        {
                return false;
        }

        if (fseek(filepointer, 0 , SEEK_END) != 0) // put filepointer at the end of the file
        {
                fclose(filepointer); // check whether failed
                return false;
        }

        int filesize;
        filesize = ftell(filepointer); // get filesize

        if (fseek(filepointer, 0, SEEK_SET) != 0) // bring filepointer back to beginning of file
        {
                fclose(filepointer);
                return false;
        }

        int numint;
        numint = (filesize / sizeof(int)); // find number of integers in array

        int * mergearr  = malloc((sizeof(* mergearr)) * numint); // allocate an array to use for mergesort

        if (mergearr == NULL) // check whether allocation fails
        {
                fclose(filepointer);
                return false;
        }

        int numint2;

        if (fread(&numint2, sizeof(int), 1, filepointer) != numint)
        {
                fclose(filepointer);
                return false;
        }
        else
        {
                fclose(filepointer);
        }

        * arr = mergearr; // update argument for array address

        * size = numint2; // update size of array

        return true;
}

________________________________________________________________

bool writeData(char * filename, const int * arr, int size)
{

    FILE * filepointer;
    filepointer = fopen(filename, "wb");

    if (filepointer == NULL)
    {
            return false;
    }

    if ((fwrite(arr, sizeof(int), size, filepointer) != size))
    {
            fclose(filepointer);
            return false;
    }
    else
    {
            return true;
    }

}

__________________________________________________________________

static void merge(int * arr, int l, int m, int r)
{

    int i;
    int j;
    int k;
    int LeftSize = m - l + 1;
    int RightSize = r - m;

    int * Left = malloc((sizeof(* Left) * LeftSize)); // Array allocation
    int * Right = malloc((sizeof(* Right) * RightSize));;

    for (i = 0; i < LeftSize; i++) // Copying over elements
    {
            Left[i] = arr[l + i];
    }
    for (j = 0; j < RightSize; j++)
    {
            Right[j] = arr[m + 1 + j];
    }

    i = 0; // Reset indices
    j = 0;
    k = l;

    while (i < LeftSize && j < RightSize) // Merge arrays back together
    {
            if (Left[i] <= Right[j])
            {
                    arr[k] = Left[i];
                    i++;
            }
            else
            {
                    arr[k] = Right[j];
                    j++;
            }
            k++;
    }

    while (i < LeftSize) // Copy leftover elements
    {
            arr[k] = Left[i];
            i++;
            k++;
    }

    while (j < RightSize)
    {
            arr[k] = Right[j];
            j++;
            k++;
    }
}

____________________________________________________________________

void mergeSort(int arr[], int l, int r)
{

    if (l < r)
    {
            int m;
            m = l + (r - l) / 2;

            mergeSort(arr, l, m);
            mergeSort(arr, m+l, r);

            merge(arr, l, m, r);
    }
}


text:
Q: parse rss feed while exclude some text i am trying to parse the user names from an rss feed using php, but for some reason its not working correctly here is my code.
$feedDom = new DomDocument();
$feedDom ->load($TURL);
$xPath = new DomXPath($TwitterDom);
$usernames = $xPath->xpath("//author/name']");

echo $usernames;

I looked at the rss feed and here is what i am trying to parse, but I would like to exclude the (jimmy), and only parse the user name.
<author>
      <name>ilovemyname (jimmy)</name>
</author>

A: Like this?
$usernames = substr($usernames, 0, strpos($usernames, ' '));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does Inheritance contradict Dependency Inversion Principle The dependency Inversion principle says that (Head First Java):

*

*Depend upon abstractions. Do not depend upon concrete classes.

What does it mean with respect to inheritance? As a subclass depends on concrete class.
I am asking for a case when say - There is an interface Bird (doesn't have fly method as some birds cant fly), which represents all Non-Flying Birds. So I create a class - NonFlyingBird which implements Bird.
Now I want to make a class for Birds that can fly. As NonFlyingBirds and FlyingBirds have the same attributes I extend the FlyingBirds from NonFlyingBirds and Implement Flyable to give it flying behavior.
Do Doesn't it break the dependency Inversion principle as FlyingBirds is extending from a concrete class NonFlyingBirds?
interface Bird {   // Represents non Flying birds

    void getColor();
    void getHeight();
    ...
 }

class NonFlyingBird implements Bird {
     void getColor();
     void getHeight();
      ...
  }

class FlyingBird extends NonFlyingBird implements Flyable { // Does it break Dependency Inversion principle by extending concrete NonFlyingBird class?

    Flyable fly;
    ...
  }

Note - The only reason I am extending is because the FlyingBird has the same attributes and methods as NonFlyingBird + the flying behaviour. So it kind of makes sense to reuse code by inheritance.

A: Short answer:  No.
Longer answer:  Use strategy pattern.
Classes that depend on the Bird interface can still be handed a FlyingBird or NotFlyingBird instance without knowing the difference.
The interface for Bird is still the same, or in general, should be, if the classes do have a different interface (new methods in FlyingBird that your calling code depends on), then there is a problem.
Perhaps a better way to solve your problem is by using the Strategy Pattern.
Off the cuff example:
public interface Bird {

    void fly();
}

public class BirdImpl implements Bird {

    private FlightStrategy flightStrategy;

    public BirdImpl(FlightStrategy flightStrategy) {

        this.flightStrategy = flightStrategy;
    }

    public void fly() {

        this.flightStrategy.fly();
    }
}

public interface FlightStrategy {

    void fly();
}

public class FlyingBirdFlightStrategy implements FlightStrategy {

    public void fly() {

        System.out.println("Wings flap");
        System.out.println("Wings flap");
        System.out.println("Wings flap");
        System.out.println("Wings flap");
    }
}

public class NonFlyingBirdFlightStrategy implements FlightStrategy {

    public void fly() {

        // do nothing non flying birds can't fly.
    }
}

Then when creating your Bird for use, create the default BirdImpl and pass in the FlightStrategy for the type of bird you want.

A: Yes, your intuition is correct - inheritance introduces non breakable compile-time and run-time dependency between a child and its parent.
Therefore the applications of inheritance is limited: You should only use inheritance to implement an "is" relation, not a "has code to be shared" relation. You should be careful, though: inherit only when an object "is" its subclass during the whole life. Human can safely extend Mammal, but it's risky to define Student as a subclass of a Human. Humans can cease to be Students and you cannot change this in runtime.
class FlyingBird extends NonFlyingBird

This is a heresy! :)
There's a strong movement against template classes like "AbstractBird". Unfortunatelly, a lot of introductory programming books teach this pattern of code sharing. There's nothing inherently wrong with it, but nowadays there are better solutions - Strategy, Bridge. In Java, you can even have poor-man's Traits - default implementations in interfaces.
In my opinion, the Dependency Inversion Principle, when applied to Inheritance translates to "Favour composition over inheritance".

A: Despite I liked an example with strategy from answers there, I will answer too, because I think you are confused a bit about dependency inversion principle.
Dependency inversion principle means
Don't use this, if you don't  really need LinkedList behaviour:
public class A {
    private LinkedList<SomeClass> list;
//...
}

Use that instead:
public class A {
    private List<SomeClass> list; //or even use Collection or Iterable
//...
}

Dependencies are what we use inside our class.
Inheritance
Inheritance is what we call IS-A relationship and it has nothing to do with the principle. If you want to make class A that inherits class B, you need to answer a question: is it true that A is B. If you ask this question, you'll find that expression "FlyingBird is a NonFlyingBird" is a noncense.
Reusing code with inheritance
Think about this: not all birds can fly and not only birds(e.g. flies) can fly.
It may lead us to an idea that we should create interface Flyable as you already done. Then we should rename NonFlyingBird to just SimpleBird, because if some creature is a bird it doesn't mean it can fly. In the end you will get:
class FlyingBird extends SimpleBird implements Flyable {

    void fly() {
        ...
    }
    ...
}

Hope it'll help.


text:
Q: jQuery disable textbox input for type number I have a HTML markup which looks like following:
 <input type="number"  step="0.1" min="0" max="100" value="1" class="form-control breakEvenInput" style="width:150px" />

 <button type="submit" class="btn btn-primary saveBreakEven">Save</button>

As you can see the input is of type "number"... What I was thinking (if it's possible) to do here is to disable the end user so that he/she is not able to input anything into the textbox, but rather enable the user just to have that side scrool up/down arrows that he gets when browser renders the HTML input as type of "number".
I've tried to add "disabled" or "readonly" properties to HTML input but that didn't give me the desired result. When I do it like that then the entire textbox is disabled...
I was thinking that this might be done somehow via jQuery? Can someone help me out ?
P.S. So i'd like to disable the input into the textbox via keyboard, but still leave the up/down arrows in textbox for the user to change the value, so that the user can't enter anything they want , let's say 99999999999 number.. ?

A: One of the things you can do is to prevent the keydown event.

$(function() {

  $('input').on('keydown', function(e) {
    e.preventDefault();
  });

});

<input type="number" step="0.1" min="0" max="100" value="1" class="form-control breakEvenInput" style="width:150px" />

<button type="submit" class="btn btn-primary saveBreakEven">Save</button>

This way you keep the arrows active, but disable keyboard keys.
Inside the event object (e), you can also check what key was pressed (if you want to support backspace or arrows for example).

A: An issue you will have is different browsers support and render type="number" differently.  I would suggest a span element for the number readout (ff you need to have it as an input, I would hide it), and use styled buttons or elements to increase, decrease the number and update the input box.  This will give a uniform user experience across browsers.

0
<button id="add>Up</button><button id="sub">Down</button>

A: $(function() {

    $('input[type=number]').on('keydown', function(e){
    e.preventDefault();
    });
});


text:
Q: Open an Image to the Instagram Story publishing page To clarify: Instagram currently does not support the scheduling of stories (I know there are some hacky ways).
Some Instagram scheduling tools have the feature to schedule stories and notify you when the time to publish has come. These apps then send you a notification on the phone and by clicking it, the Instagram app opens on the story publishing page and the only thing I have to do is to click on the publish button.
I am wondering now, how can I do this on my own?
The idea would be to receive an image lets say on telegram which includes a link which then by clicking opens the IG app and inserts the image.


text:
Q: Applying 'margin: 0px auto' to the body element doesn't work According to this answer, putting display: block; float: none; position: relative; in a selector should ensure that the margin: 0px auto trick to horizontally center an element works. This is my code for attempting to center the body within the html element:
body {
    background-color: lightgray;
    float: left;
    font-family: 'Lato', 'Roboto', 'Arial', 'Verdana', sans-serif;

    margin: 0px auto;
    /* Adding these last 3 doesn't seem to make a difference */
    display: block;
    float: none;
    position: relative;
}

When I specify the pixels manually like 0px 500px, it works out fine. Does anyone know why auto doesn't seem to be working in this case?
edit: Guys, it doesn't work even when I specify the width for the body. https://jsfiddle.net/ozm2x9zx/

A: You have to mention width to make it center.

And also no need to mention px for 0(Zero) values.

A: You missed the 4th point in that answer your referred to:

*The element must have a width that is not auto

Which was then explained in the notes:

Technically, margin: 0 auto does work with an auto width, but the auto width takes precedence over the auto margins, and the auto margins are zeroed out as a result, making it seem as though they "don't work".

So add a width to your body and you will see it working. Ah, but here is the catch: you are applying it to the body, not any element on the page. It works, but you will not see the effect unless you make the color of the html different from the body. Try this:
html {
  background-color: red;
}

body {
  background-color: lightgray;
  float: left;
  font-family: 'Lato', 'Roboto', 'Arial', 'Verdana', sans-serif;
  margin: 0 auto;
  display: block;
  float: none;
  position: relative;
  width: 70%;
}

A: You need to remove float, off of your body element and your container sits in the middle perfectly.
Also, there is no need to attribute the unit type, (px), on a value of zero.
Consider:
  body {
        background-color: lightgray;
        background-image: url('../images/brushed.png');
        background-repeat: repeat;
        font-family: 'Lato', 'Roboto', 'Arial', 'Verdana', sans-serif;
        margin:0;
    }

    div#container {
        background-color: #aaaaaa;
        color: white;
        width: 960px;
        margin: 0 auto;
    }

A: I just remove float:left; from body, and it is centered +
most of the time -> margin:0px auto; will work fine with display:table;

        <title>My Favorite Films</title>

        <link type="text/css" rel="stylesheet" href="css/site.css" />

        <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet" />
        <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" />
        <link href="https://fonts.googleapis.com/css?family=Playfair+Display" rel="stylesheet" />

My Favorite Films

Home

Black Mirror

House of Cards

Inception

Interstellar

Stranger Things

My Favorite Films

By James Ko

Copyright © 2017 James Ko. All rights reserved.


text:
Q: You roll a die until you get a $5$, what is the expected value of the minimum value rolled? I am struggling to work out a simple way to answer this, and a rationale behind this approach using tail sum (as I do not understand):
$$E\left( x\right) =\sum ^{5}_{k=1}P\left( x\geq k\right) =\dfrac {1}{6}\sum ^{5}_{k=1}\left( \sum ^{\infty }_{i=0}\left( \dfrac {k}{6}\right) ^{i}\right)  = \frac{137}{60}.$$
Does this always hold?
$$E\left( x\right)=\sum ^{n}_{k=1}kP\left( x= k\right)  =\sum ^{n}_{k=1}P\left( x\geq k\right)$$
I have never seen this formula, but working through it I understand.
EDIT: I can get the right answer with a long winded method, calculating each probability separately, which I believe the Tails sum speeds up:
This is my long winded approach.
$$E\left( X_{\min }\right) = 5P\left( x= 5\right) +\ldots +1P(x=1)$$
$$=5\left( \dfrac {1}{6}\sum ^{\infty }_{i=0}\left( \dfrac {1}{6}\right) ^{i}\right) +4\left( \dfrac {1}{6}\sum ^{\infty }_{i=1}\left( \dfrac {2}{6}\right) ^{i}- \dfrac {1}{6}\sum ^{\infty }_{i=1}\left( \dfrac {1}{6}\right) ^{i}\right)+\ldots$$ $$+1\left( \dfrac {1}{6}\sum ^{\infty }_{i=1}\left( \dfrac {5}{6}\right) ^{i}- \dfrac {1}{6}\sum ^{\infty }_{i=1}\left( \dfrac {4}{6}\right) ^{i}\right),$$
where $\dfrac {1}{6}$ represents getting a $5$, so the first sum is all the possibilities of getting repeated $6$s and then a $5$, or just rolling a $5$. The next sum is all the possibilities of getting a $4$ or a $6$, then a $5$, minus all the possibilities of just getting a $6$ then a $5$. So it represents all the strings of just $4$s or $6$s before getting a $5$, so all the possibilities of minimum value being a $4$.

A: I have found a different way to think about to this problem for those still a little stuck. Let m = the minimum number found.
E(m) = 1*P(m=1) + 2*P(m=2) + ... + 5*P(m=5)
Notice we do not include the probability that m=6 as we know we have rolled a 5 (this is when the game stops) so we cannot have our smallest number to be 6.
Lets have a look at P(m=1):
This is effectively the event that we get a 1 before we get a 5. Whats more likely, getting a 1 before a 5 or a 5 before a 1? Naturally they are both equally likely so P(m=1) = 0.5
Now lets look at P(m=2). We need two things here. To get a 2 before a 5 and to get a 5 before a 1. I.e we have 2 as our minimum but the game has stopped before we had a chance to change that minimum to 1. We now have 6 possible choices in the race of 1,2 and 5. We could have 512 or 125 or 251 or so on. Think of it as a race between 3 horses, all outcomes equally likely. (in essence we are also "racing horse 4 5 and 6" but we dont care how they perfom in the race just the relative positions of 1 2 and 5)  We have 3 choices for First place, 2 for second and 1 for third. 3! = 6. Of these 6 choices the ONLY way in which m=2 is if we have 251. 1 choice out of 6 thus P(m=2) = 1/6.
Now onto P(m=3) again we are looking at the positions of horses 1,2,3 and 5. With a total of 4! possibilities we must have either 3512 or 3521. P(m=3)=2/4! = 1/12.
P(m=4). we have 5 horses now racing: 1,2,3,4 and 5. with a total of 5!, 120 outcomes and m=4 only occuring on the outcomes: 45xyz. with x,y,z taking any choice in 123. there are 3! choices for xyz thus 3!/5! = 1/20 = P(m=4)
P(m=5). Just look the step above we are looking at the relative positions between horses 1,2,3,4 and 5. This time m=5 if and only if 5 wins the race! So successful outcomes are of the form 5xyzt. with xyzt in 1234. There are 4! ways to arrange horses 1234 thus P(m=5) = 4!/5! = 1/5.
Can you spot a pattern for P(m=i)?
Putting this all in gives E(m) = 1*1/2 + ... + 5*1/5 = 137/60.
:) Oskar

A: I seem to get $\dfrac{137}{60}$, slightly more than $2$, which seems as plausible to me as your similar answer
More precisely: $$1 \times \frac12 + 2 \times \frac16 + 3 \times \frac1{12}+4 \times \frac{1}{20}+5 \times \frac15$$
I think you are saying that if only $6$s are thrown before the first $5$ then the minimum is $6$ to calculate
$$1 \times \frac12 + 2 \times \frac16 + 3 \times \frac1{12}+4 \times \frac{1}{20}+5 \times \frac16+6 \times \frac1{30}$$
I am saying the minimum is $5$, since a $5$ is thrown to stop the game.  This is what is causing the difference between $\frac{139}{60}$ and $\frac{137}{60}$

A: I wanted to point out that we don't need infinite series or fancy formulas to solve this problem.
Any infinite sequence of die rolls yields a permutation of $\{1,2,3,4,5,6\}$ by simply retaining all of the first appearances of each number. By symmetry, all $6!$ permutations are equally likely. Therefore to calculate the desired expectation, one can simply enumerate the $6!$ permutations, find the minimum values before the $5$ in each case, and average the results.

A: The formula
$$E\left( x\right) =\sum ^{n}_{k=1}P\left( x\geq k\right)$$
is a special case of a fairly well-known more general result:
\begin{align}
E(X) &=\int_0^\infty P(X>x)\ dx
\end{align}
for any random variable $\ X\ $ which assumes only non-negative values.  For a non-negative integer-valued random variable, this becomes
\begin{align}
E(X) &=\sum_{k=0}^\infty\int_k^{k+1} P(X>x)\ dx\\
&= \sum_{k=0}^\infty\int_k^{k+1} P(X>k)\ dx\ \ \text{ because }P(X>x)= P(X>k)\\
&\hspace{10.2em}\text{ for } k\le x < k+1\\
&= \sum_{k=0}^\infty P(X>k)\\
&= \sum_{k=0}^\infty P(X\ge k+1)\\
&= \sum_{k=1}^\infty P(X\ge k)\  ,
\end{align}
and for the case being considered here, the sum can be terminated at $\ k=5\ $, because $\ P(k\ge k) = 0\ $ for $\ k\ge 6\ $.
The identity
$$
\sum_{k=1}^5 P(X\ge k) = \frac{1}{6}\sum_{k=1}^5\sum_{i=0}^\infty \left(\frac{k}{6}\right)^i
$$
comes from the decomposition
\begin{align}
\left\{X\ge k\right\}&=\bigcup_{i=1}^\infty\left\{k\le T_j\le4\text{ or } T_j=6 \text{ for } 1\le j<i\right\} \cap \left\{T_i=5\right\}\ ,
\end{align}
giving
\begin{align}
\sum_{k=1}^5 P(X\ge k)&=\sum_{k=1}^5\sum_{i=0}^\infty \left(\frac{6-k}{6}\right)^i\frac{1}{6}\\
&= \sum_{k'=1}^5 \sum_{i=0}^\infty \left(\frac{k'}{6}\right)^i\frac{1}{6}\ ,
\end{align}
where the final sum is obtained by replacing the index $\ k\ $ in the previous one with $\ k'=6-k\ $.


text:
Q: How to "seq" plugin settings in a multi-project sbt build I am converting a single-project build.sbt to a multi-project build.sbt, which is always a PITA. There is this obscure syntax to make plugin settings available. E.g. before
seq(appbundle.settings: _*)

How do I do this with sub-projects. E.g.
lazy val views = Project(
  id        = "views",
  base      = file("views"),
  dependencies = Seq(core),
  settings  = commonSettings ++ Seq(
    seq(appbundle.settings: _*),    // ???
    name        := "views",
    description := ...
  )
)

This just gives me an error
 found   : Seq[sbt.Def.SettingsDefinition]
 required: Seq[sbt.Def.Setting[_]]
  settings  = commonSettings ++ Seq(
                             ^

A: Add them using ++ to the overall settings
lazy val views = Project(
  id        = "views",
  base      = file("views"),
  dependencies = Seq(core),
  settings  = commonSettings ++ appbundle.settings ++ Seq(
    name        := "views",
    description := ...
  )
)


text:
Q: Does Mathematica have an implementation of the Poisson binomial distribution? I need to work out the probability of having $k$ successful trials out of a total of $n$ when success probabilities are heterogeneous. This calculation relates to the Poisson Binomial Distribution. Does Mathematica, or perhaps the Mathstatica add-on, have an implementation for that?

A: From what it appears you require, the following should suffice:
pb = Fold[ListConvolve[##, {1, -1}, 0] &, Transpose[{1 - #, #}]] &;

It should provide more accurate results for reasonably sized probability vectors.
As an example, a vector of 100 probabilities:
SeedRandom@1234
testps = RandomReal[{0, 1}, 100];

Timings:
r1 = pb@testps; // AbsoluteTiming // First

r2 = Re@PDF[PoissonBinomialDistribution[testps], Range[0, Length@testps]]; // AbsoluteTiming // First

0.0008377
0.137304

Comparing accuracy with a random sample of the PMFs (pb left, PoissonBinomialDistribution right. The correctness of pb was verified for full PMF):
With[{p = RandomSample[Range@100, 10]},
  Transpose[{r1[[p]], r2[[p]]}]] // TableForm

You can of course use the same to generate generic results for n probabilities,  à la Carl Woll's answer, and then replace probabilities as desired:
np = 18;

r1 = Table[p[np, x], {x, 0, np}]; // AbsoluteTiming // First

r2 = pb[Array[p, np]]; // AbsoluteTiming // First

%%/% // Round

And @@ MapThread[FullSimplify[#1 == #2] &, {r1, r2}]

504.622
0.0738808
6830
True

Same results, but ~1/7000th the time taken. I tried with np of 20, gave up waiting, probably 1/20000th the time or so...

A: Another possibility is:
p[n_, k_] := SeriesCoefficient[Product[1 - (1 - ϵ) p[i], {i, n}], {ϵ, 0, k}]

Reproducing gwr's results:
Table[p[3, i], {i, 0, 3}] //Simplify //Column //TeXForm

$\begin{array}{l}
 -(p(1)-1) (p(2)-1) (p(3)-1) \\
 -2 p(3) p(2)+p(2)+p(3)+p(1) (-2 p(3)+p(2) (3 p(3)-2)+1) \\
 p(2) p(3)+p(1) (-3 p(3) p(2)+p(2)+p(3)) \\
 p(1) p(2) p(3) \\
\end{array}$

A: I have answered this question using a full implementation of the Poisson Binomial.

A: Mathematica does not know about the PoissonBinomialDistribution, but you can use the formula given for the PDF on Wikipedia:
PoissonBinomialDistribution[ plist : { __?NumericQ } ] := With[
    {
      n = Length @ plist,
      c = Exp[(2 I \[Pi])/(Length@plist + 1)]
    }
    ,
    ProbabilityDistribution[
        Re[ 1/(n + 1) Sum[c^(-l k) Product[1 + (c^l - 1) plist[[m]] , {m, 1, n }], {l, 0, n}] ]
        ,
        {k, 0, n, 1}
    ]
 ] /; AllTrue[ plist, 0 <= # <= 1& ]

Now we may model a quality control where fault type 1 has a prob of 4% and fault types 2 and 3 have a prob of 7%:
dist = PoissonBinomialDistribution[ {0.04, 0.07, 0.07} ];

With this we find the probability for 3 faults:
Probability[ k == 3, k \[Distributed] dist ]// PercentForm

0.0196 %

Update
Another possibility is to work with TransformedDistribution. Doing so also allows for symbolic evaluation:
PoissonBinomialDistribution::fargs = "Probabilities must be between zero and one";
PoissonBinomialDistribution[ plist : {__?NumericQ | __Symbol } ] := With[
    {
        xList = Table[ Unique["x"], Length @ plist ]
    }
    ,
    If[ Not @ AllTrue[ plist, 0 <= # <= 1 &],
        Return[ Message[PoissonBinomialDistribution::fargs]; $Failed ]
    ];
    TransformedDistribution[
        Total @ xList,
        Thread[ xList \[Distributed] Map[ BernoulliDistribution, plist] ]
    ]
]

PDF[ PoissonBinomialDistribution[{p1, p2, p3}], x ]


text:
Q: How to create a short circuit evaluation in bison using mid-rules action? I was assigned to write a calculator that, among some other things, also supports variables definition and assignments, boolean expressions and decrement/increment operations.
My calculator should also support the conditional (ternary) operation ? :, the same kind some programming languages support, which used as follows:
condition ? value_if_true : value_if_false ;

Or as it defined in my grammar rules:
bool_expression ? int_expression : int_expression ;

The problem is, it has to be a short circuit evaluation, meaning that if bool_expression evaluates to true, only the first int_expression should be evaluated, and otherwise, if bool_expression evaluates to false, then only the second int_expression should be evaluated.
I was told to use bison's Action in mid-rule functionality, but I fail to see how could that be of help.
I also looked around online and found this to be the closest thing to what I'm trying to accomplish, but unfortunately, the answer there is not quite what I'm looking for. The answer there indeed describes what should be done, but does not state specifically how to do it (global flag is out of the question, you'll understand why when you'll see the code).
Here's a very small part from what I have so far:
%{
    #include<stdio.h>
    #include<iostream>
    #include <string>
    #include <map>

    using namespace std;

    map<string, int> symbolTable;

    int yylex();
    void yyerror(const char*);

%}

%union{
    int     int_val;
    char*   string_val;
    bool b;
}

%token <int_val> T_NUMBER
%token <string_val> T_VAR
%type  <int_val> expr
%type  <b>bool_expression
%nonassoc ':'
%nonassoc T_EQUALS
%left '+' '-'
%left '*' '/'
%left UMINUS
%left '$' '~'

%%

commands:
        /* eps rule */      {cout<<"create commands"<<endl;}
        | commands command  {cout<<"add command"<<endl;};

command:    expr '\n'       {cout<<"Expression value: "<<$1<<endl;}
    |   T_VAR '=' expr '\n' {cout<<"Assignment: "<<$1<<"="<<$3<<endl; symbolTable[$1] = $3;}
    |   bool_expression '\n'    {$1 ? cout<<"true"<<endl : cout<<"false"<<endl;}
    ;

expr:
        T_NUMBER        {$$ = $1;}
    |   T_VAR           {$$ = symbolTable[$1];}
    |   expr '+' expr       {$$ = $1 + $3;}
    |   expr '-' expr       {$$ = $1 - $3;}
    |   expr '*' expr       {$$ = $1 * $3;}
    |   expr '/' expr       {if ($3 == 0) {yyerror ("Division by zero!"); return 1;} $$ = $1 / $3;}
    |   '$' T_VAR       {$$ = ++symbolTable[$2]; }
    |   '~' T_VAR       {$$ = --symbolTable[$2]; }
    |   '-' expr %prec UMINUS   {$$=-$2;}
    |   bool_expression '?'     {/* this is a mid-rule; what should go here... */}
        expr ':' expr       {/* in order to evaluates only one of these two, depending on bool_expression */}
    ;

bool_expression:  expr T_EQUALS expr        {$$=($1==$3);}

%%

void yyerror(const char* errorInfo){
    cout<<errorInfo<<endl;
}

int main(){
    yyparse();
}

the '$' operator you see there has the same meaning as the operator ++ in C, and the '~' operator has the same meaning as --.
Back to my problem: the above is only the relevant code, I have a lot more rules I've omitted for the sake of readability. This also means that using some global flag is not my best choice here, since it will require its inspection in every rule in my file.
Now, consider the input:
a=5
1==1 ? $a : $a
And the naive approach of defining the above rule as:
|   bool_expression '?' expr ':' expr {$1 ? $$=$3 : $$=$5 ;}

this code results in 'a' having the value 7 instead of 6.
So how can 'action in mid-rule' be used here to prevent the first expr to ever be shifted/reduced if bool_expression is false, and prevent the second expr to be shifted/reduced if bool_expression is true?

A: You need a global flag eval which is set (true) while parsing code that should be evaluated.  While it is false, the parser should just skip over things and not actually evaluate anything.  So your rule for assignment becomes:
command: T_VAR '=' expr '\n' {
    if (eval) {
        cout << "Assignment: " << $1 << "=" << $3 << endl;
        symbolTable[$1] = $3; } }

Similarly for all other rules that might have side effects (for those that have no side effects, you can run unconditionally and generate a value that will be ignored, or you can similarly guard it.)
Then, your conditional rule becomes:
expr: expr { if ($$ = eval) eval = $1; } '?'
      expr { if ($2) eval = !eval; } ':'
      expr { if (eval = $2) $$ = $1 ? $4 : $7; }

This saves the eval flag in the result of the first inline action, restores it in the final action and, if it was set, sets it for the expression that should be evaluated and not for the other.
One big problem with this is that error recovery becomes much harder, since you need to figure out when/where to restore the eval flag.
edit
With what you have abouve, $ and ~ don't actually do anything.  If you want them to be equivalent to ++ and --, you need:
expr: `$` T_VAR { $$ = eval ? symbolTable[$2]++ : 0; }
    | `~` T_VAR { $$ = eval ? symbolTable[$2]-- : 0; }


text:
Q: Create new django project in pycharm: "Remote path not provided" After creating a python docker container, I want to use it as my interpreter instead of Virtualenv. If I leave it empty it says "Remote path not provided". After typing something you see the warning on the screenshot.
Screenshot:

How can I fix it?

A: You can't fix it.  It is Jetsbrains domain to fix it.  It's a longstanding bug in Pycharm:
https://youtrack.jetbrains.com/issue/PY-28097
https://youtrack.jetbrains.com/issue/PY-31823
https://youtrack.jetbrains.com/issue/PY-33662
https://youtrack.jetbrains.com/issue/PY-24427
You're expected to work around it.

*

*by creating a virtualenv, even though you don't want it, then connecting the docker using other screens after the project is created.

*by creating the project by just "open"ing the folder, then attaching the docker via the project dialogs.

One might wonder how, given that you can't use it, the option ever made it into the Create Project dialog, and why it's still there, but since we all work in software, we can surmise the answers for ourselves :-)


text:
Q: How do to pass tag of UIView pressed to method selector? I have 11 UIView on each has been set a Gesture Recognizer. This UIView are within mutable array and each have got a tag. How do to pass tag of UIView pressed to method selector?
viewIcone.userInteractionEnabled = YES;
viewIcone.tag = index;

UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self    action:@selector(touchUp:)];
tap.delegate = self;
[viewIcone addGestureRecognizer:tap];
[self.arrayMutabile insertObject:viewIcone atIndex:index];

[self addSubview:viewIcone];

The implementation of method selector is:
-(void) touchUp: (UITapGestureRecognizer *) gestureRecognizer{

   NSInteger tag = [self.arrayMutabile indexOfObject:self.viewIcone];
   NSLog(@"the tag is %d", tag);
}

I always leave 10. Where is the wrong?
Thanks in advance

A: The UITapGestureRecognizer has a view property which it inherits from it's parent:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIGestureRecognizer_Class/Reference/Reference.html#//apple_ref/occ/cl/UIGestureRecognizer
The view the gesture recognizer is attached to. (read-only)

@property(nonatomic, readonly) UIView *view
Discussion
You attach (or add) a gesture recognizer to a UIView object using the addGestureRecognizer: method.

Availability
Available in iOS 3.2 and later.
Declared In
UIGestureRecognizer.h

This will be the view that was tapped and you can retrieve the tag from there.


text:
Q: How to write a unit test for a DefaultMultipartHttpServletRequest controller method with MockMvc? code like this:
@RequestMapping(value = "/upload/{resource}",method=RequestMethod.POST)
@ResponseBody
public Object uploadfileUpload(@PathVariable("resource") String resource,DefaultMultipartHttpServletRequest request,HttpServletResponse resp,MultipartFile file) throws IOException {
    ......
}

in the code:
this.mockMvc.perform(mockMultipartHttpServletRequestBuilder)

only can post a MultipartHttpServletRequest,because mockMultipartHttpServletRequestBuilder  implements MultipartHttpServletRequest.  MultipartHttpServletRequest is a interface.
How can I create a DefaultMultipartHttpServletRequest  class object an then in the mockMvc post the request to complete my unit test?

A: @Test
public void testUploadARA3() throws Exception {
    FileInputStream file = new FileInputStream(
            "C:/test_42873.xlsm");
    MockMultipartFile multipartFile = new MockMultipartFile(
            "test_42873.xlsm", file);
    MockMultipartHttpServletRequestBuilder mockMultipartHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload(
            "/upload/{resource}", "ARA").accept(MediaType.ALL);
    mockMultipartHttpServletRequestBuilder.file(multipartFile);
    //mockMultipartHttpServletRequestBuilder.content("whatever");

    MockHttpServletRequest request;
    MvcResult response =   this.mockMvc.perform(mockMultipartHttpServletRequestBuilder).andDo(print())
            .andExpect(status().isOk()).andReturn();
    System.out.println(response.getResponse().getContentAsString());

}

my test code doesn't enter uploadfileUpload methord.


text:
Q: ¿Se puede transformar esta fecha por PHP o MySQL? tengo la siguiente fecha: Sat, 30 May 2020 07:25:30 +0000
¿Se puede transformar usando PHP o MySQL al siguiente formato?
Como esta:
Sat, 30 May 2020 07:25:30 +0000
Como debería estar:
2020-05-30 07:25:30
Gracias.

A: En PHP podrías primero leer el string inicial para convertirlo a tipo fecha:
$fecha = date_create_from_format('D, d M Y h:i:s O', 'Sat, 30 May 2020 07:25:30 +0000');
y luego:
$fechaFormateada = date ( 'Y-m-d h:i:s', date_timestamp_get($fecha))
En el manual de PHP están todos los formatos posibles: https://www.php.net/manual/es/datetime.createfromformat.php


text:
Q: Visual Studio Express 2012 debug mode doesn't work I have a project in Visual Studio that I have been working on for a while, and I have used the debugger extensively. Recently I changed some settings and I have lost the ability to stop the program and step through code. I can't figure out what I had changed that might have affected this.
If I put a breakpoint in my code and try to have the program stop there, it doesn't. The break point shows up white with a red outline. If I hover the mouse over it, it says
"The breakpoint will not currently be hit. No executable code of the debugger's target code type is associated with this line. Possible causes include: conditional compilation, compiler optimizations, or the target architecture of this line is not supported by the current debugger code type."
I know for a fact that the program executes the code where the breakpoint is because I put the breakpoint in the beginning of the InitializeComponent method. The program displays the window fine, but does not stop at the breakpoint. Yes, I am running in debug mode.
It seems as though there is a disconnect between the compiled code and the source code displayed. Does anyone know what that would be, or know which compiler settings I should check to re-enable debugging?
Here are the compiler options:

/GS /analyze- /W3 /Zc:wchar_t
  /I"D:\dev\libcurl-7.19.3-win32-ssl-msvc\include" /Zi /Od /sdl
  /Fd"Debug\vc110.pdb" /fp:precise /D "WIN32" /D "_DEBUG" /D "_UNICODE"
  /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /Oy- /clr
  /FU"C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework.NETFramework\v4.5\mscorlib.dll"
  /FU"C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework.NETFramework\v4.5\System.Data.dll"
  /FU"C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework.NETFramework\v4.5\System.dll"
  /FU"C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework.NETFramework\v4.5\System.Drawing.dll"
  /FU"C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework.NETFramework\v4.5\System.Windows.Forms.DataVisualization.dll"
  /FU"C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework.NETFramework\v4.5\System.Windows.Forms.dll"
  /FU"C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework.NETFramework\v4.5\System.Xml.dll" /MDd
  /Fa"Debug\" /EHa /nologo /Fo"Debug\" /Fp"Debug\Prog.pch"

The linker options are:

/OUT:"D:\dev\Prog\Debug\Prog.exe" /MANIFEST /NXCOMPAT
  /PDB:"D:\dev\Prog\Debug\Prog.pdb" /DYNAMICBASE "curllib.lib"
  "winmm.lib" "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
  "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib" "oleaut32.lib"
  "uuid.lib" "odbc32.lib" "odbccp32.lib" /FIXED:NO /DEBUG /MACHINE:X86
  /ENTRY:"Main" /INCREMENTAL /PGD:"D:\dev\Prog\Debug\Prog.pgd"
  /SUBSYSTEM:WINDOWS /MANIFESTUAC:"level='asInvoker' uiAccess='false'"
  /ManifestFile:"Debug\Prog.exe.intermediate.manifest"
  /ERRORREPORT:PROMPT /NOLOGO
  /LIBPATH:"D:\dev\libcurl-7.19.3-win32-ssl-msvc\lib\Debug"
  /ASSEMBLYDEBUG /TLBID:1

A: Not pretend to be a full answer, but
here are some thoughts:

*

*Make a backup copy of your project (to prevent further damage)

*Delete all compiled binaries and object files: whole Debug folder and maybe something else. Leave just source files, project files and solution files (and assets, forms, databases etc. if you use it). It is also good idea to remove other build folders, e.g. Release.

*Rebuild project

*Make sure that debugger starts project that you expect: right click on a project in Solution Explorer and choose Set as StartUp project

*Make sure that debugger starts binary that you expect: Project Properties - Debugging - Command

*Close all files opened in VS. Reopen source file with breakpoint  by clicking in Solution Explorer. Make sure that your source file with breakpoint is the same that used during compilation: go to source folder and open it by double click. Compare path to file opened in editor and file in source folder. Also make sure that you saving file before compilation.

*Try start debugging using Step Into. Then click Show next statement. If it will not step into main() something really broken ;(

*If nothing helps, just create new project, copy your source files in its folder and add them recursively to your new project.

How to prevent it in future:
To prevent time loss, code loss and frustration in such situations, programmers use Version control systems. They allow to save your coding results incrementally, in a way you can quickly compare any two steps, observe what was changed, and roll back if needed.
Most popular systems are: Subversion (SVN), Git, Mercurial (Hg). All thee can be integrated to Visual Studio.
Love your code and never loose/break your work results!
Hope it helps. Happy coding! =)

A: I had a similar problem, it was resolved by setting the linker option "Debugging/Generate Debug Info" to "Yes(/DEBUG)".
(Although I see you already have this set in your linker options...)

A: I am new to Visual Studio and C++,hope support a clue for you.My expression is poor,so I choose use code to show my suffer.
#include <stdio.h>
#include <iostream>
class Circle
{
public:
    int x;
    Circle() {
        x = 2;
    }
};
int main() {
    Circle circle;
    printf("%p\n", &circle);
    printf("yyy\n");
    system("pause");
    return 0;
}

this is a very simple example.However if you put a break pointer in main(){}(any line before system("pause")),then debug it.As you said before,it will warn you

The breakpoint will not currently be hit.No executable code of the debugger's target code type is associated with this line.
  Possible causes include:conditional compilation,compiler optimizations,of the target architecture of this line is not supported by the current debugger code type.

However,if you put class Circle in a .h ,it will allow you debug main().The code as below:
Header.h
class Circle
{
public:
    int x;

    Circle() {
        x = 1;
    }
};

Source.cpp
#include <stdio.h>
#include <iostream>
#include "Header.h"
int main() {
    Circle circle;
    printf("%p\n", &circle);
    printf("yyy\n");
    system("pause");
    return 0;
}

It's contructor make a trick.

A: This behavior is possible when compiler does automatic optimizations.
You can try disabling Compiler optimization and rerun.
Select Project Properties -> C/C++ -> Optimization.In Optimization, choose option Disabled (/Old).


text:
Q: Stored Procedure Update Single row based on condition I am trying to create a stored procedure in SQL Server that will essentially update a table given a condition.
Let's say I have a table with Orders

Order ID
Product ID
Quantity

1000
BEA10
2

1000
RAN25
5

1001
RAN50
3

1001
RAN25
1

1001
RAN60
4

1002
BEA10
1

A table we want to insert into let's call this InsertOrder Table

ID
Code
Order ID

1
ABC1
NULL

2
ABC2
NULL

3
ABC3
NULL

4
ABC4
NULL

5
ABC5
NULL

6
ABC6
NULL

What I am trying to do is look through the Orders table where the Product ID = 'BEA10' and update a single row in the InsertOrder table and set it to the Order ID where we found the Product ID of 'BEA10' as long as that Order ID in the InsertOrder info table is NULL
I guess that would mean that if we run the stored proc again it should ignore already inserted Order ID's.
I am fairly new to SQL so I tried to build up some form of code but it seems way off
ALTER PROCEDURE [dbo].[InsertOrder]

AS

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

DECLARE @ORDERS_PRODUCTID nvarchar(50);
DECLARE @ORDERS_ORDERID int;

SELECT @ORDERS_PRODUCTID = ProductID from ORDERS
SELECT @ORDERS_ORDERID = OrderID from ORDERS

IF(@ORDERS_PRODUCTID = 'BEA10' and @ORDERS_ORDERID not in (SELECT OrderID from InsertOrder))

BEGIN

    UPDATE InsertOrder SET OrderID = @ORDERS_ORDERID where OrderID is null

END
GO

A: hope it works
DECLARE @ORDERS_PRODUCTID nvarchar(50);
DECLARE @ORDERS_ORDERID int;

SET @ORDERS_ORDERID = (SELECT OrderID
                        FROM ORDERS O
                        WHERE ProductID='BEA10'
                            AND NOT EXISTS (SELECT 1 FROM InsertOrder WHERE OrderID=O.OrderID));

UPDATE InsertOrder
SET OrderID = @ORDERS_ORDERID
WHERE Code=(SELECT TOP 1 Code FROM InsertOrder WHERE OrderID is null);


text:
Q: Atomikos error prepared transaction "transaction id" with identifier does not exist I have spring boot app with Atomikos as transaction manager and I see this log:

ERROR:  prepared transaction with identifier "1096044365_MTcyLjE3LjAuMy50bTAwNDAyMDAwMDE=_MTcyLjE3LjAuMy50bTQwMg==" does not exist

getting printed continuously.
After reading on Atomikos docs I understood that Atomikos has some crash recovery mechanism and I followed this http://fogbugz.atomikos.com/default4343.html?community.6.1918.14 but it didn't solve my issue.
My question is: why does Atomikos attempt to clean up a tx forever? When there's no chance of getting it to commit state.
Below is the stack trace:

org.postgresql.xa.PGXAException: Error rolling back prepared transaction
      at org.postgresql.xa.PGXAConnection.rollback(PGXAConnection.java:419) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      at com.atomikos.datasource.xa.XAResourceTransaction.rollback(XAResourceTransaction.java:636) ~[transactions-jta-3.9.3.jar!/:na]
      at com.atomikos.icatch.imp.RollbackMessage.send(RollbackMessage.java:70) [transactions-3.9.3.jar!/:na]
      at com.atomikos.icatch.imp.PropagationMessage.submit(PropagationMessage.java:83) [transactions-3.9.3.jar!/:na]
      at com.atomikos.icatch.imp.Propagator$PropagatorThread.run(Propagator.java:79) [transactions-3.9.3.jar!/:na]
      at com.atomikos.icatch.imp.Propagator.submitPropagationMessage(Propagator.java:58) [transactions-3.9.3.jar!/:na]
      at com.atomikos.icatch.imp.HeurHazardStateHandler.onTimeout(HeurHazardStateHandler.java:135) [transactions-3.9.3.jar!/:na]
      at com.atomikos.icatch.imp.CoordinatorImp.alarm(CoordinatorImp.java:933) [transactions-3.9.3.jar!/:na]
      at com.atomikos.timing.PooledAlarmTimer.notifyListeners(PooledAlarmTimer.java:112) [atomikos-util-3.9.3.jar!/:na]
      at com.atomikos.timing.PooledAlarmTimer.run(PooledAlarmTimer.java:99) [atomikos-util-3.9.3.jar!/:na]
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_151]
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_151]
      at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]
  Caused by: org.postgresql.util.PSQLException: ERROR: prepared transaction with identifier "1096044365_MTcyLjE3LjAuMy50bTAwNDAyMDAwMDE=_MTcyLjE3LjAuMy50bTQwMg==" does not exist
      at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2103) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1836) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:512) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:302) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      at org.postgresql.xa.PGXAConnection.rollback(PGXAConnection.java:409) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      ... 12 common frames omitted

How to stop this retry mechanism
This is happening again after updating to 4.0.6

2018-01-22 20:42:52.247 ERROR [RequestId:] 1 --- [    Atomikos:51] c.a.datasource.xa.XAResourceTransaction  : Heuristic termination of XAResourceTransaction: 3137322E31372E302E342E746D313531363637303131363034343030383435:3137322E31372E302E342E746D383435 with state HEUR_HAZARD
  2018-01-22 20:42:52.247 ERROR [RequestId:] 1 --- [    Atomikos:51] com.atomikos.icatch.imp.CoordinatorImp   : Local heuristic termination of coordinator 172.17.0.4.tm151667011604400845 with state HEUR_HAZARD
  2018-01-22 20:42:52.247 ERROR [RequestId:] 1 --- [    Atomikos:51] com.atomikos.publish.EventPublisher      : Transaction 172.17.0.4.tm151667011604400845 corrupted - check https://www.atomikos.com/Documentation/HowToHandleHeuristics to learn more
  2018-01-22 20:42:52.420  WARN [RequestId:] 1 --- [    Atomikos:51] c.a.datasource.xa.XAResourceTransaction  : XA resource 'postgres': rollback for XID '3137322E31372E302E342E746D313531363637303131363034343030383435:3137322E31372E302E342E746D383435' raised -3: the XA resource detected an internal error
org.postgresql.xa.PGXAException: Error rolling back prepared transaction
      at org.postgresql.xa.PGXAConnection.rollback(PGXAConnection.java:419) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      at com.atomikos.datasource.xa.XAResourceTransaction.rollback(XAResourceTransaction.java:460) ~[transactions-jta-4.0.6.jar!/:na]
      at com.atomikos.icatch.imp.RollbackMessage.send(RollbackMessage.java:47) [transactions-4.0.6.jar!/:na]
      at com.atomikos.icatch.imp.RollbackMessage.send(RollbackMessage.java:20) [transactions-4.0.6.jar!/:na]
      at com.atomikos.icatch.imp.PropagationMessage.submit(PropagationMessage.java:67) [transactions-4.0.6.jar!/:na]
      at com.atomikos.icatch.imp.Propagator$PropagatorThread.run(Propagator.java:63) [transactions-4.0.6.jar!/:na]
      at com.atomikos.icatch.imp.Propagator.submitPropagationMessage(Propagator.java:42) [transactions-4.0.6.jar!/:na]
      at com.atomikos.icatch.imp.HeurHazardStateHandler.onTimeout(HeurHazardStateHandler.java:75) [transactions-4.0.6.jar!/:na]
      at com.atomikos.icatch.imp.CoordinatorImp.alarm(CoordinatorImp.java:650) [transactions-4.0.6.jar!/:na]
      at com.atomikos.timing.PooledAlarmTimer.notifyListeners(PooledAlarmTimer.java:95) [atomikos-util-4.0.6.jar!/:na]
      at com.atomikos.timing.PooledAlarmTimer.run(PooledAlarmTimer.java:82) [atomikos-util-4.0.6.jar!/:na]
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_151]
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_151]
      at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]
  Caused by: org.postgresql.util.PSQLException: ERROR: prepared transaction with identifier "1096044365_MTcyLjE3LjAuNC50bTE1MTY2NzAxMTYwNDQwMDg0NQ==_MTcyLjE3LjAuNC50bTg0NQ==" does not exist
      at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2103) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1836) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:512) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:302) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      at org.postgresql.xa.PGXAConnection.rollback(PGXAConnection.java:409) ~[postgresql-9.1-901-1.jdbc4.jar!/:na]
      ... 13 common frames omitted

A: This looks like a bug that has been fixed in TransactionsEssentials 4.0.6

A: After digging into Atomikos source code and going through the stack traces.
Below is the change I made(in Atomikos source code) to alarm method in CoordinatorImp.java and this solved my issue.
public void alarm ( AlarmTimer timer )
{
   try {
        boolean isHeuristic = stateHandler_ instanceof
          HeurHazardStateHandler
|| stateHandler_ instanceof HeurAbortedStateHandler
                                  || stateHandler_ instanceof HeurCommittedStateHandler || stateHandler_ instanceof HeurMixedStateHandler;
    if (!(isHeuristic)) {
     stateHandler_.onTimeout ();
    }
    } catch ( Exception e ) {
       LOGGER.logWarning( "Exception on timeout of coordinator " + root_ , e );
    }
   }


text:
Q: How to create a video from sequence images Android Java programmatically I want to create a video from sequence of images, the images are of same size and I don't want to add any audio file to it so that's going to not hard.
What I need to do for that please explain, what line of code should I need to use for this, or if you have the sample code for it?

A: I suggest use ffmpeg. https://github.com/bramp/ffmpeg-cli-wrapper
This is a  wapper library for java.


text:
Q: k3s ingress to my app's service routing using daemonset not working I have k3s cluster working pretty well with Grafana monitoring and traefik/klipper-lb. However my own app Ingress does not work.
ingress.yaml
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-esp
  namespace: myapp
spec:
  rules:
  - host: test-esp.nip.io
    http:
      paths:
      - path: /
        backend:
          serviceName: test-esp
          servicePort: http

service.yaml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: test-esp
  name: test-esp
  namespace: myapp
spec:
  ports:
  - name: http
    port: 22000
    targetPort: 22000
  selector:
    app: test-esp

daemonset.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
  labels:
    app: test-esp
  name: test-esp
  namespace: myapp
spec:
  selector:
    matchLabels:
      app: test-esp
  template:
    metadata:
      labels:
        app: test-esp
    spec:
      tolerations:
      - key: node-role.kubernetes.io/master
        effect: NoSchedule
      containers:
      - name: test-esp
        image: <gitlab image pull url>
        envFrom:
        - configMapRef:
            name: test-esp-config
        ports:
        - containerPort: 22000
        command: ["/home/scripts/entrypoint.sh"]
        args: ["1"]
        imagePullPolicy: Always
        resources: {}

** 3 Nodes in K3s have DaemonSet Pods running **
> kubectl get po -n myapp
NAME                    READY   STATUS    RESTARTS   AGE
test-esp-9cwzp   1/1     Running   0          4m3s
test-esp-qjk5n   1/1     Running   0          4m3s
test-esp-j8nnk   1/1     Running   0          4m3s

** curl on individual nodes work **
masternode-1> curl -XGET http://masterip:22000
<long html page>

** curl from ingress times out **
mylocal> curl -XGET http://test-esp.nip.io
gateway timeout

** ping/telnet to test-esp.nip.io finds the ip works well **
Any experts out there, is this something do with iptables ?


text:
Q: How to support multiple Spring Security authentication providers in a single application and switch between them In my Java 11, Spring Boot 2.7.3, Maven application, I am using Spring Security in order to authenticate my users. To do this, I included the following dependency in my pom.xml file:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>2.7.3</version>
</dependency>

And then coded the following security configuration class:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
@Configuration
public class SecurityConfiguration {

    @Bean
    public AuthenticationProvider authenticationProvider() {
        return new DocumentumAuthenticationProvider();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/content/login")
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/content/logout")
                .logoutSuccessUrl("/content/logout")
                .permitAll();
        return http.build();
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().antMatchers("**/content/css/**" ,"/content/js/**" ,"/content/images/**" ,"/error/**");
    }

    @Bean
    public BCryptPasswordEncoder encodePWD() {
        return new BCryptPasswordEncoder();
    }
}

Note that my custom authentication provider, DocumentumAuthenticationProvider, extends AbstractUserDetailsAuthenticationProvider. The user is prompted for credentials, which are then authenticated against a Documentum repository.
The above approach works fine.
Next, I wanted to implement SSO against Azure AD, so I removed the above security configuration class and custom authentication provider from the code set, and replaced the above pom.xml dependency with the following entries:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
        <version>2.7.3</version>
    </dependency>
    <dependency>
        <groupId>com.azure.spring</groupId>
        <artifactId>spring-cloud-azure-starter-active-directory</artifactId>
    </dependency>

I then added the following entries to my application.properties file, using values from a new application registration that I configured after logging into my Azure AD portal:
spring.cloud.azure.active-directory.enabled=true
spring.cloud.azure.active-directory.profile.tenant-id=xxxxxxxxxxxx
spring.cloud.azure.active-directory.credential.client-id=yyyyyyyyyyyy
spring.cloud.azure.active-directory.credential.client-secret=zzzzzzzzzz

Again, this all works fine.
The goal is now to have both these authentication approaches available together in my application and to make them switchable. Not surprisingly, if I simply merge the code snippets above all together, the application will not start because I have a WebSecurityConfigurerAdapter as well as SecurityFilterChain, which is not supportable:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: Found WebSecurityConfigurerAdapter as well as SecurityFilterChain. Please select just one.
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653)
    ... 21 common frames omitted
Caused by: java.lang.IllegalStateException: Found WebSecurityConfigurerAdapter as well as SecurityFilterChain. Please select just one.

Many thanks for reading. I'd be very grateful for any suggestions / guidance as to how to proceed so that I can have both authentication providers sitting side by side in my code, with the ability to switch between them with a configuration setting.


text:
Q: How to set a timer for CSS animation-timing-function? Ok, imagine you have created animation with ease-out effect and you set duration for 2s (eg):
animation-name: example;
animation-timing-function: ease-out;
animation-duration: 2s;

Animation-duration property specifies how many seconds an animation takes to complete one cycle, but I was not able to find solution how to (for example) slow down only "ease-out" part of animation.
Here is a fiddle example of simple animation, so you everything ready to test your ideas (if it is even possible?!): https://jsfiddle.net/3nbr6LhL/
(Feel free to use js if you like).
Thank you.

A: How to slow down only "ease-out" part of animation?
You cannot slow down only the ease-out part of the animation as ease-out is a built-in reference to a bezier-curve timing function, which defines the behaviour of the 1d transform of a CSS property's value for the whole duration of the animation:

<timing-function>
The  CSS data type denotes a mathematical function that describes how fast one-dimensional values change during transitions or animations. This in essence lets you establish an acceleration curve, so that the speed of the animation can vary over its duration. These functions are often called easing functions.

What you can do is create your own bezier-curve using a tool like cubic-bezier.com, amending the ease-out curve as you see fit. For example, here is a slower ease-out timing function:
animation-timing-function: cubic-bezier(0, 0, .8, .45);

[ See working in JSFiddle ]
______
How to set a timer for CSS animation-timing-function?
The answer to this depends on what you mean by setting a timer. If you want to delay the animation then you can use the animation-delay property. For example, to delay an animation by three seconds:
animation-delay: 3s;

[ See working in JSFiddle ]

A: You could use a custom timing function instead of ease-out to exactly control the speed of the animation.
Take a look at this CSS EASING ANIMATION TOOL named Ceaser.


text:
Q: submit value for mat-autocomplete We have a mat-autocomplete input on a form.
The options are populated from a database, these are returns as an ID, String pair.
I would like to allow the user to select based on the string value but submit the ID value with the form for a lookup when posted server side? What is the best solution for this please?
My component.html is;
<mat-form-field class="form-group special-input">
    <input type="text" placeholder="Select a trade" aria-label="Select a trade" matInput formControlName="trade" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete" md-menu-class="autocomplete">
        <mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
             <span [innerHTML]="option.name | highlight: toHighlight"></span>
        </mat-option>
    </mat-autocomplete>
</mat-form-field>

Where option has a name and id field.
I have tried adjusting the [value]="option.name" to [value]="option.id" however this updated the text field in the auto complete to be the id value rather than the string?

A: You can add a simple
(onSelectionChange)="selectedOption(option)"

on mat-option, passing the binding of the data to the ts component. Then you can easily decide what value you should pass to the server.


text:
Q: How to display images in Jenkins console output I am running an automation script through Jenkins where the console gives html image tag containing image but currently the Jenkins console output is not displaying the images in the console output.
Are there any plugins/method in jenkins available to do this?

A: It is console and it is absolutely correct to not display images there, cause the only images "available for" consoles are ASCII text decors or something similar.

A: In the console output you can print link to the userContent directory and save image there (https://www.oreilly.com/library/view/extending-jenkins/9781785284243/ch04s05.html).

A: Jenkins console supports only text.
But you can acheive your goal by doing the following things
1) Store the picture (or even videos) jn WORKSPACE directory (usally in the format
/user_home/jenkins/jobs/JOB_NAME) and then archive it as artifact. When an artifact is created, it is shown in jenkins job status and user can download that file.
Sample Jenkins Pipeline:
archiveArtifacts artifacts: /path/*file*

Note: One or more files can be achieved using glob/regexp in file path
2) Allow access to some folders of machine's file system (which might be dangerous) and then create a web app which allows viewing folders/files. Link the file path URL in jenkins console output.


text:
Q: Fusion chart error i make a fusionchart who give me these two errors?how i remove these errors?i make a fusionchart who give me these two errors?how i remove these errors?
<?php

include("DBConn.php");
include("FusionCharts.php");
$link = connectToDB();
$strQuery="select Distinct DATE_FORMAT(transactions.transaction_date,'%c-%d-%Y') as transaction_date,sum(amount)as Amount from transactions group by       DATE_FORMAT(transactions.transaction_date,'%c-%d-%Y')";
    $result = mysql_query($strQuery) or die(mysql_error());
    if ($result) {
$strXML = "<chart caption='Reports' showValues='0' useRoundEdges='1' palette='3'>";
    while($ors = mysql_fetch_array($result)){
    //Generate <set label='..' value='..' />
    $strXML .= "<set label='" .$ors['transaction_date'] ."' value='" . $ors['Amount'] ."' />";
    }
}
    //free the result set
    mysql_free_result($result);
    mysql_close($link);
    //Finally, close <chart> element
    $strXML .= "</chart>";
    //date_default_timezone_set($_SESSION['timezone']);
 ?>

 <script type="text/javascript" src="Charts/FusionCharts.js"></script>
 <div id="chartContainer">
 <?php
 FC_SetRenderer('javascript');
 echo renderChart('Charts/Column2D.swf', // Path to chart type
                '', // Empty string when using Data String Method
                $strXML, // Variable that contains XML string
                'Tracking', // Unique chart ID
                '660', '400', // Width and height in pixels
                false,      // Disable debug mode
                true// Enable 'Register with JavaScript' (Recommended)
            );
 ?>
 </div>

and here is errors:
ReferenceError:
Prototype is not defined
if(Prototype.Browser.IE)

and
ReferenceError:
FusionCharts is not defined

...Charts("Tracking") && FusionCharts("Tracking").dispose ) FusionCharts("Tracking"...

here is my xml
<chart caption='Reports' showValues='0' useRoundEdges='1' palette='3'>
   <set label='1-06-2014' value='50' />
   <set label='1-07-2014' value='151.1500015258789' />
   <set label='1-08-2014' value='45' />
   <set label='1-09-2014' value='0' />
   <set label='1-10-2014' value='0' />
   <set label='1-13-2014' value='0' />
   <set label='1-14-2014' value='0' />
</chart>

how to remove these errors?


text:
Q: Q: R NNETAR external regressors incorporation This is a question about the statistical intuition of the nnetar function of the forecast package. To my knowledge, little is mentioned in the vignette
 and the actual manual of the forecast package. If there are other
I understand that nnetar leverages the nnet library. What I do not understand is how the external regressors "xreg" are factored into the hidden layer.
In other words, as professor Hyndman suggests in the arimax model muddle, the auto.arima function fits the ARIMA part based on the specified test and the unit roots and the "X" external regressors are factored in through the xreg argument. If there are multiple external regressors, the end result is a multiple linear regression with ARIMA errors.
What is the equivalent for nnetar? Are there coefficients for those external variables? How are the contributions of the external variables factored in and how would I find their relative weight?
Finally, I am aware of the bsts package which is, to me, even more opaque. Are there other similar packages for such non-parametric forecasting?

A: External regressors are just added as additional covariates together with the lagged values of the response (like the first equation in the "ARMAX models" section). This is in contrast to a regression model with ARMA errors.
The weights can be retrieved, but I'm not sure how helpful they'll be. There are several complicating factors:

*

*It's hard to derive meaning from neural network weights in general

*In nnetar the external regressors are fitted jointly with the lagged values (as I mentioned above)

*Unless otherwise specified, nnetar fits multiple networks (20 by default) with different random starting weights and then averages their forecasts.

In case you do want to see them, here's a simple example to get the weights from each network:
library(forecast)
mynnetar <- nnetar(lynx)
mynnetar$model[[1]]$wts
mynnetar$model[[2]]$wts
## ...
mynnetar$model[[20]]$wts

This returns a vector of the weights for each network. I believe it's ordered as inputs-hidden-output, but you'll have to look at the nnet documentation to confirm that, and to check which correspond to the bias. The external regressors are placed after the lagged values in the model matrix.
The CRAN Task View for time series lists many packages for forecasting and may have others that are useful for you.


text:
Q: Turning off optimistic lock on a field within a component I am trying to turn off optimistic locking for a particular field within a component. Turning off at the component level (which applies for all fields in component) works. But not for a particular field with in the component. I am using hibernate 3.2.x
Let me explain more about the problem
Member.hbm.xml
   <class name="com.test.core.model.member.Member" abstract="true"
    table="MEMBER" optimistic-lock="dirty" dynamic-update="true"
    polymorphism="explicit" discriminator-value="LITE">
    .....
    .....
    <component name="helper" class="com.test.core.model.Helper">
        <property name="status">
            <column name="STATUS" />
            <type name="org.hibernate.type.EnumType">
                <param name="enumClass">
                    com.test.core.model.Helper$Status
                </param>
            </type>
        </property>
        <property name="changeXML" type="string">
            <column name="CHANGE_XML" />
        </property>
        <property name="lastChange" type="timestamp">
            <column name="LAST_CHANGE" />
        </property>
    </component>
</class>
</hibernate-mapping>

I am constrained to use optimistic-lock="dirty" at the class level, so I cannot switch to "version".
However would like to disable optimistic checks by hibernate for changeXML field inside the component.
So I changed
<property name="changeXML" type="string" >
to
<property name="changeXML" type="string" optimistic-lock="false">

Because this is with in a component this setting is not respected for some reason. As a result hibernate internally generates the verification query before committing an update to changeXML.
ie update MEMBER SET CHANGE_XML ="NEWVALUE" WHERE ID=SOMETHING AND CHANGE_XML=OLDVALUE
However changing at the component level ie
changing from
<component name="helper" class="com.test.core.model.Helper">
to
<component name="helper" class="com.test.core.model.Helper" optimistic-lock="false">

works by respecting this setting and hibernate doesnt generate the update statment
We cannot settle with that option of changing at component level because concurrent updates to "status" is expected and will not fail with staleobjectstateexception.
Is there a way to tell hibernate to respect the optimistic-lock="false" setting within a component ?
Thanks for taking time to read..

A: The property attribute optimistick-lock should do the trick:

specifies that updates to this property do or do not require
  acquisition of the optimistic lock. In other words, it determines if a
  version increment should occur when this property is dirty.

Try updating hibernate to a newer version, like 3.5.6 for instance.


text:
Q: formate a string and truncate from right trying to find a way to format a string in logger format that will show last module name without the long path
i found this solution that truncates with specific width but to the left
truncate and pad using format specification mini language
using the same example, expected behavior:
>>> '{0:<w.p}'.format('path.not.long.module')
'.not.long.module  '

>>> '{0:<w.p}'.format('path.other.very.long.module')
'.very.long.module '

>>> '{0:<w.p}'.format('short.module')
'short.module      '

current json format - i am trying to edit the path in name field:
"format": "{levelname:8s}; {asctime:s}; {name:<15s} {lineno:4d}; {message:s}"

Expected output:
DEBUG; 09:15:00; truncated.path.name    1111; Log message with logger


text:
Q: Can't create partition from free space in internal drive ubuntu I have installed ubuntu in a 3TB disk and now it seems like the biggest part of it is lost.
When opening disks i see all the partitions and some free space.
When i click the setting button all options are black and i can't click anything like formatting the partition. This is the only disk i have in my computer right now because i installed ubuntu from a usb directly to this disk.
SO when i tried to click the "+" button and create partition even with 2tb i am getting this error:

So as you see the whole application crashes and i am forced to close it.
I have also tried gparted but this gives this error:

And then the app crashes again...
I have looked all the related questions in this forum and also in others so please don't send me any of those and please don't flag it as a duplicate...
Yes i have also tried with command line but it didn't work and what happened was crashed the whole os and i lost everything and boot the os from scratch again.

A: Your disk has an MBR partition table. This table has a limitation.
Maximum partition size is 2 TB. And total disk space available is also 2 TB.
You need to reformat the disk using GPT.


text:
Q: How to reduce DrawCount in UE4 project? any optimizing professional? I have a big project to optimize a lot of buildings, trees, and assets. I have a very high BasePass, PrePass, ShadowDepth, and Translucency. See the Image ScreenShot
Any Advice?
Ryzen 7 4800H + RTX 2060 + 16GB RAM

A: If we're going to reduce draw calls, we're talking about making the engine render fewer objects at once with fewer materials.
Your go to methods for this are:
-Setting up HLOD's to combine distant meshes
https://docs.unrealengine.com/4.26/en-US/BuildingWorlds/HLOD/Overview/
-Setting up HISM's/ISM's (As long as you are using DirectX 12 and not 11.  With 11 it will do this by itself).  Remember to only do this on objects that are beside each other or the problem can get worse.
https://www.unrealengine.com/marketplace/en-US/product/instance-tool
-Reducing the number of material slots on meshes that don't need so many or combining small meshes with similar materials.  Actor merging can be great for this, just be careful of going overboard because it can make light baking & lightmap memory usage a pain.
https://docs.unrealengine.com/4.26/en-US/Basics/Actors/Merging/
-Reducing the max draw distance on some of your smaller meshes that are close to the ground. You can find this in the mesh's rendering settings.
Any of these things would reduce draw calls, just be careful with it.  Too much optimization by any one method can always make the problem worse by creating bottlenecks elsewhere.  When we're reducing draw calls we're also risking slowing down occlusion calculation times or potentially creating a memory bandwidth bottleneck.
Once you get that draw thread time down the next thing I'd go onto is looking at reducing the number of movable lights, objects casting dynamic shadows, and translucent objects casting dynamic shadows.   Those are some common culprits of other optimization issues.


text:
Q: Uploaded image in angular 7 not displayed just after upload I have written the below code which is working, there is no compilation error. I am successfully getting the uploaded images printed in the console. But just after uploading the image, its not visible in the page. I need to click anywhere on the screen ,then the images get previewed in the screen.

  onFileChange(event) {
    if (event.target.files && event.target.files[0]) {
     var filesAmount = event.target.files.length;
      for (let i = 0; i < filesAmount; i++) {

        var reader = new FileReader();
        reader.readAsDataURL(event.target.files[i]);
        reader.onload = (event: any) => {
            this.images.push(event.target.result);
        };
      }
    }
  }
 <form [formGroup]="formGroup" (ngSubmit)="submit()">

          Step 4: Sample information

              <input
                id="file"
                type="file"
                class="form-control"
                accept="image/*"
                (change)="onFileChange($event)"
              />

Upload image

//other formgoup inputs will be written here

            <button
              type="button"
              class="btn btn-sm btn-primary-outline me-3"
              routerLink="/order/create-order"
              [queryParams]="{ id: orderObject?.orderID }"
            >
              Back
            </button>
            <button type="submit" class="btn btn-sm btn-primary">
              Continue
            </button>

    </form>

Every time I click choose file in the this.image the images get inserted. If I try to runconsole.log(this.images)  it also gets printed . But its not immediately rendered in the screen by this array this.images via *ngFor
When this ts code is run in https://stackblitz.com/edit/angular-file-upload-preview?file=app%2Fapp.component.ts its running fine. Just after choosing file the image get visible in the screen.
Please help me to know what is the reason behind such behavior.

A: You might need to run the angular cycle again. try
 constructor(
    private cdr: ChangeDetectorRef
  ) {}

 reader.onload = (event: any) => {
      this.images.push(event.target.result);
      this.cdr.detectChanges();
  };


text:
Q: How to isolate the effect of dichotomous predictor? I want to isolate gender differences in preferences for a particular attribute of a product based on data available about their product purchases. I understand that I have to use a mixed Poisson regression model as in my data - (1) I have same person buying multiple products (also, a given product might be bought by several people); and (2) the product attribute I am interested is a count variable. I am using the below model in R -
glmer(p1 ~ gender + (1|personID), family=poisson)

In this model, how should I control for the effects of other product attributes (e.g., price)? In essence, I want to say something to the effect of "women prefer products that are high on p1 more than do men, even after controlling for price of the products"?  Would the below modification to the model take care of all other product attributes?
glmer(p1 ~ gender + (1|personID) + (1|product), family=poisson)

A: Variables that you want to control for are usually added as independent variables to your model (so you'd simply add price to the RHS of the equal sign in your model statement).
That being said, I wonder if you are approaching your modeling in an appropriate way?  What is $p_1$ here?  Is $p_1$ a count variable?  Poisson models are usually reserved for modeling count data (i.e. when your response is a count, not your independent variables) -- this is the reason you were probably told to use a Poisson model -- not because of the first reason you listed in your post: "I have same person buying multiple products (also, a given product might be bought by several people)."  When you have multiple purchases by the same person, this usually indicates that here is a correlated data problem, which means you'll likely have to rely on other methods than a standard Poisson model.  This is likely why someone recommended you use a mixed model.   That being said, given that you are interested in overall/population gender effects, and you have correlated data, I'd recommend the use of Generalized Estimating Equations or a Quasi-Poisson model.  Mixed models are generally needed for estimating individual level effects (e.g. if you were interested in looking at a specific person's purchase behavior), but in this case, you seem interested only in population-level estimates to predict general preferences among demographic blocks.
What I would recommend you do is build a GEE model and include as many different attributes as you want to control for on the product as covariates in your model as well as your repeated subject ID and gender indicator variable.  Then you'll be able to say for example what the expected effect on your response is when you go from males to femals (or vice-versa) when controlling for the given attributes.  You should consider including interaction terms if you think certain attributes have a differential effect on your outcome variable for males and females.  This will also allow you to assess the impact of the attributes on preferences.


text:
Q: ESP32 custom board not receiving code I'm trying to program one ESP32 custom board with a CP2102 USB, I followed the schematic of the official datasheet but when I try to upload my code the board doesn't recieve the code but the TX led shining :

This is my schematic:

I tried also wiring the EN and GND pin but with the same result, and adding one 25 uF capacitor between EN and GND, does anyone have any idea where my fault is?
[![enter image description here][4]][4]

A: I solved it yesterday, I needed to put a jumper on the EN and GND pins and immediately after put a jumper on GPIO0 and GND, after that, the code was loading without problems. For the next designs I will put EN and RESET buttons. Thanks everybody


text:
Q: ASP.NET MVC3 Code-First Error- attempting to update entity I've checked this question and it seems to be related to what I need, but does not answer it exactly.
I have an entity (Sql Compact using EF Code First via MVC3- if that wasn't clear from the title) for an "Issue" (generic issue tracking, just for my own education understanding of how MVC3 works).  The Issue class has a CreatedBy property (Int reference to a User who Created the Issue) and a CreatedDate property (DateTime).  When I use the scaffolded code to update (modified only to prevent some updated date fields from being modified by the user):
        if (ModelState.IsValid)
        {
            issue.LastActivity = (DateTime?)DateTime.Now.Date;
            if (issue.ClosedBy != null) issue.ClosedDate = (DateTime?)DateTime.Now.Date;
            startingIssue = null;
            db.Entry(issue).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

I receive the error mentioned in the linked question (conversion of a datetime2 data type to a datetime data type etc., etc.,)
When I step through the code, it appears my CreatedBy and CreatedDate properties are not contained in the instance of issue that the controller is passing around.  When I try to fix that by grabbing another copy of the issue from the db, and updating those to values:
        var startingIssue = db.Issues.Find(issue.IssueId);
        if (ModelState.IsValid)
        {
            if (issue.CreatedBy != startingIssue.CreatedBy) issue.CreatedBy = startingIssue.CreatedBy;
            if (issue.CreatedDate != startingIssue.CreatedDate) issue.CreatedDate = startingIssue.CreatedDate;
            issue.LastActivity = (DateTime?)DateTime.Now.Date;
            if (issue.ClosedBy != null) issue.ClosedDate = (DateTime?)DateTime.Now.Date;
            startingIssue = null;
            db.Entry(issue).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

I get the concurrency violation: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
So, how do I get EF to see the date which is already set in the DB (so it doesn't try to update the CreatedDate to 1/1/0001) without violating concurrency?
Edit
Okay... I found it.  I was, apparently, looking for @Html.HiddenFor(model => model.[property]) and adding the editor to the view anyway.  That seems a little silly and round-about to me, but it does work without having to add custom code to detach one object and substitute an updated one.

A: The short answer is that you've already loaded the entity into the context with the Find and you cannot later attach another one.
You are left with two options:

*

*Detach the first instance, then attach the second

*Copy the fields from the second instance to the first

I'll share code for the first option. First, add a Detach method to your DbContext implementation:
public void Detach(object entity)
{
    var objectContext = ((IObjectContextAdapter)this).ObjectContext;
    objectContext.Detach(entity);
}

Then call Detach instead of setting the variable to null
var startingIssue = db.Issues.Find(issue.IssueId);
if (ModelState.IsValid)
{
    if (issue.CreatedBy != startingIssue.CreatedBy) issue.CreatedBy = startingIssue.CreatedBy;
    if (issue.CreatedDate != startingIssue.CreatedDate) issue.CreatedDate = startingIssue.CreatedDate;
    issue.LastActivity = (DateTime?)DateTime.Now.Date;
    if (issue.ClosedBy != null) issue.ClosedDate = (DateTime?)DateTime.Now.Date;

    // startingIssue = null;
    db.Detach(startingIssue);

    db.Entry(issue).State = EntityState.Modified;
    db.SaveChanges();
    return RedirectToAction("Index");
}

A: If the CreateDate and CreatedBy fields are not in the edit form, the update action object will not have the db values.
The additional call to the db and resetting, as Ed's answer describes, can be avoided if you include those fields in the edit form. Then the normal model binding should pick them up and give them back to you on the update.


text:
Q: Conditions for interchanging Ito and Riemannian integrals Let $X_{s,\ r}$ be an adapted real-valued stochastic process, $s,\ r \geq 0$ and $W_s$ be the standard one-dimensional Wiener process (Brownian motion). Under which condition on $X_{s,\ r}$ does the following hold?
For a fixed $t\geq 0$,
$$\int_0^t\int_0^t X_{s,\ r} dW_s dr = \int_0^t\int_0^t X_{s,\ r} dr dW_s .$$
Thank you!
————————————————
Edit:
Mark Veraar's comment answers this question.


text:
Q: Wilson's supporters were lined up for a favorable ratification
Wilson's supporters were lined up for a favorable ratification vote, but were unprepared to act unless he authorized them to accept mild qualifying language, this he refused to do.

I cannot understand the meaning of he authorized them to accept mild qualifying language, this he refused to do. What does it mean?

A: First of all, here's how i believe this sentence would appear with the correct punctuation:
"Wilson's supporters were lined up for a favorable ratification vote, but were unprepared to act unless he authorized them to accept mild qualifying language; this he refused to do."
Putting "; this he refused to do" at the end is like saying
"... accept mild qualifying language.  He refused to do this."
Does that help?  It's not clear from your question exactly what you're having problems with.

A: Mild Qualifying language are extra terms that define how a ratification is applied. Mild suggests they are only small changes.
For example, say you were ratifying:
Cyclists will be able to ride their bicycles in bus lanes in our city
Mild qualifying language would, for example, change it to:
Cyclists on road bikes would be able to ride their bicycles in bus lanes in our city


text:
Q: Have li:nth-child effect only parent list and not child list I am able to achieve the effect I want but wondering if there is a better way of coding. I am using li:nth-child() to select parts of a parent list I want to add a border to.
However I do not want these to effect sub lists inside the parent list.
HTML

Link 1

Sub Link 1

CSS
.nav li:nth-child(-n+3) {
    border-left: 4px solid #FFC50A;
}

How do I get the "Sub Link 1" to not have a border without using:
.nav > li > ul > li {
    border: 0px !important;
}

Should I just give the parent list a class to make the list have a border instead of using .nav li:nth-child(-n+3)?
See Fiddle

A: As I noted in comments, you could use child selector in order to prevent for the inner list items from be treated by the selector, as follows:
.nav > li:nth-child(-n+3) {
    border-left: 4px solid #FFC50A;
}

EXAMPLE HERE

5.6 Child selectors
  A child selector matches when an element is the child of some element.
  A child selector is made up of two or more selectors separated by >.

A: Unfortunately, due to the cascading nature of CSS, I don't think this is explicitly possible (yet).
I think if I were implementing this, I might define parent and child classes for each list. This would help with specificity, but you can run into problems if the HTML is generated instead of hand-coded.
EDIT:
Another thing I just thought of is (depending on your scalibility needs here), you could try just styling children with your overrides like so:
fiddle

Link 1

Sub Link 1

and
.childList {
position: relative;
width: 175px;
padding: 0;
display: inline-block;
margin-right: 20px;
color: #555;
border: 0px !important;

}
. I'm not really sure how this list will be balanced, so to speak, so this could be a bad answer as well.


text:
Q: Processing structured data into a database from a giant text file using PHP? I have text files containing structured data (it is a proprietary format and not something simple or common like CSV). I'm trying to put this data into a database.  The text files are as large as 50GB so it's impossible for me to read the entire file into memory, extract it into an array, then process it into the database.
The text files are structured in such a way that data on a particular "item" (a specific id in the database) can have multiple lines (new lines) of information in the text file.  Items in the text file always start with a line that begins with '01' and can have an infinite number of additional lines (all one after the other), that will all start with 02 or 03 ... up to 08.  A new item begins when a new line starts with 01.
01some_data_about_the_first_item
02some_more_data_about_the_first_item
05more_data_about_the_first_item
01the_first_line_of_the_second_item

I'd like to use PHP to process this data.
How can I load a piece of this text file into memory where I can analyze it, get all the lines for an item, and then process it?  Is there a way to load all lines up to the next line that starts with 01, process that data, then begin the next scan of the text file at the end of the last scan?
Processing the data once I've loaded pieces of it into memory is not the problem.

A: Sure. Since you tagged the question with csv, I'll assume you have a CSV file. In that case, fgetcsv is a good function to use, which get one line from the file at a time. Using that you can get as many lines as you need for one record, then process it, then continue with the next one. Rough mockup:
$fh = fopen('file.csv', 'r');
$record = array();

do {
    $line = fgetcsv($fh);

    if ($line && $line[0] != '01') {
        // any line that does not start with 01 is part of the current record,
        // adjust condition as necessary
        $record[] = $line;
    } else if ($record) {
        /* put current $record into database */

        // start next record
        $record = array($line);
    }
} while ($line);

A: Here is a start:
<?php
$fp=fopen('big.txt','r');

while($line=fgets($fp)){
    $number=substr($line,0,2);
    $data=substr($line,2);

    // proccess each line
    echo $number.' - '.$data;
}
fclose($fp);
?>


text:
Q: How can I redirect a strongly named assembly by code using AssemblyResolve or otherwise? The typical way of creating an assembly redirect is by using bindingRedirect in app.config or dllname.dll.config. Alternatively, many posts on MSDN say that you can do so programmatically by using AssemblyResolve (I bind the event as early as possible, i.e. in <Module>.cctor).
What these posts don't tell you is that if an assembly is strongly named (in my case FSharp.Core 4.3 that must be redirected to 4.4), the AssemblyResolve method does not seem to work. Checking the Fusion Log Viewer shows an error indicating that there is a version mismatch after AssemblyResolve:
=== Pre-bind state information ===
LOG: DisplayName = FSharp.Core, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
 (Fully-specified)
LOG: Appbase = file:///D:/Projects/ThisProj/
LOG: DEVPATH = C:\ProgramData\Red Gate\.NET Reflector\DevPath
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = R:\TMP\nunit20\ShadowCopyCache\39776_635854331778854585
LOG: AppName = Tests_913980014
Calling assembly : FsUnit.NUnit, Version=1.4.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: No application configuration file found.
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Post-policy reference: FSharp.Core, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
LOG: Did not find assembly in DEVOVERRIDE path C:\ProgramData\Red Gate\.NET Reflector\DevPath
LOG: GAC Lookup was unsuccessful.
LOG: Attempting download of new URL file:///D:/Projects/ThisProj/FSharp.Core.DLL.
LOG: Assembly download was successful. Attempting setup of file: D:\Projects\ThisProj\FSharp.Core.dll
LOG: Entering download cache setup phase.
LOG: Assembly Name is: FSharp.Core, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
WRN: Comparing the assembly name resulted in the mismatch: Minor Version
ERR: The assembly reference did not match the assembly definition found.
ERR: Setup failed with hr = 0x80131040.
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

In most typical scenarios this is not a problem and I can settle with the .config approach, however, if you compile a project that references other projects with an app.config Visual Studio will only create one targetassemblyname.config for the final project, but won't do so for each individual assembly referenced, resulting in runtime binding issues for the final project (which in itself can be resolved by creating a post-build copy event).
This is also a problem when another application is trying to load an individual DLL from my project. Either because the config file is simply not there or, if the DLL is "copied around", the dll-config is not copied with.
Is there some workaround that can force the CLR to load the assembly I give to them, irrespective or version, just like the bindingRedirect works?


text:
Q: Linear momentum being independent of the coordinate system "An Introduction to Mechanics" by Kleppner and Kolenkow has the following lines:

Angular momentum $\vec L$ explicitly involves the position vector $\vec r$. The value of $\vec L$ therefore depends not only on the motion of the particle, but also on its location with respect to the origin of a particular coordinate system. This is in contrast to the situation for linear momentum $\vec p$, which is independent of the coordinate system.

When the author mentions "coordinate system" in the above lines, is he referring to a coordinate system that is fixed to the earth( approximately inertial )?
As far as I know, in Classical Mechanics, linear momentum $\vec p$ of a system moving on the earth is independent of any coordinate system that is fixed( to the earth ). If the coordinate systems are moving, different observers will record different momenta for a particular system, will they not?

A: You are right. The linear momentum of a mass point depends, of course, on the inertial system you are using to describe the motion of the mass point. Most easily you can see this from $$\vec p =m\vec v$$ where $\vec v$ is the velocity in a reference frame $\Sigma$. Using the Galilean transform for low relative speed, in an inertial reference frame $\Sigma'$ moving with constant velocity $\vec v_{rel}$ without rotation relative to the first, the velocity of the mass point $$\vec v'=\vec v-\vec v_{rel}$$ Thus the linear momentum in the reference frame $\Sigma'$ will be $$\vec p'=\vec p -m\vec v_{rel}$$

A: What the book suggests is that suppose you are in an inertial reference frame i.e. either you are at rest with respect to the particle or you are moving at an uniform speed wrt to it. The former case is trivial as then the relative velocity of the particle is $0$, and thus the momentum is also $0$. Given the second case, you observe a momentum equal to the particle's mass times relative velocity ( within a Lorentz factor $\gamma$ ).
The position of the origin of the reference frame is immaterial as it occurs nowhere in the calculations. This is what is referred to as an affine transformation, specifically translations and scalings. Whether you translate your coordinates anywhere, as long as your relative velocities stay the same, you will measure the same momentum of the particle. (But it might change if you rotate your reference frame or do something weird like being in an accelerated reference frame etc).

A: A simple view.
A coordinate system is defined in space by defining the location of (0,0,0) with respect to which one measures (x,y,z) and therefore the $\vec r$ vector. The momentum is not a function of $\vec r$ , so within an inertial system the definition is unchangeable.
Angular momentum is defined by the choice of (0,0,0) a moving mass will have a different angular momentum depending where one defines the (0,0,0) . Usually we define it on the axis of rotation because the angular momentum concept is used in rotating wheels etc. Conservation of angular momentum holds only in this case.
But in the general definition  where the (0,0,0) can be chosen anyplace and an angular momentum defined, for example for a particle moving in as straight line versus a chosen origin, the angular momentum would be changing as the particle moves, as $\vec r$ would be changing, so no conservation law. See  also the answer here.