Q: The conjugacy classes of diagonalizable $2 \times 2$ matrices can be identified with their eigenvalues, what about pairs? For sake of simplicity, let's say that we live in $G = SL(2, \mathbb{C})$. Every conjugacy class of diagonalizable matrices $$[A] := \{gAg^{-1} \mid g \in G\}$$ can be identified with its set of eigenvalues $\{\lambda, \lambda^{-1}\}$. As such, the collection of diagonalizable matrices in $SL(2, \mathbb{C})$ can be identified with $\mathbb{C}^\times / \{z \sim z^{-1}\}$.
How about the conjugacy class of pair of matrices $$[A, B] = \{(gAg^{-1}, gBg^{-1}) \mid g \in G\}?$$ Can they similarly be identified with their eigenvalues in a natural way? What is the significance of this identification?

A: It is fairly easy to do this directly. I consider the case that both $A$ and $B$ are individually diagonalizable, and not scalar. Note also that ${\rm SL}(2,\mathbb{C})$-conjugacy is equivalent to ${\rm GL}(2,\mathbb{C})$-conjugacy, since every matrix in ${\rm GL}(2,\mathbb{C})$ has a scalar multiple in ${\rm SL}(2,\mathbb{C})$. For a pair $(X,Y)$ to be $G$ conjugate to a pair $(U,V)$ we first need $X$ and $U$ to be $G$-conjugate, so we might as well assume that $X = U$, and that both are diagonal. In that case, $Y$ and $V$ need to be conjugate within $C_{G}(X)$. But $C_{G}(X)$ now consists of diagonal matrices. Hence $Y$ and $V$ need to be conjugate via a diagonal matrix.
Degenerate cases : If $U$ and $X$ are both the same scalar, then the pair $Y$ and $V$ simply need to be $G$-conjugate. If $X$ and $Y$ commute (neither scalar) and $U$ and $V$ commute (neither scalar), then if we assume wlog that $U = X$, then the pair $(U,V)$ is conjugate to $(U,Y)$ if and only if we also have $Y = V$.

A: Let me complete Ehud Meier's answer. One cannot distinguish one eigenvalue among $(\lambda,\lambda^{-1})$. In other words, one cannot distinguish between the projections $p_j$ and $q_j=1-p_j$. Therefore, $\alpha$ is only one among four relevant numbers. If $p_1q_2p_1=(1-\alpha)p_1$ is clear, it is less obvious that $q_1p_2q_1=(1-\alpha) q_1$.
Therefore one expect that the conjugacy classes are parametrized by the triples $(\alpha,\lambda,\mu)$, modulo the group generated by the involutions
$$(\alpha,\lambda,\mu)\mapsto(1-\alpha,\lambda^{-1},\mu)\quad\hbox{or}\quad(1-\alpha,\lambda,\mu^{-1}).$$

A: You have a geometric invariant theory question here: your space is the space of the pairs of matrices, and the action is given by conjugation. One possible way to deal with this is to study the ring of invariant functions. In case of one matrix it really boils down to the ring generated by the coefficients of the characteristic polynomial. In case of two matrices it is more complicated, and was studied by Proecsi in the paper "The invariants of n x n matrices". Basically the invariants are generated by polynomials of the form $tr(M_1M_2\ldots M_n)$ where $M_i=A$ or $B$. The relations between these polynomials are studied in Procesi's paper. Since you consider here only the two dimensional case, I would continue as follows:
Lets say that both matrices are diagonalizable, and that $A$ has the eigenvalues $\lambda,\lambda^{-1}$ and $B$ has the eigenvalues $\mu,\mu^{-1}$. Then we can write the two dimensional vector space $V=\mathbb{C}^2$ as the direct sum $V_{\lambda}\oplus V_{\lambda^{-1}} = V_{\mu}\oplus V_{\mu^{-1}}$. Let $p_1$ be the projection onto $V_{\lambda}$ (with respect to the first decomposition) and let $p_2$ be the projection onto $V_{\mu}$ (with respect to the second decomposition).
Then since the space is two dimensional, there will be a scalar $\alpha$ such that $p_1p_2p_1 = \alpha p_1$. I believe that $\alpha$, $\mu$ and $\lambda$ will determine the pair of matrices. You will have to mod out by a certain equivalence relation, but it is not so hard to write this equivalence relation explicitly.


Q: Transformer Operation I have few questions about transformer operation.
One of the main points of the transformer is ground isolation.
Let's say if have a transformer in an ethernet transmitter, and my circuit in the primary of the transformer runs at 5 volts.
First quesiton: What is going to be the voltage on the secondary terminals of the transformer?
Second question: Will we be also transmitting a ground reference to the receiving end? Or will it will just be a differential signal?
Third question: Do we always need a reference voltage when we send a differential signal? If not, then how does the receiving end know the reference voltage?

A:
What is going to be the voltage on the secondary terminals of the transformer?

If the transformer has a 1:1 winding ratio, then the primary voltage equals the secondary voltage at all times (neglecting leakage and other non-ideal stuff). In the more general case, the voltage ratio between the primary and secondary sides is equal to the the winding ratio.

Will we be also transmitting a ground reference to the receiving end? Or, it will just be a pair of differnetial signals?

If the receiving end is connected to the secondary, and you don't otherwise connect the secondary to ground, then there's no ground reference. That's often the point of using transformer-coupled signaling.

do we always need a reference voltage when we send a differential signal? If not then how does the receive end knows the reference voltage?

The "reference" is the other half of the differential pair.

simulate this circuit – Schematic created using CircuitLab
Here, VM1 will mirror V1, even if the two sides are connected to different grounds. The ground noise, which might represent natural variations in Earth potential between two distant points, has no effect on the signal. For signal transmission across appreciable distances, this is a really big win.
I've drawn it here with two transformers to make it symmetrical, and so you can clearly see how there's a loop of wire in the middle with no connection to anything else, but which caries the signal anyway. However, even with one transformer, the ground noise is still isolated, although each side is referenced to its own, different idea of "ground".


Q: How to share reqwest clients in actix-web server? I'm building a web server with actix-web, and one of the methods uses reqwest to make HTTP requests to an external API:
#[get("/foo")]
async fn foo() -> impl Responder {
  let resp = reqwest::get("https://externalapi.com/bar").await?; # GET request inside server
  ...
}

To improve the performance, I want to reuse the client of reqwest, because it holds a connection pool, according to the doc.
However, I cannot use Arc to share the client, because the doc also has the following statement:

You do not have to wrap the Client in an Rc or Arc to reuse it, because it already uses an Arc internally.

How can I share the client across the function calls?
Or, should I use a different library to create HTTP request inside web servers?

A: Actually suggestion in the documentation is the solution:

You do not have to wrap the Client in an Rc or Arc to reuse it, because it already uses an Arc internally.

Simply clone the client.
Please check the Client definition from the source:
#[derive(Clone)]
pub struct Client {
    inner: Arc<ClientRef>,
}

You can think Client as a reference holder
The inner type(ClientRef) has wrapped with Arc as the documentation says and Client has Clone implementation, since there is no other fields except inner: Arc<_>, cloning the client will not cause any runtime overhead comparing to wrapping it with Arc by yourself.
Additionally Client implements Send this means clone of clients can be send across threads, since there is no explicit mutable operation over Client then Mutex is not needed in here. (I said explicit because there might be an interior mutability)


Q: problems understanding java ActionListener - Performed(ActionEvent e) I have to write code for a Fibonacci program that builds a GUI with two text box and a button.  A user inputs a number in text box 1 and clicks the button which then places the Fibonacci of that number. I am having problems understanding the actionPerformed part of java and would appreciate any help. Here is my code: There are 3 files.
Fibonacci.java
public class Fibonacci{
   int Fib (int n){
      int in1=1,in2=1;
      int sum=0;//initial value
      int index=1;
      while (index<n){
         sum=in1+in2;//sum=the sum of 2 values;
         in1=in2;//in1 gets in2
         in2=sum;//in2 gets sum
         index++; //increment index
      }
   return sum;
   }
}

FibonacciJPanel.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class FibonacciJPanel extends JPanel implements ActionListener
{  private JTextField inField = new JTextField(15);  //GUI components
   private JTextField resultField = new JTextField(15);
   private JLabel prompt1 = new JLabel("Input Fibonacci>>");
   private JLabel prompt2 = new JLabel("Conversion Result:");
   private JButton FibonacciButton = new JButton("Fibonacci of the input");
   private JPanel panelN = new JPanel();        //Panels
   private JPanel panelC = new JPanel();
   private JPanel panelS = new JPanel();
   private Fibonacci F = new Fibonacci();

   public FibonacciJPanel()                     //Set up user panel
   { setLayout(new BorderLayout());             //User BorderLayout
     panelN.setLayout(new BorderLayout());
     panelC.setLayout(new BorderLayout());
     panelS.setLayout(new BorderLayout());
     panelN.add("North", prompt1);              //Input elements
     panelN.add("South", inField);
     panelC.add("West", FibonacciButton);       //Control button
     panelS.add("North", prompt2);              //Output elements
     panelS.add("South", resultField);
     add("North", panelN);                      //Input at the top
     add("Center", panelC);                     //buttons in the center
     add("South", panelS);                      //Result at the bottom
     FibonacciButton.addActionListener(this);           //Register with listeners
     setSize(175,200);
   } //FibonacciJPanel

public void actionPerformed(ActionEvent e)
    {
String inputStr = inField.getText();        //user input
        int userInput = Integer.parseInt(inputStr); //convert to integer
        boolean result=false;
    if (e.getSource() == FibonacciButton);          //Process and report
    {
            result = fc.sum(userInput);
            resultField.setText("result");

    } //if
     }//actionPerformed()
}

FibonacciJApplet.java
import javax.swing.*;

public class FibonacciJApplet extends JApplet
{   public void init()
    {   getContentPane().add(new FibonacciJPanel());
    } // init()
} // Fibonacci class

A: You don't mention what is exactly what you don't understand.
Basically when you add a button it knows how to trigger events when you click it to a thread called Event Dispatcher Thread ( EDT ).
Every time you click on a button this event will notify to every "Listener" registered within that button ( They are listening for notifications )
So a simpler example would be:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

class Click {
    public static void main( String ... args ) {
        JButton clickMe = new JButton("Click Me");
        ActionListener aListener = new OneActionListener();
        clickMe.addActionListener( aListener );
        JFrame frame = new JFrame();
        frame.add( clickMe );
        frame.pack();
        frame.setVisible( true );
    }
}
class OneActionListener implements ActionListener {
    public void actionPerformed( ActionEvent e ) {
        System.out.printf("Clicked. Thread: %s, action: %s%n",
            Thread.currentThread().getName(),
            e.getActionCommand() );
    }
}

Here you declare a class OneActionListener that implements ActionListener interface to let know the button he can handle the event ( with the actionPerformed method )
I hope this clear out a bit how this works.


Q: Impossible to search for usernames with punctuation in chat When you do a search in chat, the punctuation is removed. For example, searching T.E.D. gives me everyone with /ted/i, but it doesn't catch the one user named T.E.D..
The same thing goes for searching F'x to find F'x. Or searching J.M. to find J.M..
The context of this is that I was looking for T.E.D. (new mod) so that I could fix his chat profile so that it is recognized by the TL bot. I couldn't find him, no matter what I searched -- finally I searched "D", sorted by reputation, found the pages where his approximate total rep would fit (unfortunately, chat rep != flair rep, and I didn't want to jQuery-calculate it), and looked through a bunch of them. I really shouldn't have to do this.
It occurs to me that if Link to chat user from profile page was implemented, this would be pretty much a non-issue. < /plug >

A: This fix required a change to how user names are normalized; I missed the user name search when making this change. Fixed now.


Q: Calculating the expected value of a transformed random variable in MATLAB? I am trying to compute the following expected value for Z being lognormally distributed
E[Z^eta w(F_Z (Z))^-eta]
where eta is a real number, F_Z the distribution function of Z and w:[0,1]->[0,1] an increasing function.
First of all, I am pretty new to Matlab so I don't know which way of integrating is the better one, numerically or symbolically. I tried symbolically.
My idea was to subsequently define functions:
syms x;
g_1(x) = x^eta;
g_2(x) = logncdf(x);
g_2(x) = w(x)^-eta;
g_4(x) = g_1(x) * g_3(g_2(x));

And then
exp = int(g_4(x),x,0,inf)

Unfortunately this doesn't work and MATLAB just posts the whole expression of g_4...
Is it better to use the numerical integration quadqk? What am I doing wrong here? I already read something about MATLAB not being the best program for integration but I have to use it so switching to a different program does not help.
Thanks a lot!


Q: Prove that if certain conditions are met, $p$ does not appear in prime power decomp. of $2n$ choose $n$. I am working out of Dudley and am having troubles with the following problem: Prove that if $p$ is odd and $2n/3 < p \le n$, then $p$ does not appear in the prime-power decomposition of $\displaystyle \binom{2n}{n}$.
This is equivalent to the statement that $p \nmid \frac{(2n)!}{(n!)^2}$. I know that $p < 2n$, since $p$ is odd and in general $p \le 2n$. I'm just a bit lost after this, and don't know where to go from here.

A: Note that
$$\binom{2n}{n}=\frac{(2n)(2n-1)(2n-2)\cdots(n+1)}{n(n-1)(n-2)\cdots1}$$
and consider the multiples of $p$ dividing numerator and denominator.  We have
$$\tfrac23n<p\le n\ ,\quad \tfrac43n<2p\le2n\ ,\quad 2n<3p\le3n$$
so $p$ is a factor of the denominator, $2p$ is a factor of the numerator, and subsequent multiples of $p$ are factors of neither numerator nor denominator.  Therefore the numerator has a factor of $p$ once, so does the denominator, these cancel and the quotient has no factor of $p$ at all.


Q: How to get points from a line in OpenCV? The cvLine() function can draw a straight line given two points P1(x1,y1) and P2(x2,y2). What I'm stuck at is getting the points on this line instead of drawing it straight away.
Suppose I draw a line (in green) AB and another line AC. If I follow all the pixels on line AB there will be a point where I encounter black pixels (the border of the circle that encloses A) before I reach B.
Again when traveling along the pixels on line AC black pixels will be encountered twice.

Basically I'm trying to get the points on the (green) lines, but cvLine() doesn't seem to return any point sequence structure. Is there any way to get these points using OpenCV?
A rather dumb approach would be to draw the line using cvLine() on a separate image, then find contours on it, then traverse that contour's CvSeq* (the line drawn) for the points. Both the scratch image and the original image being of same size we'd be getting the points' positions. Like I said, kinda dumb. Any enlightened approach would be great!

A: I think a CvLinIterator does what you want.

A: Another dirty but efficient way to find the number of points of intersection between circles and line without iterating over all pixels of the line is as follows:
# First, create a single channel image having circles drawn on it.
CircleImage = np.zeros((Height, Width), dtype=np.uint8)
CircleImage = cv2.circle(CircleImage, Center, Radius, 255, 1)  # 255-color, 1-thickness

# Then create an image of the same size with only the line drawn on it
LineImage = np.zeros((Height, Width), dtype=np.uint8)
LineImage = cv2.line(LineImage, PointA, PointB, 255, 1)  # 255-color, 1-thickness

# Perform bitwise AND operation
IntersectionImage = cv2.bitwise_and(CircleImage, LineImage)

# Count number of white pixels now for the number of points of intersection.
Num = np.sum(IntersectionImage == 255)

This method is also fast as instead of iterating over pixels, it is using OpenCV and numpy libraries.
On adding another circle in the image "CircleImage", you can find the number of interaction points of both the circles and the line AC.


Q: How to code into Mathematica Section 10.3: r = 1 + (cos(theta))^999
a.)  Graph the given polar curve. Choose a parameter interval to make sure that you produce the entire curve. (This is called the Pac-Man Curve.)
My code:
f[x_] = 1 + Cos[x]^999;
Plot [f[x], {x, -pi, 2 pi}]

A: PolarPlot[1 + Cos[θ]^999,
 {θ, 0, 10}]


Q: change margin for   and  in wkwebview kit in objective c I wanted to reduce the space in the HTML string.
below is the code is am using
  NSString *headerString = @"<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'>";
    headerString = [headerString stringByAppendingString:htmlstring];
    headerString = [headerString stringByReplacingOccurrencesOfString:@"

" withString:@"

"];
    headerString = [headerString stringByReplacingOccurrencesOfString:@"

" withString:@"

"];
 [webviewkit loadHTMLString:headerString baseURL:nil];

I had also tried using Javascript but i am not sure what exactly the java script i should passed which will only give 1line spacing instead of mulitple line spacing :
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
 [webView evaluateJavaScript:@"document.open();document.close()" completionHandler:^(id _Nullable stringresult, NSError * _Nullable error) {
        NSLog(@"result=>%@ error->%@",stringresult,error);
    }];
}

But i am not able to remove the spacing properly.
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'>
Hello and welcome to XYZ session!

Over the next three Hello world.  Spacing takes alot of spaces over here due to span , br and div tags.

Thank you again for agreeing to participate and helping the discussion....

Over here,

I will be posting questions over here in stack overflow

Throughout the day I will read everyone's responses and sometimes respond with my own follow-up questions.

Please be i request to provide the code in objective c

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

A: I think you may be slightly confused about
 tags.
 or
 are self-closing/void elements/empty tags:
https://www.w3schools.com/html/html_elements.asp (under the empty html section)
http://xahlee.info/js/html5_non-closing_tag.html

 is an empty element without a closing tag (the
 tag defines a line break):

So when you're subbing in

 you're actually subbing in two line breaks.  From your description it sounds as if you only want one line break, so you'll want to remove one of them.


Q: Regex search causes VS-Code to crash on macbook I'm trying to search for a RegEx expression using VS-Code's built-in search option.
Here is the regex: (?:((\s|\w+|\d+|\]|\))+)(?<!(\bReact\b))(?<dot>\.(?!\.))+)
As soon as I enter this expression, VS-Code crashes on my macbook.
Is there any way to prevent this?

A: You have (?<dot>\.(?!\.))+) a named capturing group in your regex.  I don't believe that is supported in vscode search across files.
In any case, your original regex froze vscode on my Windows machine, but when I removed the named capturing group, the regex worked fine in BOTH the find in a file widget and searching across files.  So this did not freeze vscode for me:
(?:((\s|\w+|\d+|\]|\))+)(?<!(\bReact\b))(\.(?!\.))+)

I suggest you replace the named capturing group with just a simple capturing group.


Q: Where to put my xUnit tests for an F# assembly? I'm working on my first 'real' F# assembly, and trying to do things right.
I've managed to get xUnit working too, but currently my test module is inside the same assembly. This bothers me a bit, because it means I'll be shipping an assembly where nearly half the code (and 80% of the API) is test methods.
What is the 'right' way to do this? If I put the tests in another assembly, I think that means I have to expose internals that I'd rather keep private.
I know that in C# there is a friend mechanism for tests (if that's the right terminology), is there an equivalent in F#?
Alternatively, can anyone point me to an example project where this is being done 'properly'?

A: you could use the InternalsVisibleTo-Attribute to expose your internals to some other assembly.
http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(VS.100).aspx
EDIT
If your assembly is signed, you will also need to sign the Friend assembly, and provide the public key in the InternalsVisibleTo attribute:
[<assembly: InternalsVisibleTo("ProcessorTests, PublicKey=0024000004800...)")>]


Q: Read & Write files from Input to Output folders: Python I have written a Python script that reads one file, replaces text, & then outputs it into another file. Instead, I would like to call an input FOLDER that contains multiple files, read these files, & then output them into a destination FOLDER. How would I approach this?
Here is my code:
import re

with open("SanitizedFinal_E4300.txt", "rt") as fin:
with open("output6.txt", "wt") as fout:

for line in fin:
    line = line.replace('set system host-name EX4300', 'hostname "EX4300"')
    line = line.replace('set interfaces ge-0/0/0 unit 0 family inet address', 'ip address')

    line = re.sub(r'set interfaces ge-0/0/0 description (.*)', r'interface 1/1\nname "\1"', line)
    line = re.sub(r'set interfaces ge-0/0/1 description (.*)', r'interface 1/2\nname "\1"', line)
    #and so on...

fout.write(line)

I am using Visual Studio Code v1.63.2

A: You can use os.scandir() to iterate over files in a directory:
import re, os

for file in os.scandir(input_dir):
    with open(file, "r") as fin, open("path_to_output_dir/" + output_file_name, "w") as fout:
        # whatever file operations you want to do
        for line in fin:
            fout.write(line)

A: Read all files in the folder through the OS module, read the contents of each file, and then modify it.
import os
fileList = os.listdir(path)
for info in os.listdir(path):
    domain = os.path.abspath(path) #Get folder path
    info = os.path.join(domain,info) #Combining the path with the file name is the full path of each file
    info = open(info,'r') #Read file contents
    #You can modify the file here
    info.close()


Q: Date Sorting in Java The Instruction was to create a Random dates for each object withn the range specified in the instructions below for the interview slot objects to be stored in . I am not exactly sure how to do this
Create a random number of  InterviewSlot objects and store them in the slots container.
Use the Math.random() method to create variation in the objects created:

*

*Make the range of variation of the dates in hours.

*The range should be 30 days, meaning that the dates could vary between
say, today and 30 days from now. The max of the range would be equal
to 30*24.

*You can set the minimum of the range to 1.

*Make the duration vary between 1 and 60.

Examples of objects:
Thu Apr 02 05:28:59 EDT 2020 duration:18
Fri Mar 27 00:22:32 EDT 2020 duration:48
Wed Apr 01 20:22:32 EDT 2020 duration:8
Sat Mar 28 19:22:32 EDT 2020 duration:31

import java.util.Calendar;
import java.util.Date;

public class InterviewSlot implements Comparable<InterviewSlot> {

    Calendar cal = Calendar.getInstance();
    private Date startTime = cal.getTime();
    private Integer duration;

    public InterviewSlot(Date start, Integer d) {
        setDuration(d);
        setStartTime(start);

    }

    public void setDuration(Integer duration) {
        this.duration = duration;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    public Integer getDuration() {
        return duration;
    }

    public Date getStartTime() {
        return startTime;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "Interview Start " + getStartTime() + "Duration :  " + getDuration();
    }

    @Override

    public int compareTo(InterviewSlot s) {
        return this.getStartTime().compareTo(s.getStartTime());
        // TODO Auto-generated method stub

    }

}

import java.awt.List;
import java.util.ArrayList;

public class DataCreator {

    public static <E extends Comparable<E>> void outputData(ArrayList<E> l) {
        for (E L : l) {
            System.out.println(L);
        }

    }

    public static void createIntegers(ArrayList<Integer> a, int num) {
        // double random = (int)(Math.random()*((100-1)+1))+1;
        for (int i = 0; i < num; i++) {
            Integer random = (int) (Math.random() * ((100 - 1) + 1)) + 1;
            a.add(random);

        }

        ;
    }

    public static void createData(ArrayList<InterviewSlot> slots, int num) {

    }

}

A: I will answer as if this is for real work, as you did not indicate explicitly schoolwork.
ThreadLocalRandom
Use ThreadLocalRandom to avoid any possible concurrency issues. There is no downside to using this class over Math.random. And this class has convenient methods for generating various types of numbers rather than just double.
java.time
Never use Calendar or Date. Those terrible date-time classes were supplanted years ago by the modern java.time classes defined in JSR 310.
Get today's date.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;

Add random number of days within next 30 days.
int days = ThreadLocalRandom.current().nextInt( 1 , 31 ) ;
LocalDate localDate = today.plusDays( days ) ;

Days vary in length, such as 23, 24, 25, or other number of hours. So for your date in your zone, calculate maximum number of seconds.
ZonedDateTime start = localDate.atStartOfDay( z ) ;
ZonedDateTime stop = localDate.plusDays( 1 ).atStartOfDay( z ) ;
Duration d = Duration.between( start.toInstant() , stop.toInstant() ) ;
long seconds = d.toSeconds() ;  // In Java 9 and later. For Java 8, call `Duration::getSeconds`.

That count of seconds becomes the maximum for our length of day. From this we pick a random number of seconds.
long secondsIntoDay = ThreadLocalRandom.current().nextInt( 0 , seconds ) ;
ZonedDateTime zdt = start.plusSeconds( secondsIntoDay ) ;

Determine a random duration from 1 to 60 minutes for the elapsed time of each event.
int minutes = ThreadLocalRandom.current().nextInt( 1 , 61 ) ; // At least one minute, and less than 61 minutes.
Duration duration = Duration.ofMinutes( minutes ) ;

Define your public class InterviewSlot with two member fields: a ZonedDateTime and a Duration.

A: Simple solution with date for your spezific case, including an example:
import java.util.Date;
import java.util.Random;
import org.apache.commons.lang3.time.DateUtils;
public class SimpleDateGenerator {
    private static Random random = new Random();

    public static Date getRandomDate(Date start, long timerangeSeconds) {
        int randomTime = (int) Math.ceil(random.nextDouble() * timerangeSeconds);
        return DateUtils.addSeconds((Date) start.clone(), randomTime);
    }

    public static void main(String[] args) {
        Date now = new Date();
        System.out.println(now);
        for (int i = 0; i < 10; i++) {
            System.out.println(getRandomDate(now, 30 * 24 * 60 * 60));
        }

    }

}

main gives following (example) output:
Tue Mar 31 08:26:14 CEST 2020
Sun Apr 19 16:06:48 CEST 2020
Fri Apr 03 20:49:58 CEST 2020
Wed Apr 22 22:27:00 CEST 2020
Mon Apr 06 03:39:48 CEST 2020
Wed Apr 22 19:13:28 CEST 2020
Fri Apr 03 12:36:16 CEST 2020
Wed Apr 22 20:27:35 CEST 2020
Mon Apr 06 13:58:37 CEST 2020
Fri Apr 03 03:57:17 CEST 2020
Wed Apr 15 09:05:47 CEST 2020

A: As per @Basil Bourque suggestion the following code should do the trick :
import java.time.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

public static void main(String[] args) {
    int numberOfRandomDates = 10;
    ArrayList<InterviewSlot>  interviewSlotArrayList= new ArrayList<>();
    for (int i = 0; i< numberOfRandomDates ; i++) {
        InterviewSlot interviewSlot = calculateInterviewSlot();
        interviewSlotArrayList.add(interviewSlot);
        System.out.println(interviewSlot);
    }

    Collections.sort(interviewSlotArrayList);
    System.out.println("After sorting: \n");

    //Using lamda
    interviewSlotArrayList.forEach(element -> {
        System.out.println(element);
    });

    //or Using method reference
    interviewSlotArrayList.forEach(System.out::println);
  }

    public static InterviewSlot calculateInterviewSlot() {
        //Getting time zone id and setting local time according to the time zone
        ZoneId z = ZoneId.of("America/Montreal");
        LocalDate today = LocalDate.now(z);

        //Getting a random day between 1 and 31 and adding it to the current date
        int days = ThreadLocalRandom.current().nextInt(1, 31);
        LocalDate localDate = today.plusDays(days);

        //Getting start and end time of the day as per time zone.End time is taken as next day start time(24 hr)
        ZonedDateTime start = localDate.atStartOfDay(z);
        ZonedDateTime stop = localDate.plusDays(1).atStartOfDay(z);

        //Duration is taken which is the max duration for that time zone.
        Duration duration = Duration.between(start.toInstant(), stop.toInstant());
        long seconds = TimeUnit.SECONDS.convert(duration.toNanos(), TimeUnit.NANOSECONDS);

        //Calculating random no of seconds keeping the computed seconds as max seconds in the day
        long secondsIntoDay = ThreadLocalRandom.current().nextInt(0, Math.toIntExact(seconds));
        ZonedDateTime zonedDateTime = start.plusSeconds(secondsIntoDay);

        //Calculating random no of minutes for duration
        int minutes = ThreadLocalRandom.current().nextInt(1, 61);
        Duration durationMinutes = Duration.ofMinutes(minutes);

        return new InterviewSlot(zonedDateTime, durationMinutes);
    }
}

InterviewSlot.java :
public class InterviewSlot implements Comparable<InterviewSlot> {

    private ZonedDateTime startTime;
    private Duration duration;

    public InterviewSlot() {
    }

    public InterviewSlot(ZonedDateTime startTime, Duration duration) {
        this.startTime = startTime;
        this.duration = duration;
    }

    public ZonedDateTime getStartTime() {
        return startTime;
    }

    public void setStartTime(ZonedDateTime startTime) {
        this.startTime = startTime;
    }

    public Duration getDuration() {
        return duration;
    }

    public void setDuration(Duration duration) {
        this.duration = duration;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "Interview Start " + getStartTime() + " Duration :  " + getDuration();
    }

    @Override

    public int compareTo(InterviewSlot s) {
        return this.getStartTime().compareTo(s.getStartTime());
        // TODO Auto-generated method stub

    }

}

Generated sample output :
Interview Start 2020-04-24T02:16:09-04:00[America/Montreal] Duration :  PT12M
Interview Start 2020-04-04T20:58:43-04:00[America/Montreal] Duration :  PT38M
Interview Start 2020-04-25T00:09:12-04:00[America/Montreal] Duration :  PT31M
Interview Start 2020-04-03T20:26:01-04:00[America/Montreal] Duration :  PT22M
Interview Start 2020-04-06T03:48:29-04:00[America/Montreal] Duration :  PT45M
Interview Start 2020-04-15T07:56:32-04:00[America/Montreal] Duration :  PT34M
Interview Start 2020-04-21T09:25:15-04:00[America/Montreal] Duration :  PT44M
Interview Start 2020-04-30T18:33:40-04:00[America/Montreal] Duration :  PT52M
Interview Start 2020-04-16T07:12:54-04:00[America/Montreal] Duration :  PT14M
Interview Start 2020-04-24T17:02:48-04:00[America/Montreal] Duration :  PT50M


Q: Measure Theoretic Definition of a Random Variable I am struggling a little with the definition of a RV: Let $(\Omega,F),(\Omega',F')$ be two event spaces. Then every mapping: $X:\Omega \to\Omega'$ is a RV provided $X^{-1}A' \in F,~~~ \forall A' \in F'$.
So my understanding of this: Let $T:X \to Y$ and $S\subseteq Y$. $T^{-1}(S)$ is the preimage of S under T. Now, $T(T^{-1}(S)\subseteq S $ and not necessarily:$T(T^{-1}(S)= S $. However, in the case of a random variable, we must have equality.
Is this the correct way to think about it?

A: The underlying idea ( in very practical terms) is simple. Suppose you are a statistician working with some survey. Lets suppose the survey has some questions about age, but only ask the respondent to identify his age in some given intervals, like $[0,18), [18, 25), [25,34), \dots $. Lets forget the other questions. This questionnaire defines an "event space", your $(\Omega,F)$. The sigma algebra $F$ codifies all information which can be obtained from the questionnaire, so, for the age question (and for now we ignore all other questions), it will contain the interval $[18,25)$ but not other intervals like $[20,30)$, since from the information obtained by the questionnaire we cannot answer question like: do the respondents age belong to this interval or not? More generally, a set is an event (belongs to $F$) if and only if we can decide if a sample point belongs to that set or not.
Now, let us define random variables with values in the second event space, $(\Omega', F')$. As an example, take this to be the real line with the usual (Borel) sigma-algebra. Then, an (un-interesting) function which is not a random variable is $f: $"respondents age is a prime number", coding this as 1 if age is prime, 0 else. No, $f^{-1}(1)$ do not belong to $F$, so $f$ is not a random variable. The reason is simple, we cannot decide from the information in the questionnaire if the respondents age is prime or not!  No you can make more interesting examples yourself.
I saw this kind of introduction first in the very good book by Peter Whittle "Probability via expectation" (Springer).


Q: Aux und Output files in another directory puzzles TeXstudio I have configured my TeX runs to save all aux and output files into a 'temp' subdirectory using the 'output-directory' option of lualatex in TeXlive.
Everything works wonderful, Biber and Makeglossaries are running etc. The PDF also looks nice.
But TeXstudio displays a lot of errors and warnings (without them occurring in the logfile or being actually true). There are some "undefined control sequences", "no file *.acr" (from glossaries), "undefined references", "label(s) may have changed", "please (re)run biber" and so on.
As said, they only appear in TeXstudio, not in the log file. And all those references, the bibliography, the glossary and so on are perfect in the PDF.
I could just ignore them but then I miss the real warnings that I want to take care about since they are hidden between hundreds of wrong warnings.
Any ideas how to solve this?
For your insights, I run the following commands for compilation. $1 is the argument my bash script gets, meaning the master file name:
    # LuaLatex
    lualatex -synctex=1 -interaction=nonstopmode -output-directory=./temp --shell-escape $1
    # Biber
    cp ./general/literatur.bib ./temp/general
    biber ./temp/$1
    # Makeglossaries
    makeglossaries -d ./temp $1
    # LuaLatex
    lualatex -synctex=1 -interaction=nonstopmode -output-directory=./temp --shell-escape $1
    lualatex -synctex=1 -interaction=nonstopmode -output-directory=./temp --shell-escape $1

A: Ok, I could solve this by adding this specific './temp' directory to Settings -> Build -> Search Paths. Then the correct warnings are shown again, no additional clutter.
Adding txs:///view-log to my user command was necessary additionally in order to get the log file updates instead of loaded only the first time.


Q: Mutually Exclusive Events (or not) Suppose that P(A) = 0.42, P(B) = 0.38 and P(A U B) = 0.70. Are A and B mutually exclusive? Explain your answer.
Now from what I gather, mutually exclusive events are those that are not dependent upon one another, correct? If that's the case then they are not mutually exclusive since P(A) + P(B) does not equal P(A U B). If it was P(A U B) = 0.80 only then it would have been considered mutually exclusive. Correct?

A: "Mutually exclusive" and "independent" do not mean the same thing: they are different.
"Mutually exclusive events are those that are not dependent upon one another, correct?"
NO:
Two events are mutually exclusive if they cannot both occur. If we flip a coin, we get either a head, or a tail. We cannot get both. That is, the events are mutually exclusive.
Independent events are events where knowing the outcome of one doesn't change the probability of the other. Knowing that it's a sunny day doesn't tell me anything about the outcome of rolling a die. Those "events" are independent of one another.
When events are mutually exclusive, their probabilities add up to the probability that one event (or the other) occurs. In this case, if the $A$ and $B$ were mutually exclusive events, then you are correct, we would need for $P(A) + P(B) = 80$. But what we have, as you point out, is that $\,P(A)  + P(B) = 70\neq 80.\;$ So you're right that $A$ and $B$ are not mutually exclusive, and for the right reason - because $P(A) + P(B) \neq P(A\cup B)$ - though you want to be clear about the terminology you use.

A: No, mutually exclusive events are events that cannot occur simultaneously: they are disjoint. If $A$ and $B$ are disjoint, then $\Bbb P(A\cup B)=\Bbb P(A)+\Bbb P(B)=0.42+0.38=0.80$. That’s not the case here, so $A$ and $B$ are not mutually exclusive.
In other words, your calculations and probably your reasoning are correct, but your use of terminology is not: mutually exclusive does not mean independent.

A: You are correct in your second conjecture (about $0.80$), but not in your former. Events that are not dependent upon one another are called (appropriately enough) independent, while mutually exclusive events cannot both occur, so are certainly dependent on one another when neither event is "impossible" (since, if one happens, then the other is "impossible").

A: $A$ and $B$ are mutually exclusive if $P(A\cap B)=0$.
Now for arbitrary $A$ and $B$, $P(A\cup B)=P(A)+P(B)-P(A\cap B)$. This should give you what you need.


Q: UICollectionView showing scroll indicator for every section (header zIndex broken) When scrolling through my UICollectionView it's showing more than one scroll indicator. I've noticed there is a one for every section in the collection. See screenshot displaying three at the same time:

Anyone experienced same issue? I am using Xcode 9 beta 3. My collectionview setup is quite common:
private let formCollectionView: UICollectionView = {
        let collectionViewLayout = UICollectionViewFlowLayout()
        collectionViewLayout.minimumLineSpacing = 0
        collectionViewLayout.minimumInteritemSpacing = 0
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.backgroundColor = UIColor.clear
        return collectionView
}()

Edit 10/16/2017
Even Twitter seems having this issue:

A: Ok, so first of all there is a radar already.
There is a proposed workaround. I was partially successful with doing this crap inside my UICollectionReusableView subclass.
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
    super.apply(layoutAttributes)
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.01) {
        self.layer.zPosition = 0
    }
}

I am saying partially because if you have a little bit longer UICollectionView it's still corrupted for some headers. Most of them are ok though. So it depends on your situation. Hopefully that radar will be addressed soon.

A: you can fix this problem in delegate method.as in the following example
Objective-C
- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath
    {
        if (@available(iOS 11.0, *)) {
            if ([elementKind isEqualToString:UICollectionElementKindSectionHeader]) {
                view.layer.zPosition = 0;
            }
        }
    }

Swift
func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
    if elementKind == UICollectionView.elementKindSectionHeader {
        view.layer.zPosition = 0
    }
}

A: That are not multiple scroll indicators. The z index of the header views is higher than that of the scroll indicator view.
Edit: found something more interesting, if you run the view debugger the scroll indicator is positioned above the headers... something weird is going on.

A: There is a simple method to fix this problem. In your section header view Class, you can override method layoutSubviews, and write:
- (void)layoutSubviews {
    [super layoutSubviews];
    self.layer.zPosition = 0;
}

Because, before iOS11, the section view's layer zPosition value is default 0, but in iOS11, this default value is 1.


Q: Store application config variables to database Is there any PHP open source class that can store application configuration variables in MySQL database, like Wordpress for example?
I would like to store and read something like this:
$config['name'] = "test1";
$config['name']['subname'] = "test2";

in MySQL database table, and database table need to look something like this
Id | Name      | Value   | Parent Name Id |
1  | 'name'    | 'test1' | null           |
2  | 'subname' | 'test2' | 1              |

etc.

A: That need not have a class style.
For example:
//config.php

    $config['name'] = "test1";
    $config['name']['subname'] = "test2";

//other php.

    require_once('{path to config.php}');
    echo $config['name'];
    echo $config['name']['subname'];


Q: How to index a table with order by? Using a while loop I'm able to return my table in the order I want, but after implementing pagination the variable I've created (counter) resets itself on each page, frustratingly.  Example code:
$sql = ('SELECT id,name,logo FROM mytable ORDER BY name DESC LIMIT 25');
$query = mysqli_query($db_conx,$sql);
$counter = 0;

while ($row = $query->fetch_assoc()) {
    $counter++;
    echo "$counter, $row['id'], $row['name']";
    echo "
";
}

I've tried many things and can't get this to work.  Obviously my logic is flawed.  The loop returns the correct results, but the $counter variable breaks on each page, resetting itself indefinitely.
What I am trying to do is get $counter to increase by 25 (representing results for each page) for each of the pages created by the pagination loop.  Example code:
for ($i=1; $i<=$total_pages; $i++) {
    echo "&nbsp[".$i."] ";
    $GLOBALS["counter"]+=25;
};

Obviously this was not working, so I am stumped at what I should try next.  If anyone has any ideas I would love to hear them, I have heard great things about the SO community.

A: You seem to display only the first 25 results at any time.
You need to initialize $counter to zero if it's the first page, to 26 if it's the second page, and so on :
$counter = 0;
if(isset($_GET['counter'])){
    $counter = intval($_GET['counter']);
}

You need to modify your query to fetch a different set of results for each page :
$sql = 'SELECT id,name,logo FROM mytable ORDER BY name DESC LIMIT ' . mysqli_real_escape_string($db_conx, $counter . ',25');
$query = mysqli_query($db_conx,$sql);

Then I assume you display a link to the other paginated pages, you need to pass it the value of $counter :
<a href="results.php?counter=<?php echo $counter;?>">Next


Q: Balls with replacement I have a simple question on drawing balls with replacement.
There are 20 red balls, and 10 blue balls, and it is interest in the event that {BBR} where order doesn't matter.
So P(BBR)=10/30*10/30*20/30.    Now, does the event {BBR} consist of: drawingBBR +drawingBRB+drawing RBB (these draws are with order), or do they not include?
If they included, then P(BBR)=3*(10/30)(10/30)(20/30)

A: Yes you are right with your answer.
Since the probabilities of the events are independent of each other the result is product of each probabilities of the events.


Q: How do I address imbalanced data before training? Suppose that we want to train YOLOV3. We gathered around 5000 images for 3 different classes. Class distribution is:
Class#1 = 2250  images
Class #2= 2500  images
Class #3= 250   images

As you can see it is imbalanced and I can not train based on that data. What do I need to do? do I need to consider a data processing stage?
Please do not merely say data augmentation, as data augmentation has a different meaning. I believe it does rotation and transformation during the training and makes the trained model more robust, it doesn't solve an imbalanced data set issue.
How do I address imbalanced data?

A: You can try to do the following to your config file:
Choice 1:
[yolo]
focal_loss=1

Choice 2 (more effective):
[yolo]
counters_per_class=100, 2000, 300, ... # number of objects per class in your Training dataset

To calculate the counters_per_class, refer to this link
More details here
Choice 3: Do both Choice 1 & Choice 2

A: for yolov7, you can :

*

*Adjust the focal loss with the parameter : h['fl_gamma']


Q: Exactly once delivery option for a pubsub subscription is not available for some reason I am unable to select the 'Exactly once delivery' option for my pubsub push subscription. No where on the internet does it explain why it is greyed out. (See below)

Tried finding answeres everywhere, looked into docs as well but no luck.

A: Looks like they only allow this feature for the 'pull' option.

A: More information about Cloud Pub/Sub Exactly Once Delivery and Push Subscriptions: https://cloud.google.com/pubsub/docs/exactly-once-delivery#exactly-once_delivery_and_push_subscriptions.


Q: Installing Microsoft Office 2010 on Wine 1.4
Possible Duplicate:
MS Word will not install: “pol_error”

Microsoft Office 2010 Professional Plus will not install because of windows codecs. I need help on installing dotnet20, msxml6 and corefonts using winetricks. It says it cannot validate or find the checksum. Please help me. I got this from this article.

A: I never had a problem installing Microsoft Office because I used PlayOnLinux.  It manages Wine versions and has installation scripts similar to wine tricks or Cross Over.
I think for the most part Libre Office does everything MS Office does, but I understand some times you need to install it.
Hope this helps.


Q: laravel: can not accept post request without csrf I have added into the exceptions:
    protected $except = [
        'pay/finish'
    ];

But still I am getting MethodNotAllowedException
Route is defined in web.php
Route::post('/pay/finish', ['as' => 'pay.finish', 'uses' => 'PaymentController@finish']);

The post request comes from another domain.

A: You don't normally get a MethodNotAllowedException from an invalid CSRF token. I normally get a 419 response from CSRF issues.
However, assuming the CSRF token is the problem you could move your route from web.php to api.php. Be aware this adds the prefix api/ to the URL.
The middleware that checks the CSRF token is applied in your Kernel to all routes in web.php but not to those is api.php
You could verify whether the CSRF check is really the problem by looking in your App\Http\Kernel file and commenting out \App\Http\Middleware\VerifyCsrfToken::class from:
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

If your route then works it is CSRF and you can move the route to the API routes file and hit it at api/pay/finish with the api prefix.
If not then I suggest you look at what's calling your route and check the correct http method is being called. Is it definitely sending a POST request?
Do you have the _method input specified in your form that Laravel checks for POST requests to mutate them to PUT or PATCH for its edit routes?


Q: Trouble linking assembly program: File format not recognized I have the following simple assembly program (downloaded from this website).:
        extern  printf          ; the C function, to be called

        section .data           ; Data section, initialized variables
msg:    db "Hello world", 0     ; C string needs 0
fmt:    db "%s", 10, 0          ; The printf format, "\n",'0'

        section .text           ; Code section.

        global main             ; the standard gcc entry point
main:                           ; the program label for the entry point
        push    rbp             ; set up stack frame, must be alligned

        mov rdi,fmt
        mov rsi,msg
        mov rax,0               ; or can be  xor  rax,rax
        call    printf          ; Call C function

        pop rbp                 ; restore stack

        mov rax,0               ; normal, no error, return value
        ret                     ; return

When I try to build from the command line using NASM I get no errors, and it creates the object file correctly. Then I link it using Mingw-w64 (ld) (because I am on a x64 machine) with command line option -m i368pe, but this fails with an error message: File format not recognized. After searching a bit, I found that this has to do with the fact that there I am trying to link a 32 bit object file with a 64 bit linker or the other way around. However, this does not make sense to me as I built the object file with the -f win64 flag. Also, I believe -m i386pe is a 64 bit flag for linking, so what am I doing wrong here?
My commands for building/linking are:

*

*Build: nasm -f win64 -o test.obj test.asm

*Link: ld test.obj -m i386pe -o test.exe


Q: A parallelogram and a circle The perimeter of a parallelogram $ABCD$ is $30$ $cm$. If $D$ and $M$ which is the midpoint of $\overline{DC}$ lie on the circle with diameter $\overline{AB}$, what is the perimeter of $ABMD$?

We know that $\overline{AB}\parallel \overline{CD}$ since $ABCD$ is a parallelogram, so as $DM\in CD,$ then $\overline{AB}\parallel \overline{DM}$. $M\ne C$ so $\overline{BM}$ cannot be parallel to $\overline{AD}$ which makes the quadrilateral $ABMD$ a trapezoid. Even more, since $A,B,M,D$ lie on $k$, the trapezoid is inscribed, so $\overline{AD}=\overline{BM}$. We have $$AO=BO=\dfrac12AB=\dfrac12CD=DM=CM.$$ What else? Thank you in advance!

A: Since $\overline{DM}$ is congruent to the radius of the circle, $\triangle DMO$ is equilateral.  By symmetry, $\angle AOD\cong\angle BOM$, so those are both $60^\circ$ and the other two triangles inside the circle must be equilateral as well.
Therefore, each of the six line segments that comprise the perimeter of the triangle are congruent, so each has measure $\frac16\cdot30\text{cm}=5\text{cm}$.  Since the trapezoid is made of five such congruent segments, its perimeter is $25\text{cm}$.

A: Along diameter AB of 2 units ( each side of equilateral triangle unit= 5 ) the circle construction gives a trapezium . It comprises three equilateral triangles.
By drawing the two parallels the angle enclosed at C is $60^{\circ}$. In the new situation (top half of regular hexagon ) six units are replaced by five units so reducing perimeter to $ 5\times 5=25.$


Q: How to manage large product catalog in magento? I am looking for a website Like coverscart.com using Magento. I have 2000 mobile covers for 500 model. I am trying to create configurable products, But it's not reliable solutions. Because for every model I have to create 2000 simple products.
With Configurable Total Catalog 1000000 :: 2000 Covers * 500 Model = 1000000
It's not about the creating products, It's about managing the large product catalog. Ref:: http://take.ms/goYoE
Any ideas?
Thanks!

A: In Magento 2 provide the functionality of auto created a number of associated product base on selected attributes.
Like First, you have created one attribute for mobile model, Then you have wanted, enter 500 Model name only one time. Then after you have want to create one configurable product then select model attributes >> then click on Select All menu for all selected models >> Then create a configurable product.
Note: automatically created 500 simple (associated) product. Please see screenshot. http://prntscr.com/knsqxl
Please check the example demo : http://blankrefer.com/?http://demo-acm2.bird.eu/admin


Q: Implement Iterator interface for ArrayAccess without container array This is my attempt at implementing https://www.php.net/manual/en/class.iterator.php for an ArrayAccess. Many examples use a container array as a private member variable; but I do not want to use a container array if possible. The main reason why I don't want a container array is because I'd like to access the property (array key) like this $DomainData->domainId all while having intellisense, etc.
Demo: https://ideone.com/KLPwwY
class DomainData implements ArrayAccess, Iterator
{
    private $position = 0;
    public $domainId;
    public $color;

    public function __construct($data = array())
    {
        $this->position = 0;
        foreach ($data as $key => $value) {
            $this[$key] = $value;
        }
    }

    public function offsetExists($offset)
    {
        return isset($this->$offset);
    }

    public function offsetSet($offset, $value)
    {
        $this->$offset = $value;
    }

    public function offsetGet($offset)
    {
        return $this->$offset;
    }

    public function offsetUnset($offset)
    {
        $this->$offset = null;
    }

    /*****************************************************************/
    /*                     Iterator Implementation                   */
    /*****************************************************************/

    public function rewind()
    {
        $this->position = 0;
    }

    public function current()
    {
        return $this[$this->position];
    }

    public function key()
    {
        return $this->position;
    }

    public function next()
    {
        ++$this->position;
    }

    public function valid()
    {
        return isset($this[$this->position]);
    }
}

Calling it:
$domainData = new DomainData([
    "domainId" => 1,
    "color" => "red"
]);

var_dump($domainData);

foreach($domainData as $k => $v){
    var_dump("domainData[$k] = $v");
}

actual:
object(DomainData)#1 (3) {
  ["position":"DomainData":private]=>
  int(0)
  ["domainId"]=>
  int(1)
  ["color"]=>
  string(3) "red"
}

desired:
object(DomainData)#1 (3) {
  ["position":"DomainData":private]=>
  int(0)
  ["domainId"]=>
  int(1)
  ["color"]=>
  string(3) "red"
}
string(24) "domainData[domainId] = 1"
string(23) "domainData[color] = red"

A: Let me describe a couple of ways of how you could do this.
ArrayObject with custom code
ArrayObject implements all of the interfaces that you want.
class DomainData extends ArrayObject
{
  public $domainId;
  public $color;

  public function __construct($data = array())
  {
    parent::__construct($data);
    foreach ($data as $key => $value) {
      $this->$key = $value;
    }
  }
}

This isn't very nice, though; it copies the keys and values twice, and changing a property doesn't change the underlying array.
Implement IteratorAggregate on get_object_vars()
If you don't mind giving up on ArrayAccess, you could get away with only implementing an aggregate iterator.
class DomainData implements IteratorAggregate
{
    public $domainId;
    public $color;

    public function __construct($data = [])
    {
        foreach ($data as $key => $value) {
            $this->$key = $value;
        }
    }

    public function getIterator()
    {
        return new ArrayIterator(get_object_vars($this));
    }
}

ArrayObject with property flag and doc blocks
A better way would be to use doc blocks for describing your properties (described here), and then use the ARRAY_AS_PROPS flag to expose the array as properties.
/**
 * Magic class
 * @property int $domainId
 * @property string $color
 */
class DomainData extends ArrayObject
{
  function __construct($data = []) {
    parent::__construct($data, parent::ARRAY_AS_PROPS);
  }
}

When loaded inside PhpStorm, you'd see this:

A: Please try get_object_vars() php function to Gets the accessible non-static properties of the given object according to scope.
The function adds before foreach loop. It's working.
$domainData = get_object_vars($domainData);
foreach($domainData as $k => $v){
    var_dump("domainData[$k] = $v");
}

=> Output
string(24) "domainData[domainId] = 1"
string(23) "domainData[color] = red"

A: Implement Iterator interface for ArrayAccess for example
<?php

/**
 * Class Collection
 * @noinspection PhpUnused
 */
class Collection implements ArrayAccess, IteratorAggregate, JsonSerializable, Countable
{
    /**
     * @var array $collection
     */
    private array  $collection;

    /**
     * @inheritDoc
     */
    public function offsetExists($offset): bool
    {
        return isset($this->collection[$offset]);
    }

    /**
     * @inheritDoc
     */
    public function offsetGet($offset)
    {
        return $this->collection[$offset];
    }

    /**
     * @inheritDoc
     */
    public function offsetSet($offset, $value)
    {
        if (empty($offset)) {
            return $this->collection[] = $value;
        }

       return $this->collection[$offset] = $value;

    }

    /**
     * @inheritDoc
     */
    public function offsetUnset($offset): void
    {
        unset($this->collection[$offset]);
    }

    /**
     * @inheritDoc
     */
    public function jsonSerialize()
    {
        return serialize($this->collection);
    }

    /**
     * @inheritDoc
     */
    public function count()
    {
        return count($this->collection);
    }

    /**
     * @return array
     */
    public function __debugInfo()
    {
        return $this->collection;
    }

    /**
     * @return mixed
     */
    public function first()
    {
        return $this->collection[0];
    }

    /**
     * @inheritDoc
     */
    public function getIterator()
    {
        return new ArrayIterator($this->collection);
    }

    /** @noinspection MagicMethodsValidityInspection */
    public function __toString()
    {
        return json_encode($this->collection, JSON_THROW_ON_ERROR, 512);
    }

    /**
     * @return mixed
     */
    public function last()
    {
        return $this->collection[$this->count()-1];
    }

}

for example using
<?php

$collections = new Collection();

$collections[] =12;

$collections[] = 14;
$collections[] = 145;
$collections[] =4;

print_r($collections);

echo $collections;

echo $collections->last();

echo $collections->first();

foreach ($collections as $collection)
{
    echo $collection;
}

count($collections);


Q: Having problems with aligning layers with body background I'm creating a layered parallax page that is triggered by the scrolling of the mouse. I've managed to set this up and the layers all move how I want them to. Unfortunately, I've run into a problem with the background image of the body. On the left side of the screen, there is a gap that shows the background behind it.
Gap that shows the background:

I've tried many different solutions but none of them seems to work. Any suggestions will be greatly appreciated.
here's the snippet of my HTML that involves the section with the layers

Moon Light

and here's a snippet of the CSS
{
    margin: 0;
    padding: 0;
    box-sixing: border-box;
    overflow-x: hidden;
    scroll-behavior: smooth;

    }

body {
    min-height: 100vh;
    overflow-x: hidden;
    background: linear-gradient(#2b1055,#7597de);
}

section {
    position: relative;
    width: 100%;
    height: 100vh;
    padding: 100px;
    overflow-x: hidden;
    overflow-y: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
}

section img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    pointer-events: none;

}

A: I would structure the first two selectors like this:
html, body {
    margin: 0;
    padding: 0;
    overflow-x: hidden;
    box-sizing: border-box; /* put these last two in a 'html {}' only selector if they are intended to be different */
    scroll-behavior: smooth;
}

body {
    min-height: 100vh;
    background: linear-gradient(#2b1055,#7597de);
}

Btw, changed the type-o of box-sixing to the right property :). Never used that one before, will come very handy, thanks.


Q: Render collection using a partial giving "undefined method for nil:NilClass" I'm trying to render a collection of Projects using a project partial but I'm getting the following error:
undefined method `customer' for nil:NilClass
Extracted source (around line #1):
1:
<%= company_name(@project) %>

The stacktrace is:
app/helpers/projects_helper.rb:4:in `company_name'
app/views/projects/_summary.html.erb:1:in
app/views/customers/index.html.erb:11:in

So, my index checks that their are projects to start with:
<% if @projects.any? %>
  <%= render :partial => "projects/summary", :collection => @projects %>
<% end %>

My partial (_summary.html.erb) is simply:

<%= company_name(@project) %>

<%= summary_description(@project) %>

and my ProjectsHelper company_name method is
def company_name(project)
  if project.customer.business_name.blank?
  ...Do stuff...

If I do the following via the rails console, it works fine:
projects.first.customer.business_name.blank?

I'm really confused because I thought that's what rendering a collection was supposed to do. Any help would be much appreciated.

A: You should change your partial to

<%= company_name(project) %>

<%= summary_description(project) %>

See the Rails documentation about this under "Rendering Collections".

A: I figured out what the problem was.
It was because I was using a differently-named partial to the model I was trying to render. I needed to just render a summary of the model, so I used a summary partial. In the partial though, the "name" of my project variable was "summary". So I changed my partial to:

<%= company_name(summary) %>

<%= summary_description(summary) %>

and it worked. Rails is still a mystery to me with stuff like this. From this post, the answer is to use: :as => :foo
<%= render :partial => "projects/summary", :collection => @projects, :as => :project %>


Q: Running into issues with django/vue (and possibly livereload) So I've got a Django/Vue project I'm trying to get off the ground. It's currently being pretty inconsistent. (I was able to get Vue to generate some things, but not others)
I first got Vue working, but upon realizing I would need to wipe browser history, I followed these instructions pretty much to the letter: https://github.com/tjwalch/django-livereload-server
Although it was unclear that one needed to spawn a new session and run both livereload and runserver concurrently, I eventually figured it out and got rid of the following warnings.
GET http://127.0.0.1:32657/livereload.js net::ERR_CONNECTIONREFUSED

But Vue is inconsistent. Something simple:

{{ title }}


Q: Flask sidebar shows up at the top, not on the side I am writing a simple Flask app, and I want a sidebar to always be present.  I tried using the template below, but for some reason the sidebar appears at the top, not on the left-hand side where I want it.  Here's what it looks like:

and here's what I want it to look like:

Here's the code I tried:

   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

 <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                    Start Bootstrap

                Dashboard

                Shortcuts

Results

Topics

Result1

Result2

Result3

Result4

Could someone please help?

A: Add these styles
#wrapper {
  display: flex;
}

h2 {
  margin: 0 !important;
}

#wrapper {
  display: flex;
}

h2 {
  margin: 0 !important;
}

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

  <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                Start Bootstrap

          Dashboard

          Shortcuts

Results

Topics

Result1

Result2

Result3

Result4

          Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1
          Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1
          Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1
          Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content

          Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2
          Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2
          Result2 Result2 Result2 Result2 Result2

          Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3
          Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3
          Result3

          Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4
          Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result
          4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4


Q: How to remove Local Storage in another JS file From below case, can someone help me to know how to remove localStorage which i have implemented below :
var serverSelectorDemo = function() {

         loadrightdata();
            function loadrightdata() {
                $('#kt_datatable_fetch_display2').html(localStorage.rightdata);
            };

        $('#kt_datatable2').on('click','tr button', function() {

           var id = $(this).data('id');
            $.ajax({
            type: 'post',
            url: 'src/khu-pusat/compare/right-side/right-value.php',
            data: {
                'rowid': id
            },
            success: function(data) {
            $('#kt_datatable_nodata2').addClass('hidden');
            localStorage.rightdata = data;
             $('#kt_datatable_fetch_display2').html(localStorage.rightdata);
             return false;
            }
        });
    }).click(function() {
        $('#kt_datatable_fetch_display2').empty();
    });
    };

So far I can't find a way that can do this.


Q: Timeout a function in JavaScript/jQuery I've got the following problem:
I'm using Google Maps on my site. I've attached the following eventListener to the map itself:
google.maps.event.addListener(map, 'bounds_changed', scheduleDelayedCallback);

The event bounds_changed is called every time someone drags the map. My Problem is, that it is called several times during the drag process. Now I need to find a way to call the callback function only, if it wasn't called during the last, let's say, 750 milliseconds.
I did this using these two functions:
function fireIfLastEvent() {
    var now = new Date().getTime();
    if (lastEvent.getTime() + 750 <= now) {
        this_function_needs_to_be_delayed();
    } else {
        $("#main").html('Lade...');
    }
}

function scheduleDelayedCallback() {
    lastEvent = new Date();
    setTimeout(fireIfLastEvent, 750);
}

This method works great in Chrome and Opera. In IE it works sometimes, in Firefox it never works (it calls the functions even if the 750 milliseconds haven passed).
Is there any rock-solid way to timeout a function call?
Thanks.

A: You shouldn't need a timeout here.
function scheduleDelayedCallback() {

    var now = new Date();

    if (now.getTime() - lastEvent.getTime() >= 750) {
        // minimum time has passed, go ahead and update or whatever
        $("#main").html('Lade...');
        // reset your reference time
        lastEvent = now;
    }
    else {
        this_function_needs_to_be_delayed(); // don't know what this is.
    }
}

Your explanation of what you want to happen isn't the clearest so let me know if the flow is wrong.


Q: Matricial form of the killing form of $\mathfrak{sl}(n)$ I was reading some of my old notes and I found an explicit matricial form for the killing form
$$
\left(\kappa_{ij}\right)=\left(\begin{array}{cccccccc}
4n\\
 & \ddots\\
 &  & 4n\\
 &  &  & 0 & 2n\\
 &  &  & 2n & 0\\
 &  &  &  &  & \ddots\\
 &  &  &  &  &  & 0 & 2n\\
 &  &  &  &  &  & 2n & 0
\end{array}\right),
$$
where the number of $4n$ equals the dimension of the cartan sub-algebra. I'm wondering if there are other explicit form for the killing form and why I don't see them written in every textbook if there are?

A: Bourbaki's Lie groups and Lie algebras contains, at the end of the 8th chapter, a table concerning the classical Lie algebras (the four families $A_n$, $B_n$, $C_n$, and $D_n$), wich contains explicit descriptions of the restriction (as a bilinear form) of the Killing form to a Cartan subalgebra.


Q: Connection refused error with selenium running in docker While trying nto dockerise selenium End2End tests using the selenium docker image 'selenium/standalone' i get the error : Error retrieving a new session from the selenium server Connection refused! Is selenium server started?
ye selenium server starts up according to the console output..any ideas ?
FROM selenium/standalone-chrome
USER root
# installing node
RUN apt-get update
RUN apt-get install -y curl
RUN curl -sL https://deb.nodesource.com/setup_7.x | bash
RUN apt-get install -y nodejs
RUN node -v
RUN npm -v
# Installing Yarn
#RUN rm -r /usr/local/bin/yarn
RUN npm install -g -y yarn
ENV PATH $PATH:/usr/local/bin/yarn
#copying files
WORKDIR /app
COPY . .
# debug
RUN ls -alh .
#installing yarn
RUN yarn install
EXPOSE 4444
RUN yarn
CMD yarn test

A: The problem is your approach of solving this. See you are inheriting your image from selenium/standalone-chrome which is supposed to run a Selenium browser. Now is this image you are adding your tests and specifying the CMD to run the tests.
When you build and launch this image, you don't get any browser because the CMD has been overridden by you to run the test. When we build in docker we keep dependent services in different containers. It is preferred to run 1 service/process per container in most case. In your case when the test is run the browser server process is missing, so that is the reason for connection refused.
So you need to be running two containers here. One for selenium/standalone-chrome and one for your test.
Also your image should inherit from node: and not from selenium chrome image. You should not have node -v and npm -v commands also while building images. They create extra layers in your final image
FROM node:7
USER root
# installing node
RUN apt-get update && apt-get install -y curl
# Installing Yarn
RUN npm install -g -y yarn
ENV PATH $PATH:/usr/local/bin/yarn
#copying files
WORKDIR /app
COPY . .
# debug
#installing yarn
RUN yarn install
RUN yarn
CMD yarn test

Now you need to create a docker-compose file to run a composition which has both your test and chrome
version: '3'
services:
  chrome:
    image: selenium/standalone-chrome
  tests:
    build: .
    depends_on:
      - chrome

Install docker-compose and run docker-compose up command to run the above composition. Also in your tests make sure to use the URL as http://chrome:4444/wd/hub and use the Remote webdriver and not the local driver.

A: i used a selenium/node-chrome image, but what resolved it was making sure my chromedriver + selenium server + nightwatch were set to the latest versions in my package.json


Q: Deactivate checkbox if a condition in a text input is true in javascript I've several text inputs and an checkbox array.
If the value of the text input is less than 6 deactivate the checkbox.
I tried this but the checkbox is always enabled.

        ALGEBRA
        5.62

            <input type="text" id="1" name="1" onkeydown="return validarnumero(event)" onkeypress="return compruebacampo(event,this)" onkeyup="desactivacasillas(event)">

            <input type="hidden" name="carga[0]" id="checkbox1" value="0">
            <input type="checkbox" name="carga[0]" id="checkbox1" value="5.62">

Can you tell me please what I'm doing wrong?

A: Make the IDs unique. Here is the below I tried and worked

        ALGEBRA
        5.62

            <input type="text" id="1" name="1" value="6" onkeydown="return

validarnumero(event)" onkeypress="return compruebacampo(event,this)"

onkeyup="desactivacasillas(event)">

            <input type="hidden" name="carga[0]" id="checkbox1" value="0">
            <input type="checkbox" name="carga[0]" id="checkbox2" value="5.62">

A: Try this
  <!DOCTYPE html>

 ALGEBRA
 5.62

     <input type="text" id="1" name="1" onkeyup="desactivacasillas(this.value)">

     <input type="hidden" name="carga[0]" id="checkbox1" value="0">
    <input type="checkbox" name="carga[0]" id="checkbox2" value="5.62">

Feel free to ask anything if you don't understand the above program.

A: Try this. Use on load function in java script to disable check box while loading. and use parse Int function because input returns value as string.
change the ID's of check boxes. ID's are always Unique.

            ALGEBRA
            5.62

                <input type="text" id="1" name="1" onkeyup="desactivacasillas(event)">

                <input type="hidden" name="carga[0]" id="checkbox1" value="0">
                <input type="checkbox" name="carga[0]" id="checkbox2" value="5.62">


Q: Set a variable in url using php and mysql I need to set two variable in a url, $id and $job. The data should come from mysql select statement, [id] and [job_number_id]. My page displays a client job proposal and if there is more than one all proposals are displayed but the [id] and the [job_number_id] determines what is displayed on the webpage. I dont have a clue as to how this done. Any help would be greatly appreciated. Here's the code:
<?php

$url = 'http://localhost/estimate_lar/homepage.php';
$id = $_SESSION['id'];

$query =    "SELECT id, client_job_name, job_number_id
            FROM `job_name`
            WHERE `id`='$id'";
$allJobs = $db->query($query);

?>

<?php foreach ($allJobs as $site_title) : ?>

<?php echo ''.$site_title['client_job_name'],$site_title['job_number_id']. '
'.''; ?>

<?php endforeach; ?>

A: If you want the variables to be avaialble in the URL you need to read them with $_GET.
Getting the arguements from a url such as index.php?id=1&job_number_id=3 will look like that:
if (isset($_GET['id']) && isset($_GET['job_number_id'])) {//make sure both arguments are set
    $id = $_GET['id'];
    $job_number_id = $_GET['job_number_id'];
}

To set it in your foreach statement:
<?php foreach ($allJobs as $site_title) : ?>

<?php

$url = "http://localhost/estimate_lar/homepage.php?id=" . $site_title['id'] . "&job_number_id=" . $site_title['job_number_id'];

echo ''.$site_title['client_job_name'],$site_title['job_number_id']. '
'.'';

    ?>

<?php endforeach; ?>

PLEASE remember to read about SQL injection and making sure you are escaping your inputs. Or even better - use a prepared statement.
Currently your script is volunerable, since everyone could just alter the URL and manipluate your DB.
Hope this helps!

A: Try this.
<?php
session_start();
$id = $_SESSION['id'];
$url = 'http://localhost/estimate_lar/homepage.php';
if($id){

$query =    "SELECT id, client_job_name, job_number_id  FROM `job_name`  WHERE `id`='$id'";
$allJobs = $db->query($query);

}else{
echo "Id not in session";
}
?>

<?php if ($allJobs)  { foreach ($allJobs as $site_title) : ?>

 <a href="<?php echo $url; ?>?client_job_name=<?php echo $site_title['client_job_name'];?>&job_number_id=<?php echo $site_title['job_number_id'];?> "> <?php echo $site_title['job_number_id']. " ".$site_title['job_number_id']; ?>

<?php endforeach; ?>

 <?php }else{ echo 'No results Found' ;} ?>

This may help you.


Q: Google DoubleClickStudio - video source file After creating a creative banner with an mp4 video in Google Web Designer and then upload that creative to DoubleClick the source file has changed from mp4 to webm. The issue here is that webm in Safari is pixelated and the creative/ad is not shown properly, while on other browsers its ok. Is there a setting in DoubleClickStudio to prevent it from transcoding the mp4 video and use the default mp4 instead ?
...1630672923/mv/u/mvi/1/pl/24/file/file.webm


Q: AX88179 Ethernet Adapter drops connection after idling I have a 2017 MacBook Pro (Touchbar) running macOS Monterey 12.5
I've connected a StarTech USB-C dongle that comes with USB-A ports and a Ethernet port to this MacBook. The Ethernet controller on the dongle is a ASIX AX88179 for which I have installed the drivers and as long as I connect it to a specific USB port on the MacBook, the Ethernet connection is recognized and works correctly.
However, I'm having this strange problem where if I'm using the MacBook for a while and then let it idle, the Ethernet connection gets disabled. Once I start using the MacBook again, after 30 seconds or so the Ethernet connection seems to "wake up" and starts working again.
Things I have tried without any success:

*

*Create a new location in System Preferences>Network and ensure the Ethernet adapter is the first entry.

*Ensure that in System Preferences>Battery>Power Adapter, the option to "wake for network access" is checked and the option to "Prevent your Mac from sleeping automatically when the display is off" is also checked.

Any suggestions on how I can debug this issue further or any known solutions would be very welcome!


Q: How to create Exception and pass AggregateException as inner exception? Imagine this scenario:
Task.Run(() =>
    {
        // code...
    }).ContinueWith(x =>
    {
        var betterEx = new Exception("My custom message", x.Exception));
    }
    , TaskContinuationOptions.OnlyOnFaulted);

However, the betterEx.InnerException returns null.
Question
How can I create a new Exception and pass AggregateException as the inner exception? I want to make sure all the info in the aggregate is persisted and not lost.


Q: How to test if your REST API service supports gzip data? I am testing a REST API service that supports json and gzip data. I have tested the response from the json request payload. How to test if it handles gzip data properly? Please help?
Basically the client sends a request with accept-encoding as gzip in the header, service handles the compression and the client takes care of the decompression. But I need a way to confirm that service indeed handles compressed gzip data

A: gzip is basically a header + deflate + a checksum.
Gatling will retain the original Content-Encoding response header so you can check if the payload was gzipped, and then trust the gzip codec to do the checksum verification and throw an error if the payload was malformed.


Q: Uncaught (in promise) TypeError of webpart on reload After using the command "gulp package-solution --ship" I read the solution in the AppCatalog and add the webpart to the home page. When I start the first time it loads correctly, when I refresh the page it fails and says: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'web'), what can I do?
I have two webparts that work the same way, but while this one gives an error, the other one works fine.

EDIT 26/11:
the error is in _sp.web, does anyone know why?
export default class ProvaLinks extends React.Component<ProvaLinksProps, {}> {
  public render(): React.ReactElement<ProvaLinksProps> {
    const {
      environmentMessage,
      listName,
      color
    } = this.props;

    return (
      <div>
        <ButtonsLinks listName={""} environmentMessage={''} color={color}
           siteUrl={''} description={''} isDarkTheme={false}
           userDisplayName={''} hasTeamsContext={false} />
      </div>
    );
  }
}

const ButtonsLinks = ({color}: IMyVgiButtonsLinksProps) => {
  const _sp: SPFI = getSP();
  let readItems: IMyVgiButtonsLinks[] = [];
  const [itemsListProva, setItemsItemsListProva] = useState(readItems);

  useEffect(() => {
    getItemProva("ListaProva");

    itemsListProva([]);
  }, []);

async function getItemProva (ListName: string) {
    let itemsList: any[] = [];
        itemsListProva = await
            _sp.web.lists.getByTitle(ListName).items.filter("Enable ne'" +
           false + "'").orderBy("Order")();

      itemsList.forEach((e) => {
        readItems.push({
          Title: e.Title,
          URL: e.MyVgiURL.Url,
          ID: e.ID,
          ButtonType: e.ButtonType,
          ButtonImage: e.ButtonImage,
          Order: e.Order,
          Enable: e.Enable,
          });
      });
      setItemsListProva(readItems);
  }


Q: Jquery Deferred for an async function I have been reading a lot about JQuery's deferred object.  And I can see how it works to de-couple code.   I wrote this orignally using Async.js but would was recommended to use promise.
Most examples I find just chain things to AJAX calls.  I want to chain an async function but can't figure out how to do it.  I am retrieving a time from the database then using that time as a parameter in a url, finally I would then like to make a AJAX call.
This is where I'm at:
    var fetch = function (contactId, callback, errorCallback)
    {
        var buildPromise = new $.Deferred();

        var getLastImportTime = function ()
        {
            var querySuccess = function (tx, result)
            {
                buildPromise.resolve("7 oclock");
            };

            var queryError = function (tx, e)
            {
                buildPromise.reject("Error querying database");
            };

            database.open();
            database.query("SELECT EventImportTime FROM Contact WHERE Contact.Id = ?", [contactId], querySuccess, queryError);
        };

        var buildUrl = function (lastImportTime)
        {
            console.log("I do happen");
            var url = "http://";
            url += 'MobileGetChangedEvents.aspx?Reference=';
            url += '&LastImportTime=';
            url +=  lastImportTime;
            url += '&Format=JSON';
                            return url;

        };

        var makeRequest = function (url)
        {
            getJSON(url, callback, errorCallback)
        };

        $.when(getLastImportTime()).pipe(buildUrl).then(makeRequest);

Also my pipe methods seems to be called first :s

A: since you pass getLastImportTime function to when helper method, it should explicitly return a promise, (but in getLastImportTime() you are returning nothing and when() is expecting you to pass a promise) otherwise the helper could evaluate it as an immediate resolved (or rejected) promise.
This could explain why it seems that function in pipe is executed before getLastImportTime()
So try to change your function like so
var getLastImportTime = function () {
   ...
   database.open();
   database.query("SELECT  ...");

   return buildPromise.promise();
};


Q: PostgreSQL: Optimizing bulk INSERT INTO/SELECT FROM In my Postgresql schema I have a jobs table and an accounts table. Once a day I need to schedule a job for each account by inserting a row per account into the jobs table. This can done using a simple INSERT INTO.. SELECT FROM statement, but is there any empirical way I can know if I am straining my DB by this bulk insert and whether I should chunk the inserts instead?
Postgres often does miraculous work so I have no idea if bulk inserting 500k records at a time is better than 100 x 5k, for example. The bulk insert works today but can take minutes to complete.
One additional data point: the jobs table has a uniqueness constraint on account ID, so this statement includes an ON CONFLICT clause too.

A: In PostgreSQL, it doesn't matter how many rows you modify in a single transaction, so it is preferable to do everything in a single statement so that you don't end up with half the work done in case of a failure. The only consideration is that transactions should not take too long, but if that happens once a day, it is no problem.


Q: XML mapping to objects without attributes in C# Is there a C# library that allows mapping C# objects to XML without Attributes?
I have several data sources, all of them containing XML data with the same logical-structure, but different schema. For example in one XML there might be a field called 'zip-code', in another this data will be in attribute called 'postal-code' etc. I want to deserialize all XML sources in single C# class.
Obviously I can not use XMLAttrubtes, because there are different 'paths'. I want something like EclipseLink MOXy (metadata is specified in XML), but for C#.

A: The XmlSerializer allows you to specify attribute overrides dynamically at runtime. Let's suppose that you have the following static class:
public class Foo
{
    public string Bar { get; set; }
}

and the following XML:
<?xml version="1.0" encoding="utf-8" ?>
<foo bar="baz" />

you could dynamically add the mapping at runtime without using any static attributes on your model class. Just like this:
using System;
using System.Xml;
using System.Xml.Serialization;

public class Foo
{
    public string Bar { get; set; }
}

class Program
{
    static void Main()
    {
        var overrides = new XmlAttributeOverrides();
        overrides.Add(typeof(Foo), new XmlAttributes { XmlRoot = new XmlRootAttribute("foo") });
        overrides.Add(typeof(Foo), "Bar", new XmlAttributes { XmlAttribute = new XmlAttributeAttribute("bar") });
        var serializer = new XmlSerializer(typeof(Foo), overrides);
        using (var reader = XmlReader.Create("test.xml"))
        {
            var foo = (Foo)serializer.Deserialize(reader);
            Console.WriteLine(foo.Bar);
        }
    }
}

Now all that's left for you is to write some custom code that might read an XML file containing the attribute overrides and building an instance of XmlAttributeOverrides from it at runtime that you will feed to the XmlSerializer constructor.


Q: How to connect to tables and display their content? (MySQL and PHP) I have two mysql tables (products and categories). I have some mock data in both tables. Now I need to somehow attach the categories to the products. For example - The product witht he ID 1 should return the following:
| product name | category   |
| Monitor      | Technology |

I know I have done this bevore, but today I simply can't seem to find the solution to this.
EDIT
This is waht I have so far. The connection works well and I can display the data in a Table.
<?php
// Include database connection
include("connection.php");

// Create variables for later use
$db = $conn;
$tableName = "Produkte";
$columns= ['id_product', 'name_product'];

// Create variable to use in index.php
$fetchData = fetch_data($db, $tableName, $columns);

// The function below feteches data from the tables specified and checks if the colums are emtpy by any chance.
function fetch_data($db, $tableName, $columns) {
    // Check db connection
    if (empty($db)) {
        $message= "Database connection error";
    }
    // Check if the columns variable is empty and not an array by any chance
    elseif (empty($columns) || !is_array($columns)) {
        $message="Product Name must be defined in an indexed array";
    }
    // Check if table name is empty
    elseif (empty($tableName)) {
        $message= "Table Name is empty";
    }
    // Else proceed as usual.
    else {
        $columnName = implode(", ", $columns);
        // The query needs to be repalced. Today my SQL stuff is leaving me a bit.
        $query = "SELECT p.".$columnName." AS product, c.name_category FROM $tableName p JOIN Kategorie c ON c.id_";
        $result = $db->query($query);
        if ($result== true) {
            if ($result->num_rows > 0) {
                $row= mysqli_fetch_all($result, MYSQLI_ASSOC);
                $message= $row;
            }
            else {
                $message= "No Data Found";
            }
        }
        // Throw error if error occures
        else{
            $message= mysqli_error($db);
        }
    }
    return $message;
}

The table products has only 2 columns. An id column and a product_name column.

A: It's vary basic technics:
// create DBquery using JOIN statement
$query = "
SELECT
    p.name AS product, c.name AS category
FROM products p
JOIN categories c ON c.id = p.category_id;";

// get DB data using PDO
$stmt = $pdo->prepare($query);
$stmt->execute();

// show table header
printf('| product name | category   |' . PHP_EOL);

// loop for output result as table rows
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    printf('| %-12s | %10s |' . PHP_EOL, $row['product'], $row['category']);
}

Try online


Q: React Native bottom tab navigator - Android screen reader only selects tab label and not tab icon as well I have a bottom tab navigator from react navigation.
Previously, when you had the screen reader on, both the text and the icon of each tab could be selected as one container.
Here we see both the icon and label being selected as one container for the screen reader
After upgrading to RN 0.69 from 0.68, only the text in the tab bar is selectable. How can I make both the icon and text selectable as one container? If I add an accessibility label to the tab bar icon, the whole container can be selected again, but that requires that we add a label.

A: You can make a custom tab bar and add accessibility as you wish in each tab bar item like this:
<Tab.Navigator tabBar={(props) => <CustomTabBar/>}>
    <Tab.Screen .../>
</Tab.Navigator>

A: Thank you guys for responding. Really appreciate it!
I hadn't done the correct research. In the documentation , it says that theres is a prop which you can add to the whole tab bar.
https://reactnavigation.org/docs/bottom-tab-navigator/#tabbaraccessibilitylabel
After adding this, the container (both the tab icon and text) was selectable as one container. It is just strange that this behaviour worked before without adding that prop.


Q: using CASE WHEN in SQL Statement I have to display information by comparing data in two ID columns, one column has 'ALL' and numbers as ID's while the other has only numbers in it as  ID's. My problem is, I cannot compare character and number columns with a number column. So I am using CASE WHEN.
If the value is 'ALL' then display 'ALL' in the output, else display name for the matching records.
Here is the code:
CASE
  WHEN secorg.org_id = 'ALL' THEN 'ALL'
  WHEN secorg.org_id = progmap.org_id THEN secorg.org_name
END AS org_name,

the condition is this: 'secorg.org_id = progmap.org_id' which is based on the id and I have to display secorg.org_name if the id's are same.
Here is the entire query:
SELECT distinct program_id,
                prog_name,
                case
                  when Eitc_Active_Switch = '1' then 'ON'
                  when Eitc_Active_Switch = '0'then 'OFF'
                End as Prog_Status,
                progmap.client_id,
                case
                  when secorg.org_id = 'ALL' then 'ALL'
                  --when secorg.org_id = progmap.org_id then secorg.org_name
                  else secorg.org_name
                end as org_name,
                case
                  when prog.has_post_calc_screen = 'True' then 'True'
                  Else 'False'
                End as Referal_ID,
                case
                  when progmap.program_ID IN ( 'AMC1931', 'AMCABD', 'AMCMNMI',
                                               'AMC' )
                       And sec.calwinexists_ind = '1' then 'Yes'
                  when progmap.program_ID IN ( 'AMC1931', 'AMCABD', 'AMCMNMI',
                                               'AMC' )
                       And sec.calwinexists_ind = '0'then 'No'
                  when progmap.program_ID NOT IN (
                       'AMC1931', 'AMCABD', 'AMCMNMI', 'AMC' ) then
                  'N/A'
                End as calwin_interface,
                sec.Client_name
FROM   ref_programs prog (nolock)
       LEFT OUTER JOIN ref_county_program_map progmap (nolock)
         ON progmap.program_id = prog.prog_id
            AND progmap.CLIENT_ID = prog.CLIENT_ID
       INNER join sec_clients sec (nolock)
         on sec.client_id = progmap.Client_id
       Inner join sec_organization secorg (nolock)
         on secorg.org_id = progmap.org_id

A: Why not cast the number columns to varchar columns?
If you're using SQL SERVER you can do that like so:
CONVERT(VARCHAR,secorg.org_id) = CONVERT(VARCHAR,progmap.org_id)

You'll have to do an outer join for instances when the column that is both 'ALL' and numbers is 'All' as it won't be able to inner join to the other table.
For the quick fix based on your code above you can just change the second WHEN clause to look like so (again assuming you're using MS SQL SERVER):
WHEN CONVERT(VARCHAR,secorg.org_id) = CONVERT(VARCHAR,progmap.org_id) THEN secorg.org_name

Try this as your query:
SELECT DISTINCT
    program_id,
    prog_name,
    CASE Eitc_Active_Switch
        WHEN '1' THEN 'ON'
        ELSE 'OFF'
    END AS Prog_Status,
    progmap.client_id,
    ISNULL(secorg.org_name,'ALL') AS org_name,
    CASE prog.has_post_calc_screen
        WHEN 'True' THEN 'True'
        ELSE 'False'
    END AS Referal_ID,
    CASE WHEN progmap.program_ID IN ('AMC1931','AMCABD','AMCMNMI','AMC') AND sec.calwinexists_ind = '1' THEN
        'Yes'
        WHEN progmap.program_ID IN ('AMC1931','AMCABD','AMCMNMI','AMC') AND sec.calwinexists_ind = '0' THEN
        'No'
        WHEN progmap.program_ID NOT IN ('AMC1931','AMCABD','AMCMNMI','AMC') THEN
        'N/A'
    END AS calwin_interface,
    sec.Client_name
FROM
    ref_programs prog (nolock)
LEFT OUTER JOIN ref_county_program_map progmap (nolock) ON progmap.program_id = prog.prog_id AND progmap.CLIENT_ID = prog.CLIENT_ID
INNER JOIN sec_clients sec (nolock) ON sec.client_id = progmap.Client_id
LEFT OUTER JOIN sec_organization secorg (nolock) ON CONVERT(VARCHAR,secorg.org_id) = CONVERT(VARCHAR,progmap.org_id)

A: The case statement is fine its the field alias thats bad it shoud be
     END As org_name

A multipart alias like secorg.org_name won't work


Q: Word 2010 - Coversheets We have created standard coversheets for several projects. These coversheets are exchanged on standard documents to make it client specific.
The font type of these coversheets is Arial.
It seems that standard format roled out at Word instal is Courier New with Paragraph setting 10 pt after and 1.5 line size.
This is causing problems. Is there a method where the coversheet format can be maintained while the remainder of the documents (or new documents) can be based on the standards as set by Office ?


Q: Multiple locks locking the same functions C# .Net I have a simple question about lock.
Are Process1 and Process2 the same because they are eventually locking the LongProcess?
Thank you.
private static readonly object _Locker = new object();
public void Process1()
{
    lock(_LockerA){
        LongProcess()
    }
}

public void Process2()
{
    if(curType == A)
        ProcessTypeA();
    else if(curtype == B)
        ProcessTypeB();
}

private static readonly object _LockerA = new object();
public void ProcessTypeA()
{
    lock(_LockerA){
        LongProcess()
    }
}

private static readonly object _LockerB = new object();
public void ProcessTypeB()
{
    lock(_LockerB){
        LongProcess()
    }
}

public void LongProcess()
{
}

A: No, they are not the same. If you lock against a different object than an already existing lock, then both code paths will be allowed. So, in the case of Process2 curtype == 'b' the lock is using the _LockerB object. If one of the other locks using the _LockerA object is attempted, then they will be allowed to enter the LongProcess.

A: Process1 and Process2 have the potential to lock the same object, but they are definitely not the same. Locks on the same object are however allowed (I think, rarely if ever had to do it) within the same call stack (also referred to as recursive locking in the case where Process1 invokes Process2). This could likely be better described as dependent locking.
Your question is however fairly vague so you'll have to elaborate on what you mean by the same...