window.location.replace is always undefined

Question: I have a ajax post that I need to redirect to redirect url on success.
In the browser debugger I do c the correct url but I'm always getting "MYURL/undefined".
$.ajax({
        type: 'POST',
        url: "/NewsLetter/Create",
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        data: data,

        success: function(result) { //debug >result={urlOne:'https://localhost:7077'}
            //  alert('Successfully received Data ');

            if (result.UrlOne !== undefined) {
                window.location.replace(result.UrlOne);
            } else {
                window.location.replace(result.UrlTwo);
            }
            console.log(result);
        },
        error: function(error) {
            alert('Failed to receive the Data');
            console.log(JSON.stringify(error));
            console.log('Failed ');
        }
    });

In my controller:
if (ModelState.IsValid && isNewUser == null)
{
   //remove for clear code
    return Json(new { UrlOne = Url.ActionLink("Index","Home")});
}

TempData["ErrorMes"] = "You are allready register";
return Json(new { UrlTwo = Url.ActionLink("_RegNews", "NewsLetter") });

Comment: Have you checked what the values of `result.urlOne` and `result.urlTwo` are?
Comment: if i understand your Q.  then yes this are 2 valid url
Comment: @RoryMcCrossan how ever  window.location.replace('https://localhost:7077'); is also undefined" while paste it in the browser is a valid Url
Comment: Javascript is case sensitive, you use `urlOne` and `UrlOne` - they are not the same.!
Answer: Pass the JsonSerializerOptions as a parameter when creating the Json object to make property's name case-sensitive during deserialization. The JsonSerializerOptions has PropertyNameCaseInsensitive property that by default set to false. This will prevent the Json serializer to change names to be camel-cased.

var options = new System.Text.Json.JsonSerializerOptions();

if (ModelState.IsValid && isNewUser == null)
{
   //remove for clear code
    return Json(new { UrlOne = Url.ActionLink("Index","Home")}, options);
}

TempData["ErrorMes"] = "You are allready register";
return Json(new { UrlTwo = Url.ActionLink("_RegNews", "NewsLetter") }, options);

JsonSerializerOptions Class
Answer: Please check the return json from controller:

You will find that the key is urlOne instead of UrlOne.
Javascript is case sensitive, So you need to change your code like:
if (result.urlOne !== undefined) {
                    window.location.replace(result.urlOne);
                } else {
                    window.location.replace(result.urlTwo);
                }


Windows Hello for Business - Hybrid Azure Joined Devices - Off LAN enrolment behaviour

Question: Environment
Windows 10 Professional devices, Hybrid Azure AD Joined (physical)
Server 2019 DCs
AD Connect 1.5.45
Key Trust setup
Endpoint Manager used to deploy WHfB
CRL distribution point published to internal and external web servers
Verified CA and CA+.crl files are accessible from LAN and non LAN connected Windows 10 endpoints
Details
When the WHfB wizard runs for the first time and the user is off the LAN, the PIN setup completes without issue.
However once the user signs out or locks the screen the PIN code does not work
"Your credentials could not be verified" is displayed. This is also taking into account the 30 min sync back to AD Connect.
However, once the user reverts to using their password to sign in and then activates the VPN AND then locks the workstation whilst still connected, the PIN code will work for the unlock.
Subsequent use of the PIN will also work when the VPN is not connected, including PIN change and reset.
LAN based devices have no issue at all and WHfB works as expected.
Can any advise what is the correct workflow when enrolling off LAN?
Answer: What you're seeing is expected and by design:

In the above deployment model (Hybrid Azure AD join authentication using a Key), a newly provisioned user will not be able to sign in using Windows Hello for Business until (a) Azure AD Connect successfully synchronizes the public key to the on-premises Active Directory and (b) device has line of sight to the domain controller for the first time.

https://docs.microsoft.com/en-us/windows/security/identity-protection/hello-for-business/hello-how-it-works-authentication#hybrid-azure-ad-join-authentication-using-a-key
Comment: Thanks Noor, I will study that link you sent me. I understand the need to have line of of sight to the DCs now.

From what I can see, the TGT has be cached which appears to occur when the enrolled device locks the screen or logs out.

In both circumstances, the VPN must be in operation to achieve success.

Does this sound correct to you?
Comment: Yup, DC line of sight is required, you need to have VPN up and running at least for the first sign-in after the 30 minutes replica passes successfully.


Why the null hypothesis should always be written as an equality

Question: It is often stated that the null hypothesis should be written as an equality (see for example here), like for example $\mu_A-\mu_B=0$, while the alternative uses an inequality (for example, $\mu_B\gt\mu_A$). I think that this kind of null hypothesis is called "simple". My question is, why should we always prefer simple null hypotheses?
Suppose for example that I have an existing machine learning code A, and I develop a new code B, based on a different paradigm (maybe A is a neural network, while B is a random forest). I test A and B on some data. I can define an accuracy metric for the codes, thus for each test I can say whether A or B was more accurate. It seems extremely unlikely to expect that A and B could have the same average accuracy on the population from which the data are drawn. After all, they're completely different algorithms. Thus, a NH such as $H_0:p_A=p_B$ seems quite "unnatural" to me. Rather, since I want to know if new code is more accurate than the old one, I would try to falsify the NH that B is no more accurate than A, i.e., $H_0: p_B\le p_A$. Thus, the alternative would be $H_a:p_B\gt p_A$. Why is this kind of null not appropriate for testing?
I guess the issue is that with the "compound" null (is this the correct term?) I cannot easily find a distribution of a test statistics, and thus I may not be able to perform NHST. For example, in the two sample t-test, the null that the mean of the two samples is the same allows me to derive easily the distribution of the test statistics (mean is zero, and standard deviation is derived from sample standard deviation and number of samples). If instead I assume that one mean is larger than the other, then I don't know the parameters of the test statistics distribution. Is this correct?
Comment: I'd say that not everyone agrees with the premise of the.title. Some people certainly take that point of view in respect of the usual tests, but some don't.
Answer: There is nothing wrong with your proposed test.  It is possible to derive the sampling distribution of the null with a compound null.  What we do, in essence, is use the sampling distribution of the simple null, and if the truth were that $p_B\ll p_A$, then the rate of type I errors would be less than your stated alpha.
What you are getting at is called a non-inferiority test.  Here is a non-gated and practitioner-friendly paper:

Walker, E., & Nowacki, A. S. (2011). Understanding Equivalence and Noninferiority Testing. Journal of General Internal Medicine, 26(2), 192–196. http://doi.org/10.1007/s11606-010-1513-8

It may also help to read some of the existing threads on CV that are related to this topic.  I have provided somewhat related answers:

Why do statisticians say a non-significant result means "you can't reject the null" as opposed to accepting the null hypothesis?
Can a paired t-test test if the difference between two means is less than a specific value?

You can also read the threads categorized under the equivalence tag.

On an unrelated note, you should not use the t-test to compare the accuracy of two classifiers.  Since these are correct or incorrect, you would use some method appropriate for binary data, such as the z-test for two proportions.  However, since the classifiers will almost certainly be assessed using the same data, McNemar's test should be used (see my answer here: Compare classification performance of two heuristics).
Comment: Great answer, thanks! I will be sure to read your references. I didn't know about these concepts (noninferiority and equivalence testing). Concerning the McNemar's test, sure, that's the appropriate test in my specific case  (even though I often just use the z-test on the difference of proportions, since I have colossal samples). I was just considering two different examples (one being the comparison of accuracy between two classifiers, and other being the two sample t-test for unpaired data). That probably wasn't clear. But thanks for the pointer anyway!
Answer: If $H_0: p_A-p_B=0$ is not rejected with some significance level, then it doesn't imply that $p_A$ is exactly $p_B$ (this is very basic). It means that $0$ is in an interval around your observed test statistic. The two algorithms can be different but they can return values of some chosen loss function that are close from each other. This is reasonable. If you suspect that the algorithm B is at least as good as A's, you can test
$H_0:p_A=p_b$ against $H_1: p_A>p_B$. This is what most of staticians would do....


Where is "one"? How do you keep track?

Question: I recently watched a YouTube excerpt of Jack Feierman's master class in which he alludes to techniques that can be developed to know where "one" is.

He has a click going on the background — at 2:32 min he establishes where "one" is and moves on to talk about certain topics.
Then, at 3:17 min he nails "one". Then again, at 3:25 min. (just count along to see for yourself)
I find this to be an important skill to have, similar to perfect pitch.
Sadly, Feierman passed away shortly after and it appears his book "Where is One" was not published.
Do you have any insights on this topic or other sources to learn/develop this skill?
Comment: It's just counting.  Some part of him is still paying attention to the beat.
Comment: So, just to be clear - this question is not about finding the downbeat in a musical rhythm or part (like a typical drum rhythm), but just the skill of allowing your mind to keep track of where '1' has been previously *arbitrarily* decided to be in a  chain of identical pulses (like this metronome beat)?
Comment: yes, the focus is on "the skill of allowing your mind to keep track of where '1' has been previously arbitrarily decided to be in a chain of identical pulses"
Comment: He's spot on, but do we ever find out the secret. Even while talking, there's an inner rhythm happening, which is pretty impressive.
Comment: It's hard to tell whether there's 'anything to see here'; It's quite common to have to feel or count a beat consciously while doing something else; if he's really doing it 'subconsciously' and perfectly, that's impressive, but I'm not sure I'd expect delivering a lecture that he presumably knows well wouldn't necessarily distract him sufficiently that he wouldn't be able to to count or feel a beat in a fairly normal conscious way (especially just for less than one minute, between 2:32 and 3:17).
Answer: He´s a conductor and mentions conducting patterns so I think he is counting as well. At least that is the way I´m learning choir conducting and we are being taught to count with the conducting patterns. "One" has a clear emphasis. For me the counting is becoming like an internalized running commentary in the background of whatever else I´m trying to focus on. Without the "one" you´re lost. Watching the video I felt that that was what he was doing.
Comment: I see your point—but do you imply that he's multitasking at a high level? That is, that he can keep counting 1-2-3-4 while talking about something? If so, could you give suggestions on how this is practiced or developed?

Where is "one"? How do you keep track?


To_Date Function Migration from oracle to SQL Server

Question: I am migrating my oracle database to SQL Server. What is the easiest way to convert to_date functions? I have many sql which use to_date.
For example I have an update query. It contains following line.What can be solution to convert it to SQL Server 2008 with minimum effort?
Sample Query Line
LAST_LOGIN=to_date('" & m_LAST_LOGIN & "','DD.MM.YYYY HH24:MI:SS') ")

Answer: LAST_LOGIN = convert(datetime, m_LAST_LOGIN, 20)

You can find further information from
http://msdn.microsoft.com/en-us/library/aa226054(SQL.80).aspx
Comment: That will give a format of YYYY-MM-DD HH:MM:SS.mmmm, not what was requested. And the link to SQL 2000, not 2008. And in SQL, the variable woudl have been @LAST_LOGIN
Answer: This page contains useful conversion information. From what you've given, the following should suffice. (Used with getdate() as an example date)
declare @LAST_LOGIN varchar(21)
set @LAST_LOGIN = convert(varchar(10), getdate(), 104) + ' ' +convert(varchar(10), getdate(), 108)

There is nothing directly to convert it to the format you specify, so you have to concatenate the two conversions as shown above.


What am I missing for setting up firebase app check on ios and react native / expo?

Question: I'm sure I've set up the app in the firebase console.
I'm trying to set up app check for our ios app. I'm intending to use it to secure a functions call. I've verified that the function works when I don't throw an error on looking for the app check. However, I'm not seeing context.app.
I've added a sanity check by calling getToken on the mobile app and I'm running into the following error
NativeFirebaseError: [appCheck/token-error] The operation couldn't be completed. Too many attempts. Underlying error: The operation couldn't be completed. The server responded with an error:
 - URL: https://firebaseappcheck.googleapis.com/v1/projects/<Redacted>/apps/<Redacted>:exchangeDeviceCheckToken
 - HTTP status code: 400
 - Response body: {
  "error": {
    "code": 400,
    "message": "App not registered: <Redacted>.",
    "status": "FAILED_PRECONDITION"
  }
}

I've checked the firebase app check console and I have the following:

The appcheck console has this app registered with device check and app attest.
The device check configuration uses the p8 file I set up for device check in the apple developer portal.
The id that I redacted above is the id in the relevant google.plist file.

The only thing I'm not doing that's in the docs is setting up debug tokens, but my understanding is that's for CI and simulator environments. I'm testing on a physical device with an expo development build. Is there something I'm missing for set up?
Here is the init code I'm using
async function initiateAppCheckSecurity () {
    const provider = appCheck().newReactNativeFirebaseAppCheckProvider();
    await provider.configure({
        /** @todo set up android */
        apple: {
            provider: 'appAttestWithDeviceCheckFallback',
        },
    });
    await appCheck().initializeAppCheck({ provider, isTokenAutoRefreshEnabled: false });

    // sanity check
    const blah = await appCheck().getToken();
        // error thrown here.
    console.log({ blah });
}

Answer: I have had the same issue. I fixed by recreating a p8 file and follow this thread.
How do I overcome AppCheck failed on iOS 15.2 Firebase v8.11.0?
Answer: I don't particularly understand why this happened, but the issue resolved itself this morning and I did nothing with the project since I posted this. My guess is that there is some caching going on, but I didn't see anything in docs regarding it.
If someone finds a mention about this in the docs, I'll mark it as the correct answer.
Comment: They have some 24hrs cache which might be the issue.


Is it possible to determine the eigenvalues of this rather complicated matrix? How many eigenvalues are stable/ unstable?

Question: Without giving you the lengthy and really nasty computations, let $n\in\mathbb{N}$, $\beta(n):=\frac{n(n+1)(2n+1)}{6}$ and $\alpha(n):=\sqrt{1/\beta(n)}$. The $(n\times n)$-matrix $A(n)$ is then given by the following entries:
The first row of $A(n)$ is given by
\begin{align*}
       a_{1,i}=\frac{a(n)}{\beta(n)}\cdot\begin{cases}-\beta(n)-1, & i=1\\
        -1, & 2\leqslant i\leqslant n-1\\
        n^2+2n, & i=n
         \end{cases}
    \end{align*}
The last row is given by
\begin{align*}
        a_{n,i}=\frac{a(n)}{\beta(n)}\cdot\begin{cases}n(n^2+2n-\beta(n)), & i=n\\
        n(\beta(n)-1), & i=n-1\\
        -n, & \textrm{else}
        \end{cases}
    \end{align*}
    And, for $2\leqslant j\leqslant n-1$ and $1\leqslant i\leqslant n$, the entries are
    \begin{align*}
    a_{j,i}=\frac{a(n)}{\beta(n)}\cdot\begin{cases}-j(1+\beta(n)), & i=j\\
   j(\beta(n)-1), & i=j-1\\
    -j, & i=j+1<n\\
    n^3+n^2-2n, & i=j+1=n\\
    -j, & 1\leqslant i\leqslant j-2\\
    jn(n+2), & j+2\leqslant i=n\\
    -j, & j+2\leqslant i<n
    \end{cases}
\end{align*}
Question: Is there any chance to determine the eigenvalues of this matrix? Or, if not determining explicitly, is it possible to say how many of the eigenvalues are stable/ unstable?

I observe some similarities between the entries.
Let me illustrate this for $n=4$. Without computing the concrete values, the matrix is
$$
A(n)=\frac{\alpha(n)}{\beta(n)}\underbrace{\begin{pmatrix}
\color{green}{-(1+\beta(n))} & \color{red}{-1} & \color{red}{-1} & \color{magenta}{n(n+2)}\\
  \color{blue}{j(\beta(n)-1)} & \color{green}{-j(1+\beta(n))} & \color{red}{-j} & \color{magenta}{jn(n+2)}\\
\color{red}{-j} & \color{blue}{j(\beta(n)-1)} & \color{green}{-j(1+\beta(n))} & \color{magenta}{(n-1)n(n+2)}\\
\color{red}{-n} & \color{red}{-n} & \color{blue}{n(\beta(n)-1)} & n(n^2+2n-\beta(n))
\end{pmatrix}}_{=C(n)}
$$

The red entries are all of the form $-j$, where $j$ is the row.
The lower off-diagonal elements (blue) are all of the form $j(\beta(n)-1)$.
The diagonal entries in green are all of the form $-j(1+\beta(n))$.

The entries in the last column in magenta are all of the form $jn(n+2)$.

So the only entry which "marches to a different drummer" seems to be $c_{nn}$.
Maybe these observations are helpful to determine the eigenvalues of $C(n)$.
Maybe Laplace expansion? Maybe Gauss elimination?
Update (due to discussion in the comments)

In the meantime, it turned out that $\vec{c}(n):=(1,2,\ldots,n)$ is an eigenvector of $C(n)$ to the corresponding positive eigenvalue $\lambda=2\beta(n)$. So there exists at least one unstable eigenvalue.
Note also that $C(n)$ can be written as the product
$$
C(n)=\textrm{diag}(1,2,\ldots,n)\cdot C'(n),
$$
where $C'(n)$ is much easier than $C(n)$ because the row-dependent factor $j$ disappears. Maybe this is helpful.

For example, due to this product structure one might estimate the Gershgorin circles, as mentioned here.
Answer: EDIT : you can factorize the whole matrix by $6$, replacing $b(n)$ by $b(n)/6$ (which is an integer).
Well, I've tried writing off the matrix for $n=4$ (calculating the values after factorization), and get (if I'm correct)
$$\begin{pmatrix}-31&-1&-1&24\\58& -62 & -2& 48 \\ -3 & 87 & -93 & 72 \\ -4 & -4 & 116 & -24 \end{pmatrix}$$
for which WolframAlpha gave me the following eigenvalues : $(-120, -90, -60, 60)$. As you can see, only one is positive, so your intuition might happen to be true.
Actually, the eigenvector for the positive eigenvalue is $(1,2,3,4)$ so I wonder to which extent the vector $(1,\dots, n)$ can be an eigenvector for all $n$. Maybe it is only a happy coincidence, or maybe there is something deeper behind it.
I will try to edit this answer as soon as I get time to explore further. Please let met know if you advance somehow.
Comment: As you can see your matrix as a matrix multiplied to the left by $\text{diag}(1,\dots,n)$, maybe you should also look at https://mathoverflow.net/questions/120014/eigenvalues-of-a-diagonal-matrix-times-a-matrix
Comment: Matrix $D(n)$ will indeed be as you described it. Unfortunately, there are no direct connections between the eigenvalues of $D(n)$ and the ones of $C(n)$, except if they are both diagonalizable at the same time, which means that they have the same eigenvectors... Which seems not true.
Comment: If you only want the determinant of $C$, then yes, absolutely, you're right.
Comment: Indeed, $\vec{v}=(1,2,\ldots,n)$ is always an eigenvector of $C(n)$ and the corresponding eigenvalue is $\lambda=2n(1+n)(1+2n)$. So we have at least one positive (unstable) eigenvalue.
Comment: If I got this right, then since $C(n)=\textrm{diag}(1,2,\ldots,n)\cdot D(n)$ for some matrix $D(n)$, then it suffices to determine the eigenvalues of $D(n)$ (at least if one only wants to estimate the eigenvalues of $C(n)$). The advantage of the matrix $D(n)$ here is that all the diagonal entries (except for $d_{nn}$) are the same, all the subdiagonal elements are the same, all the entries in the last column (except for $d_{nn}$) are the same and all other entries are $-1$.
Comment: But isn't it true that the determinant is multiplicative, that is, $\textrm{det}(C)=\textrm{det}(\textrm{diag}(1,2,\ldots,n))\cdot\textrm{det}(D)$? And for the diagonal matrix the eigenvalues are clear.
Comment: It is; but the eigenvalues are given by the solutions of $\det(C-\lambda I) = 0$. As $C-\lambda I \neq (\text{diag}(\dots) -\lambda I)(D-\lambda I)$, the eigenvalues are not multiplicative.
Comment: I don't claim that the eigenvalues are multiplicative. But maybe it is easier to determine the determinant of C if one knows that of D. I dont know.


xsd validation fails with cvc-elt.1: Cannot find the declaration of element

Question: I am validating my xml using my xsd in java:
javax.xml.validation.SchemaFactory
.newInstance("http://www.w3.org/2001/XMLSchema")
.newSchema(new java.io.File(schemaPath))
.newValidator()
.validate(new javax.xml.transform.stream.StreamSource(new java.io.FileInputStream(xmlPath)));

and I get the following error:
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 18; cvc-elt.1: Deklaration des Elements "WrappedBodyText" kann nicht gefunden werden.

I reduced my xml to the following:
<WrappedBodyText></WrappedBodyText>

I reduced my xsd to:
<?xml version="1.0" encoding="UTF-8"?>
<schema targetNamespace="http://compa.ny/customer/schema/Wrapper"
        xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:Wrapper="http://compa.ny/customer/schema/Wrapper"
        xmlns:WrapperType="http://compa.ny/customer/schema/WrapperType"
        xmlns:standardservice="http://compa.ny/standard/service/schema">

    <complexType name="WrappedBodyText">
    </complexType>
</schema>

I looked through several posts here or on other forums, but none of the errors I found seem to apply. Please help
Answer: As far as I have understood it a single definition of a complexType is not enough. I had to define an element too:
<?xml version="1.0" encoding="UTF-8"?>
<schema targetNamespace="http://compa.ny/customer/schema/Wrapper"
        xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:Wrapper="http://compa.ny/customer/schema/Wrapper"
        xmlns:WrapperType="http://compa.ny/customer/schema/WrapperType"
        xmlns:standardservice="http://compa.ny/standard/service/schema">

    <complexType name="WrappedBodyText">
    </complexType>

    <element name="WrappedBodyText" type="Wrapper:WrappedBodyText"/>
</schema>

But there was also an error in my xml instance. The validator found an element WrappedBodyText with empty namespace, but was expecting an element in the defined targetNamespace. So I changed the xml instance too:
<WrappedBodyText xmlns="http://compa.ny/customer/schema/Wrapper"></WrappedBodyText>

I guess the combination of those two errors was the worst part about it.


How to inspect "multi-object" return type

Question: Is there a common reflection approach to find out whether java method returns a set of objects like array, list, set, collection and other iterable subinterfaces?
The story behind is that I need to inspect third-party method's return type and say two things:

Does method return set of objects (in
human sense)?
If yes - what is the component type?

For example if method's return type is Vector, A[], Set, etc, I want that A to be returned by my code.
I'm new to reflection/generics, don't want to re-invent the wheel and not sure my approach is correct. Here's what I've done so far:
  private boolean isMultiple(Class clazz) {
    return clazz.isArray() || Iterable.class.isAssignableFrom(clazz);
  }

  private Class getReturnComponentType(Method m) {
    Class clazz = m.getReturnType();
    if(!isMultiple(clazz)) return clazz; // Not a collection
    // Collection
    if(clazz.isArray()) {
      // How do I get Array's component type?
      // return null;
    } else {
      // How do I get Iterable component type?
      // return null;
    }
  }

Please help.
Answer:
To get Iterable component type: Besides getReturnType() also use getGenericReturnType() to get generic types. Then compare it to Type subinterfaces: GenericArrayType, ParameterizedType.
To get Array component type use clazz.getComponentType().
Comment: I'd say that then use Collection.class.isAssignableFrom() or Iterable.class.isAssignableFrom() or Class.isArray().
Comment: He already does this. Now he needs the type parameter (i.e. T in List)
Comment: thanks. I worried mostly about my isMultiple method, glad it's ok.


Windows Server 2012 & Exchange Server 2013 CAL's

Question: Trying to build an Exchange server solution for a company and they want me to look into licensing for Windows. I'm going to be purchasing the necessary server licenses for Windows Server 2012 Standard and Microsoft Exchange 2013 Enterprise. I just have a few questions about the CAL's thing which seems like a complete ripoff to me.
How are CAL's tracked for both Windows Server and Exchange? Is it tied to Active Directory profiles?
What happens if I dont have the necessary CAL's for Windows Server? Will a client be denied access from Active Directory? Is there any enforcement for this? Also the same question for Exchange 2013 CAL's
Thanks
Answer:
I just have a few questions about the CAL's thing which seems like a complete ripoff to me.

You're not going to get much sympathy for that here. It's how Microsoft chooses to license access to their products and as professional sysadmins, we do the professional thing and stay compliant with our licenses.

How are CAL's tracked for both Windows Server and Exchange?

Honor system, except for RDS CALs. Those are enforced.

Is it tied to Active Directory profiles?

No.

What happens if I dont have the necessary CAL's for Windows Server?

Then you hope that you are never part of a license audit.

Will a client be denied access from Active Directory?

No.

Is there any enforcement for this?

Microsoft and various licensing partners occasionally conduct licensing audits. If you are non-compliant, you are generally given a chance to "settle up." If you don't you risk fines and/or a lawsuit.

Also the same question for Exchange 2013 CAL's

Same as above.


Bad CentOS server performance with Digium T1/E1 TDM Card

Question: I have a PowerEdge 2850 server that used to work well under CentOS 5 i386. It was used with Asterisk as a telephony server, hooked up to the world via a T1 line.
I've since wiped it and installed CentOS 6 x86_64, and everything works well as long as you boot from the install media. As soon as you reboot from the installed image, things slow down to a crawl. It takes about a second for every letter typed on the local console to appear on screen. SSH access through the network is abysmally slow as well. Hard drive read speeds are around 0.5mbytes/s. Same thing happens on CentOS 6 i386. Updating the system using yum doesn't help.
A T1 line from a Cisco router is plugged into the T1/E1 card.
Answer: The problem is that the default CentOS configuration loads the netjet driver for the Digium card, and that driver is the root of the problem. This driver is not the right driver, it doesn't make any sense to use it with Digium telephony cards. As soon as you rmmod the driver, the system's performance recovers. One can turn the driver off in /etc/modprobe.d/blacklist.conf by adding the following line:
blacklist netjet

To use the card, you'll need to install dahdi-linux with appropriate driver package, and configure it for your card.


first order partial differential equation

Question: I have a first order PDE:
$$xu_x+(x+y)u_y=1$$
With the initial condition:
$$u(1,y)=y$$
I have calculated result in Mathematica:
$u(x,y)=\dfrac{y}{x}$ , but I am trying to solve the equation myself, but I had no luck so far. I tried with method of characteristics, but I could not get the correct results.
I would appreciate any help or maybe even whole procedure.
Thanks
Comment: The function $u$ which you call the final result does not solve the PDE.
Answer: There must be (at least) an error here, but I fail to see it:
General first order two variables PDE:
$$a(x,y)u_{x}(x,y)+b(x,y)u_{y}(x,y)+c(x,y)u(x,y)=f(x,y) $$
In this case
$a(x,y)=x$, $b(x,y)=(x+y)$, $c(x,y)=0$ and $f(x,y)=1$
Now we will find some $$\xi(x,y)=c $$
$c \in \mathbb{R}$ constant solves the differential equation
$$\frac{dy}{dx}=\frac{b(x,y)}{a(x,y)}=\frac{x+y}{x}=1+\frac{y}{x} $$
In order to solve this define a new function $$u(x)=\frac{y(x)}{x}$$ so that
$$\frac{du}{dx}=\frac{dy}{dx}\frac{1}{x}-\frac{y(x)}{x^2}=\left(1+u\right)\frac{1}{x}-\frac{u}{x}=1 $$
Hence $u(x)=x+c$, $\frac{y}{x}=x+c \rightarrow c=\frac{y}{x}-x$
$$\boxed{\xi(x,y)=\frac{y}{x}-x} \Rightarrow (\xi +x)x=y$$
Now let $u(x,y)=v(x,\xi)$ and take derivatives
$$u_{x}=v_{x}+v_{\xi}\left( -\frac{y}{x^2}-1\right) =v_{x}+\left( -\frac{(\xi+x)}{x}-1\right)v_{\xi}$$
$$ u_{y}=v_{\xi}\frac{1}{x}$$
Substitution into the PDE yields
$$ x\left( v_{x}+\left( -\frac{(\xi+x)}{x}-1\right)v_{\xi}\right)+(x+(\xi+x)x)v_{\xi}\frac{1}{x}=1$$
$$xv_{x}-(\xi+x)v_{\xi} -xv_{\xi}+v_{\xi}+\xi v_{\xi}+xv_{\xi}=1$$
$$v_{x}x+v_{\xi}(1-x)=1$$
Answer: $xu_x+(x+y)u_y=1$
$u_x+\left(\dfrac{y}{x}+1\right)u_y=\dfrac{1}{x}$
Follow the method in http://en.wikipedia.org/wiki/Method_of_characteristics#Example:
$\dfrac{dx}{dt}=1$ , letting $x(1)=1$ , we have $x=t$
$\dfrac{dy}{dt}=\dfrac{y}{x}+1=\dfrac{y}{t}+1$ , letting $y(1)=y_0$ , we have $y=y_0t+t\ln t=y_0x+x\ln x$
$\dfrac{du}{dt}=\dfrac{1}{x}=\dfrac{1}{t}$ , letting $u(1)=f(y_0)$ , we have $u(x,y)=\ln t+f(y_0)=\ln x+f\left(\dfrac{y}{x}-\ln x\right)$
$u(1,y)=y$ :
$f(y)=y$
$\therefore u(x,y)=\ln x+\dfrac{y}{x}-\ln x=\dfrac{y}{x}$
Answer: my answer   $\frac{dx}{x}=\frac{dy}{x+y}=\frac{du}{1}$
from first and third eqn.  $\frac{exp(u)}{x}=c_1$
from first and second eqn
$\frac{dy}{dx} -\frac{y}{x}=1$ which is first order ode and it can be easily solved  $\frac{y}{x}- ln x= c_2$
 parametrized initial curve C : x=1 , y=t , u=t
$u_1 =\frac{exp(u)}{x}$ and $u_2= \frac{y}{x}- ln x$ are two first integrals
on initial curve say u_1|C =U_1= exp t, u_2|C =U_2= t eliminating t we find U_1=exp U_2
come back U_1=u_1, U_2=u_1 we obtain u= y/x


given two concentric circles construct a particular chord

Question: I am stumped by another Euclidea problem - Euclidea problem 9.8:
Given two concentric circles $C_1$ and $C_2$ with radians $r_1$ and $r_2$, with  $r_1 < r_2 < 2 r_1 $
Construct the chord $e$ of $C_2$ intersecting $C_2$ at $A$ and $B$, $C_1$ at $D$ and $E$ such that $AD < AE$ and $ AD = DE = EB $
(so the chord is trisected by  $C_1$ )
Please only a hint
Answer: A hint, you say? Use the chord theorem at $D$.


Find the exact value of trigonometric expression: $ \arctan\frac{2\cos \frac{\pi}{30} \cos\frac{\pi}{15}}{1+2\cos \frac{\pi}{30} \sin\frac{\pi}{15}}$?

Question: How can I simplify this trigonometric expression?

$$  \arctan\frac{2\cos \frac{\pi}{30} \cos\frac{\pi}{15}}{1+2\cos \frac{\pi}{30} \sin\frac{\pi}{15}}$$

I used
$$\sin \frac{\pi}{15}=2 \sin \frac{\pi}{30}  \cos \frac{\pi}{30}$$ and $$\cos\frac{\pi}{15}=2\cos^2\frac{\pi}{30}-1$$
But these give me more complicated expressions.
Comment: @Elementary, I need more time & concentration which  I'm really sorry that I could not invest. I will be really happy to solve it. Thanks for the nice problem. Pray continue supplying such problems
Comment: What is the source of this uncommon problem?
Comment: I find the answer is $\dfrac{3\pi}{10}$ by wolfram alpha
Comment: Reminds me of https://math.stackexchange.com/questions/805023/how-to-prove-dfrac1-sin6-circ-cos12-circ-cos6-circ-sin12-circ
Comment: @labbhattacharjee  A contest math problem.(in the book) I could not solve.  (I tried for hours) WA can solve ,but unfortunately, doesnt show steps. So, I shared problem here.
Comment: @labbhattacharjee   Do you have any idea how to solve this problem? Do you think there is an elegant way?
Comment: @labbhattacharjee I'll just be happy, to learn from your wisdom..
Answer: $\begin{align}
T &= \large \left(\frac{2\cos 6° \cos 12°}{1\;+\;2\cos 6° \sin 12°}\right)
\left({2\sin 6° \over 2\sin 6°}\right)\cr
&= \large \frac{\sin 24°}{2\sin 6°+\;2\sin^2 12°}\cr\cr
{1\over T}&= \large \frac{2\sin(30°-24°)+\;(1-\cos 24°)}{\sin 24°}\cr
&=\large {(\cos 24° - \sqrt3\sin24°) + (1-\cos 24°) \over \sin 24°}\cr
&=\large{1\over\sin(60°-36°)} - \sqrt3 \cr
&=\large{4\over 2\sqrt3 \cos36° - 2\sin 36°}-\sqrt3 \cr
\end{align}$
From wikipedia on Golden triangle,
$\quad2\cos(36°)=\phi,\quad 2\sin(36°)=\sqrt{4-\phi^2}$
$\begin{align}
\large{1\over T}&=\left({4\over \sqrt3\phi-\sqrt{4-\phi^2}}\right)
\left({\sqrt3\phi+\sqrt{4-\phi^2} \over \sqrt3\phi+\sqrt{4-\phi^2}} \right)
-\sqrt3 \cr
&= {4(\sqrt3\phi + \sqrt{4-\phi^2}) \over 3\phi^2-(4-\phi^2)} -\sqrt3 \cr
&= {\sqrt3\phi + \sqrt{4-\phi^2} \over \phi^2-1}-\sqrt3 \cr
&= {\sqrt3\phi + \sqrt{4-\phi^2} \over \phi} -\sqrt3 \cr
&= {\sqrt{4-\phi^2} \over \phi} = \tan(36°)
\end{align}$
$$T = \tan(90°-36°) = \tan(54°)$$
Answer: Let $\arctan\left(\dfrac{2\cos6^\circ\cos12^\circ}{1+2\cos6^\circ\sin12^\circ}\right)=y,-90^\circ<y<90^\circ$
$\implies\dfrac{2\cos6^\circ\cos12^\circ}{1+2\cos6^\circ\sin12^\circ}=\tan y=\dfrac{\sin y}{\cos y}$
Rearranging we get $$\cos(6^\circ+y)+\cos(18^\circ+y)=\sin y=\cos(90^\circ-y)$$
$$\iff\cos(90^\circ-y)=\cos(18^\circ+y)+\cos(6^\circ+y)=2\cos6^\circ\cos(12^\circ+y)\ \ \ \  (1)$$
Like Solve equation $\tan(x)=\sec(42^\circ)+\sqrt{3}$
using Proving trigonometric equation $\cos(36^\circ) - \cos(72^\circ) = 1/2$
$$\cos36^\circ=\cos72^\circ+\cos60^\circ=2\cos6^\circ\cos66^\circ\ \ \ \  (2)$$
Compare $(1),(2)$
$$\frac{\cos36^\circ}{\cos(90^\circ-y)}=\dfrac{2\cos6^\circ\cos66^\circ}{2\cos6^\circ\cos(12^\circ+y)}$$
$$\iff\dfrac{\cos(12^\circ+y)}{\cos(90^\circ-y)}=\dfrac{\cos66^\circ}{\cos36^\circ}$$
Apply Componendo et Dividendo and Prosthaphaeresis Formulas to find
$$\tan(y-39^\circ)=\tan15^\circ$$
The rest should be easy!
Answer: The identity can also be proved from: $\quad\cos36° = \cos 72° + {1\over2}$
$\cos 72° + {1\over2}= (2\cos^2 36° - 1)+ {1\over2}\;= \large{\phi^2\over2}-{1\over2} ={\phi \over 2}=\cos36°$

$T= \Large \frac{2\cos 6° \cos 12°}{1\;+\;2\cos 6° \sin 12°}$
$\Large{1\over T} = {1\over 2\cos 6° \cos 12°} + \normalsize \tan 12°$
$\begin{align} \tan 36° - \tan12°
&= {\sin36° \over \cos36°} - {\sin12° \over \cos12°} \cr
&= {\sin36° \cos12° - \cos36° \sin12° \over \cos12° \cos36°} \cr
&= {\sin24° \over \cos12° (\cos72° + 0.5)} \cr
&= {\sin24° \over \cos12°(\sin18° + \sin30°)} \cr
&= {\sin24° \over \cos12°(2 \sin24° \cos6°)} \cr
\tan36° &= {1\over 2\cos 6° \cos 12°} + \tan12°
\end{align}$
$$T = \cot 36° = \tan 54°$$


Find $MAX$ and $MIN$ of $P = 2ab+3ac+3bc+\frac{6}{a+b+c}$

Question: Let : $a,b,c\in\mathbb{R}$ , $a\ge 0 , b\ge 0,0\le c\le 1 $ and $a^2+b^2+c^2=3$.
Find $MAX$ and $MIN$ of $P=2ab+3ac+3bc+\dfrac{6}{a+b+c}$.
Comment: I want to have an element solution use classical inequalities? Can you help me ?
Comment: change variables to uncouple. For example $x=a+b$, $y=ab$ and $z=c$.
Answer: Apply Lagrange multiplier, but you will have to add 5 conditions, the inequalities will become equalities, so that will give $2^4=32$ cases to check. This is actually application of the KKT conditions Although some of them will cancel, because of contradiction. The function is:
$$f(a,b,c) = 2ab + 3ac + 3bc + \frac{6}{a+b+c}$$
After applying Lagrange Multiplier we have:
$$F(a,b,c,\lambda,\lambda_1, \lambda_2, \lambda_3, \lambda_4) = 2ab + 3ac + 3bc + \frac{6}{a+b+c} - \lambda(a) - \lambda_1(b) - \lambda_2(c) + \lambda_3(c-1) + \lambda_4(a^2 + b^2 + c^2 - 3)$$
Now we take partial derivatives:
$$F_a = 2b + 3c -\frac{6}{(a+b+c)^2} - \lambda + 2\lambda_4a= 0$$
$$F_b = 2a + 3c -\frac{6}{(a+b+c)^2} - \lambda_1 + 2\lambda_4b= 0$$
$$F_c = 3a + 3b -\frac{6}{(a+b+c)^2} - \lambda_2 + \lambda_3 + 2\lambda_4c= 0$$
We know that those $\lambda$ terms has to be set to 0, so we have $16$ distinct cases.
Case 1: $\lambda = \lambda_1 = \lambda_2 = \lambda_3 = 0$
Case 2: $\lambda = \lambda_1 = \lambda_2 = c-1 = 0$
Case 3: $\lambda = \lambda_1 = c = \lambda_3 = 0$
This one is violates the condition: $0<c$
Case 4: $\lambda = \lambda_1 = c = c-1 = 0$
This is a contradiction.
Case 5: $\lambda = b = \lambda_2 = \lambda_3 = 0$
Case 6: $\lambda = b = \lambda_2 = c-1 = 0$
This implies a solution $(a,b,c) = (\sqrt{2},0,1)$
Case 7: $\lambda = b = c = \lambda_3 = 0$
This one is violates the condition: $0<c$
Case 8: $\lambda = b = c = c-1 = 0$
This is a contradiction.
Case 9: $a = \lambda_1 = \lambda_2 = \lambda_3 = 0$
Case 10: $a = \lambda_1 = \lambda_2 = c-1 = 0$
This implies a solution $(a,b,c) = (0,\sqrt{2},1)$
Case 11: $a = \lambda_1 = c = \lambda_3 = 0$
This one is violates the condition: $0<c$
Case 12: $a = \lambda_1 = c = c-1 = 0$
This is a contradiction.
Case 13: $a = b = \lambda_2 = \lambda_3 = 0$
This implies a solution $(a,b,c) = (0,0,\sqrt{3})$, but this violates the condition $c\le1$
Case 14: $a = b = \lambda_2 = c-1 = 0$
This implies a solution $(a,b,c) = (0,0,1)$, this implies the condition $a^2 + b^2 + c^2 = 3$
Case 15: $a = b = c = \lambda_3 = 0$
This one is violates the condition: $0<c$
Case 16: $a = b = c = c-1 = 0$
This is a contradiction.
Now as you can see we excluded many cases, and i solved some that are easier, now you can play with the other $3-4$ cases using the partial derivatives.
Now plug all those solutions into the initial function and see which one is minima and which one is maxima.
Answer: (1) The minimum is $2\sqrt 3$ when $a = b = 0$ and $c = \sqrt 3$.
Proof.
Let $x = a + b + c$.
Using $a + b + c \le \sqrt{3(a^2 + b^2 + c^2)} = 3$ and $a + b + c \ge \sqrt{a^2 + b^2 + c^2} = \sqrt 3$, we have $x \in [\sqrt 3, 3]$.
We have
\begin{align*}
 2ab + 3ac + 3bc + \frac{6}{a+b+c}
 &\ge 2ab + 2ac + 2ab + \frac{6}{a + b + c}\\
 &= (a + b + c)^2 - (a^2 + b^2 + c^2) + \frac{6}{a + b + c}\\
 &= x^2 + \frac{6}{x} - 3\\
 &\ge 2\sqrt 3
\end{align*}
where we use the fact that $x \mapsto x^2 + \frac{6}{x} - 3$ is strictly increasing on $[\sqrt 3, 3]$.
We are done.
$\phantom{2}$
(2) The maximum is $10$ when $a = b = c = 1$.
Proof.
We have
$$2ab + 2bc + 2ca \le 2a^2 + 2b^2 + 2c^2 = 6. \tag{1}$$
If $a + b + c \ge 2$, we have
\begin{align*}
 ac + bc + \frac{6}{a + b + c}
 &= ac + bc + \frac{6 - 2(a + b + c)}{a + b + c} + 2\\[6pt]
 &\le ac + bc + \frac{6 - 2(a + b + c)}{2} + 2\\[6pt]
 &= 4 - (1 - c)(a + b - 1)\\
 &\le 4 \tag{2}
\end{align*}
where we use $a + b + c \le \sqrt{3(a^2 + b^2 + c^2)} = 3$ and
$c \le 1$ and $a + b \ge \sqrt{a^2 + b^2} = \sqrt{3 - c^2} \ge \sqrt 2$.
If $a + b + c < 2$, we have
$$ac + bc + \frac{6}{a + b + c}
\le (2 - c)c + \frac{6}{\sqrt 3}
\le \frac12 + 2\sqrt 3 < 4 \tag{3}$$
where we use
$(2 - c)^2 > (a + b)^2 \ge a^2 + b^2 = 3 - c^2$
to obtain $2c - c^2 \le 1/2$;
and $a + b + c \ge \sqrt{a^2 + b^2 + c^2} = \sqrt 3$.
From (1), (2) and (3), we have
$$2ab + 3ac + 3bc + \frac{6}{a+b+c} = (2ab + 2bc + 2ca) + \left(ac + bc + \frac{6}{a + b + c}\right) \le 10.$$
We are done.


Class 'Mpdf\Mpdf' not found

Question: I am trying to download content in pdf.
I have done composer require mpdf/mpdf
Then in my code I have used the following:
<code>use \Mpdf\Mpdf;

$mpdf = new Mpdf();

$filename = 'file.pdf';

$mpdf->Output($filename, 'D');
</code>
But I am getting error Class 'Mpdf\Mpdf' not found in Drupal. Following some blogs I have tried using
<code>$mpdf = new mPDF()
</code>
But the error still persists. Please help.
Comment: Where have you done the `composer require`? Is your site Composer managed? The leading backslash can be removed from the `use` statement. Where exactly are you having that code placed right now? Please **update your question** in a way that this becomes a reproducible problem.
Comment: Thanks. I was not running composer require mpdf/mpdf in the root directory. Now it is resolved.
Answer: I was not running composer require mpdf/mpdf in the Drupal root directory. Hence the error.
Now it is resolved.

Class 'Mpdf\Mpdf' not found


Centralizar submit no form

Question: Tenho a print abaixo:

Estou tentando dar um margin: 0 auto no botão submit dentro do form mas nada que eu faça centraliza esse botão. Mas não posso fazer text-align: center senão vai centralizar todos os elementos do form.
Eis o **form**:

Cadastro de Administrador

  <form class="administradorCadastra">

      Tipo<select id="tipo" name="tipo" required  class="typeTextMedio">
        <option value="">Escolha o tipo</option>
        <option value="s">Super Administrador </option>
        <option value="c">Comum Administrador </option>
      </select>

      Nome<input type="text" class="typeTextMedio" maxlength="200" id="nome" name="nome" required />

      Login<input type="text" class="typeTextMedio" maxlength="<?php echo $constantes->getLenLogin(); ?>" id="login" name="login" required />

      Senha<input type="password" class="typeTextMedio" maxlength="<?php echo $constantes->getLenSenha(); ?>" id="senha" name="senha" required />

      <input type="submit" class="btnAcesso" value="Cadastrar Administrador" />

  </form>

O que fazer?
Answer: Isso ocorre pq o input é um elemento do tipo inline, ai ele não reconhece os valores de margim. Mas se vc colocar ele com display:block ele vai pegar o valor das margens e fica centralizado.
Veja no exemplo para entender melhor. Repare que bastou colocar display:block e margin:auto que o input centralizou. OBS: Nem encostei no seu HTML só com CSS resolveu.

form [type="submit"] {
    display: block;
    margin: auto;
}

Cadastro de Administrador

        <form class="administradorCadastra">

            Tipo<select id="tipo" name="tipo" required  class="typeTextMedio">
                <option value="">Escolha o tipo</option>
                <option value="s">Super Administrador </option>
                <option value="c">Comum Administrador </option>
            </select>

            Nome<input type="text" class="typeTextMedio" maxlength="200" id="nome" name="nome" required />

            Login<input type="text" class="typeTextMedio" maxlength="<?php echo $constantes->getLenLogin(); ?>" id="login" name="login" required />

            Senha<input type="password" class="typeTextMedio" maxlength="<?php echo $constantes->getLenSenha(); ?>" id="senha" name="senha" required />

            <input type="submit" class="btnAcesso" value="Cadastrar Administrador" />

        </form>

Comment: Pode me ajudar em mais essa: https://pt.stackoverflow.com/questions/301056/encurtar-caminho-com-jquery  fazendo favor?
Comment: Essa do inline eu entendi agora.  Obrigado! Não esqueço NUNCA mais.
Comment: Pois é, até deu certo. Mas me ocorre uma dúvida aqui: Se apenas elementos block recebem dimensões, Porque mesmo sem display: block ele está recebendo dimensões? E, no inspector, o browser cou ele como inline-block. Nesse caso, não seria o caso, de que se ele recebe dimensões também não deveria receber o margim: o auto?
Comment: @CarlosRocha a diferença do inline para inline-block é que o  inline-block pode ter width e height etc, mas ao mesmo tempo ele continua na  "lina"  do fluxo do texto com os outros elemento inline e inline-block. Ele não quebra a linha como uma div, um P ou um H1 por exemplo entende. Vou ver se consigo te ajudar com a outra pergunta que vc linkou
Answer: Você pode deixar o botão dentro de uma div separada e centraliza-lo dentro.
Ex:

.baseCenter{
  width:100%;
  display:flex;
  justify-content:center;
  align-items:center;
}

Cadastro de Administrador

  <form class="administradorCadastra">

      Tipo<select id="tipo" name="tipo" required  class="typeTextMedio">
        <option value="">Escolha o tipo</option>
        <option value="s">Super Administrador </option>
        <option value="c">Comum Administrador </option>
      </select>

      Nome<input type="text" class="typeTextMedio" maxlength="200" id="nome" name="nome" required />

      Login<input type="text" class="typeTextMedio" maxlength="<?php echo $constantes->getLenLogin(); ?>" id="login" name="login" required />

      Senha<input type="password" class="typeTextMedio" maxlength="<?php echo $constantes->getLenSenha(); ?>" id="senha" name="senha" required />

      <input type="submit" class="btnAcesso" value="Cadastrar Administrador" />

  </form>

No exemplo acima apenas adicionei o botão dentro de uma div com a classe .baseCenter. Nessa classe, centralizo todos os elementos que estiverem dentro dela utilizando display:flex.
Answer: CSS:
.center {
  text-align: center;
}

HTML:

   <input type="submit" class="btnAcesso" value="Cadastrar Administrador" />

Põe o que vc quer centralizar numa div e aplica o text-align: center;

Centralizar submit no form


Cascade Update Columns Relational Laravel 5.6

Question: I'm trying to have a new trait or etc for my models
I have some relation in my database mysql and I'm using laravel 5.6
I have some tables include 'is_approved' column
now I want to create something that when I set is_approved to false for one of my table, all other tables that have relation with that table, updated to the value that I would choose.
how can I do that?
for example:
I have these tables:
-product_type [columns: 'id', 'type_name', 'is_approved']
-product_brand [columns: 'id', 'type_id', 'brand_name', 'is_approved']
-product_model [columns: 'id', 'brand_id', 'model_name', 'is_approved']
-product_name [columns: 'id', 'model_id', 'product_name', 'is_approved']

and all of these tables have the 'is_approved' column
I want, when I set one of product_type record 'is_approved' column to false all I relation records updated to false
Comment: Could you explain the relations between them?
Comment: @ka_lin I explained it well, but yeah of course. there's type_id in product_brand that refer to the relation between product_type and product_brand and the others are like this
Comment: What models have you defined?
Comment: @DelenaMalan ProductType, ProductBrand, ProductModel, ProductName :-??
Answer: You could use Events on your models.
Answer: To update column to other tables. You need to make it manually with respect of type_id. like this:
$productbrand = ProductBrand::where('type_id', $type_id)->update(['is_approved' => 1]);
$productmodel = ProductModel::where('brand_id', $productbrand->id)->update(['is_approved' => 1]);
$productname = ProductName::where('model_id', $productmodel->id)->update(['is_approved' => 1]);

or you can do this using trigger. for more details read this.
http://www.expertphp.in/article/laravel-53-creating-mysql-triggers-from-migration-with-example
Answer: You can make is_approved column as part of all foreign keys with ON UPDATE CASCADE attribute:
create table product_type(
    id int auto_increment primary key,
    type_name varchar(50),
    is_approved tinyint,
    index(id, is_approved)
);

create table product_brand (
    id int auto_increment primary key,
    type_id int,
    brand_name varchar(50),
    is_approved tinyint,
    index(id, is_approved),
    foreign key (type_id, is_approved)
        references product_type(id, is_approved)
        on update cascade
);

create table product_model (
    id int auto_increment primary key,
    brand_id int,
    model_name varchar(50),
    is_approved  tinyint,
    index(id, is_approved),
    foreign key (brand_id, is_approved)
        references product_brand(id, is_approved)
        on update cascade
);

create table product_name (
    id int auto_increment primary key,
    model_id int,
    product_name varchar(50),
    is_approved  tinyint,
    foreign key (model_id, is_approved)
        references product_model(id, is_approved)
        on update cascade
);

Online demo
A change in product_type will automaticly change the corresponding rows in product_brand.
A change in product_brand will cause a change in product_model.
A change in product_model will cause a change in product_name.


Find the average value of f over region D. f(x, y) = 6xy, D is the triangle with vertices (0, 0), (1, 0), and (1, 9)

Question: I have no idea how to find the limits for this. I've tried plotting it over x but cant figure it out.
Answer: Try the limits $0\le x\le 1$, $0\le y\le 9x$. Your exression is thus
$$\frac{\int_0^1 \int_0^{9x} 6xy\,dy\,dx}{\int_0^1 \int_0^{9x} \,dy\,dx}$$
Or, for the denominator, you could just use the area of the triangle.
Comment: You are a math god.
Answer: In general, if you have a triangle and you want inequalities that define that triangle, take the equation for the line between each pair of vertices and then let the last vertex determine whether your inequality should be greater than or less than for that side of the triangle. In this case it gives you $0 \leq x \leq 1$, $0 \leq y \leq 9x$, as indicated in another answer, which gives you limits for integration.


bridge connection between lxc container and virtual host

Question: I'm relatively new to linux and network communication, and I'm been struggling with the following problem:
I have a lxc container in a virtual machine host, and the host is connected to usrp devices via interface ens5. I'm trying to establish bridge connection between lxc and virtual host so that lxc would also have access to usrp. Below are the specific details of the network:

host can ping to both usrp and lxc.
lxc seems to have no internet access since ping google.com failed.

I have attached ifconfig output for both host and lxc below:
Host:
br0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet6 fe80::8cec:6bff:feb6:f091  prefixlen 64  scopeid 0x20<link>
        ether 00:00:00:00:00:00  txqueuelen 1000  (Ethernet)
        RX packets 71  bytes 3266 (3.2 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 347  bytes 112162 (112.1 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
ens3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 8950
        inet 192.168.0.106  netmask 255.255.255.0  broadcast 192.168.0.255
        inet6 fe80::f816:3eff:fe06:31f1  prefixlen 64  scopeid 0x20<link>
        ether fa:16:3e:06:31:f1  txqueuelen 1000  (Ethernet)
        RX packets 267747  bytes 4853956651 (4.8 GB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 181065  bytes 13938392 (13.9 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
ens5: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 9216
        inet 172.23.201.111  netmask 255.255.255.0  broadcast 172.23.201.255
        inet6 fe80::50a7:4fff:fe09:f13e  prefixlen 64  scopeid 0x20<link>
        ether 52:a7:4f:09:f1:3e  txqueuelen 1000  (Ethernet)
        RX packets 85266  bytes 5116074 (5.1 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 77853  bytes 4684890 (4.6 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 392  bytes 30396 (30.3 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 392  bytes 30396 (30.3 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

LXC Container:
eth0     Link encap:Ethernet  HWaddr 00:16:3e:d6:08:87
inet addr:10.146.57.62  Bcast:10.146.57.255  Mask:255.255.255.0
          inet6 addr: fe80::216:3eff:fed6:887/64 Scope:Link
          inet6 addr: fd42:e7bb:bece:2928:216:3eff:fed6:887/64 Scope:Global
          UP BROADCAST RUNNING MULTICAST  MTU:9216  Metric:1
          RX packets:948 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1337 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:127890 (127.8 KB)  TX bytes:124727 (124.7 KB)
lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:41 errors:0 dropped:0 overruns:0 frame:0
          TX packets:41 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:3148 (3.1 KB)  TX bytes:3148 (3.1 KB)

Answer: With LXC 2.0, you can try to use the macvlan nic type for this. To do this, edit the profile you are launching your containers with. Let's say you want to edit the default profile, then do
lxc profile edit default

under the devices, section, add another nic, something like this:
devices:
  eth0:
    name: eth0
    nictype: bridged
    parent: lxcbr0
    type: nic
  usrp0:
    name: usrp0
    nictype: macvlan
    parent: ens5
    type: nic

Then, after the new container is launched, add an ip address to the new NIC:
ip address add 172.23.201.78/24 dev usrp0

You should now be able to ping the usrps from the container.


How to disable javascript validation of html5 URL element?

Question: The LinkWidget uses a URL render element, which behaves differently in different browsers.  In chrome, there is annoying pop-up, which is out of character with other validation within Drupal where there is an error message at the top of the page and a red border added to the form element.
In order to gain more control over the validation, I'd like to do away with the javascript (i.e. HTML 5) validation.  There are various suggestions using javascript or CSS, but they are heavy handed as the most effective method is to set the "novalidate" parameter on the entire form, which loses the benefit of validation on other html 5 elements such as email or dates.
What is a good way to turn this off for link fields that are set to accept external links?  (If you also accept internal links, this doesn't happen).
Answer: One way to do this is to simple not use the URL render element.  You can still use its validation, but you replace the URL element with a textfield element.
<code>/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {

  if ($context['items']->getFieldDefinition()->getType() == 'link') {
    $settings = $context['items']->getFieldDefinition()->getSettings();
    // If external link, don't use HTML5 URL element, to prevent its annoying
    // pop-ups.  Use a textfield with the backend validation from the URL element.
    if (!empty($settings['link_type']) && $settings['link_type'] == 16) {
      $element['uri']['#type'] = 'textfield';
      array_unshift($element['uri']['#element_validate'], ['Drupal\Core\Render\Element\Url', 'validateUrl']);
    }
  }
</code>


How to create a div with set size in Tailwind CSS

Question: I got some starter code from a tutorial and I've been struggling to set the correct size. I've tried to find solutions via documentation but I feel like I'm missing something very basic. The issue that I am having is that the size of the box changes based on the content that is inside. I'd like a definitive size set regardless of the inside content. This is my code for the section:

      {projects.map((project) => (

                {project.subtitle}

                {project.title}

{project.description}

      ))}

Thank you!
Answer: On your a tag you have className="flex w-1/2 h-full p-4"> updating the h-full to be the specified height that you want should do the trick. The tailwind numbers will provide a value in em I believe. To get these to be a px value you can write the style like this: h-[50px] but include your desired height in the square brackets instead of teh 50px.
Comment: Tailwind numbers are in  0.25 `rem`, which is usually 16px. https://tailwindcss.com/docs/customizing-spacing#default-spacing-scale


Executar função depois de carregar página com Angularjs

Question: Estou tentando executar uma função que da um alerta na tela depois que o contudo é carregado, porem, não estou tendo sucesso com o ng-init pois usando o ng-init ele da o alerta e a tela fica em branco e só carrega depois de clicar no botão 'OK'.
Existe uma forma de executar uma função só depois que o conteúdo da ng-view foi carregado ?
Answer: De acordo com a documentação:
<code>$scope.$on('$viewContentLoaded', function(){
    //Executar depois de carregado
});
</code>
Comment: Também não deu certo, acabei 'resolvendo' com o $timeout, mas obrigado pela ajuda!


Understanding the notation $\nabla_n K_{bd}$ for covariant derivatives, with $n$ a vector

Question: I am having troubling interpreting a particular expression in differential geometry. It arose in computing the Lie derivative along a unit normal, $n$, of the extrinsic curvature of a sub-manifold embedded in spacetime. Specifically,
$$\mathcal{L}_n K_{bd} = \underbrace{\nabla_n K_{bd}}+(\nabla_b n^c)K_{cd} + (\nabla_d n^c)K_{bc} = \underbrace{\nabla_n K_{bd}} + 2K_{bc}K^c_d$$
I do not know how to make sense of what looks like a covariant derivative $\nabla_n$. Normally, the subscript is an index, but in this case $n$ is a vector. So I can only assume that $\nabla_n$ is compact notation for something else.
Source: The notation was encountered at roughly 25:00 minutes on the Perimeter Institute lecture available at: http://pirsa.org/displayFlash.php?id=12020017.
Answer: This means $$\nabla_n T_{\dots} = n^a \nabla_a T_{\dots}$$
Comment: @user1997744 It is better to say that the covariant derivative in the direction of a vector is a connection contracted to this vector, and this is what the formula in my answer really means. The point is that a connection is an **additional piece of information**, whereas the Lie derivative is defined on any smooth manifold along any smooth vector field **without** making additional choices.
Comment: Just a quick question, is there a physical interpretation of $\nabla_n$, i.e. a covariant derivative contracted with a vector? Is it similar, intuitively, to a Lie derivative?


Why are notes always written in all-caps instead of C..B and then c..b for the next octave (E-Bass)

Question: According to the positions of the notes on the sheet, the plain strings of an electric bass should be E,A,d,g with the latter two written in lower case because they belong to a higher octave.
Whenever I google for "bass fretboard notes" or similar, though, I get images with all notes in capitals (E,A,D,G) as if they were the same.
Why is that and how do you distinguish e.g. the "E" of the plain E-string from the "e'"(?) on the 9th fret on the g-string?
Comment: "with the latter two written in lower case because they belong to a higher octave" - are you referring to https://en.wikipedia.org/wiki/Helmholtz_pitch_notation ?
Comment: @topoReinstateMonica yes, exactly. Isn't that used in the Rest oft Europe/America? (I learned it at school in Germany and thought it way universal) Why isn't at least "scientific notation" C3,G4 etc used to distinguish the notes?
Comment: In that Wikipedia page, it says "Helmholtz developed this system in order to accurately define pitches". If that's the intent, why would we name the strings according to the positions of the notes in standard notation? Bass is a transposing instrument, notated an octave higher than played; wouldn't the notes actually be E͵ A͵ D G ?
Comment: @topoReinstateMonica It should be E, A, D G (with the lower notes having a comma after them) or E A d g. But not E A D G as the E is the lowest and not between the D and G strings.
Comment: I wrote "E͵ A͵ D G" using the same sub-prime symbol for the E and the A as in https://en.wikipedia.org/wiki/Helmholtz_pitch_notation. Perhaps the sub-prime symbol isn't showing up in your browser?
Comment: @topoReinstateMonica Sorry, you did indeed. But if you e.g. search for "bass fretboard" images, there is not a single one that distibguishes the pitches.
Answer:
Whenever I google for "bass fretboard notes" or similar, though, I get images with all notes in capitals (E,A,D,G) as if they were the same.

I assume you mean a diagram like this one:
Generally, people who use these diagrams already understand what the intervals between the strings are, and that each fret is a semitone higher. Which note position is in which octave  - at least relative to the others - will more-or-less already be clear to them; they just want to put note names to the 'patterns' they already know.
It's true that you could perfectly sensibly add an octave designation to such diagrams, but this extra information just wouldn't add much value for most people who would consult this kind of diagram.
Let's contrast this with the first diagram that I get when I google "isomorphic keyboard":

Most people seeing that for the first time won't understand the interval patterns; the octave numbers in that case are much more useful to more people.

how do you distinguish e.g. the "E" of the plain E-string from the "e'"(?) on the 9th fret on the g-string?

When people are notating how to play a piece, they may use tablature, or standard notation with positions indicated with Roman numerals. When they're talking casually, they may just say 'E on the 9th fret on the g-string'.
The thing is - neither Helmholtz notation nor scientific pitch notation provide a complete solution to this problem, because 'E on the 9th fret on the g-string' is the same actual pitch as 'E on the 14th fret on the d-string'.
In situations where we do want to specify pitch, I'm much more used to seeing Scientific pitch notation than Helmholtz notation. In our brief exchange in the comments, we already highlighted two ways that Helmholtz notation can be confusing; https://en.wikipedia.org/wiki/Scientific_pitch_notation#Use mentions some other problems with Helmholtz notation too.


I need to return if btnYes is pressed

Question: public class StartPeriodMessage extends Stage implements Initializable{

    @FXML
    private  Button btnYes = new Button();
    @FXML
    private boolean btnYesStatus = false;

    public StartPeriodMessage(){

        try {

            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(getClass().
getResource("/fxmlFiles/StartPeriodMessage.fxml"));
            loader.setController(this);

            Parent root = loader.load();
            Scene scene = new Scene(root);

            setScene(scene);

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void handelYesBtn(){

        setBtnYesStatus(true);
        this.close();
    }

    @FXML
    public void setBtnYesStatus(boolean btnYesStatus) {
        this.btnYesStatus = btnYesStatus;
        System.out.println(btnYesStatus); // prints true

    }

    public boolean isBtnYesStatus() {
        return btnYesStatus; // returns false
    }
}

public class WorkPeriodController extends Stage implements Initializable{

    @FXML
    private void handlebtnStartPeriod() throws InterruptedException{
       StartPeriodMessage spm = new StartPeriodMessage();
       spm.initOwner(this);
       spm.initModality(Modality.APPLICATION_MODAL);
       spm.show();

       if (spm.isBtnYesStatus()) // always false {

            btnStartPeriod.setDisable(true);

            // do some actions
       }
    }

Answer: You can easily set action event to your button like below :
  @FXML
    private void btnYes(ActionEvent event) {
    // your action here..
    System.out.println(Button is pressed..);
  }

And you dont need to go for the initialization part FXMLLoader will do it for you
@FXML
private Button btnYes = new Button();

Comment: The Application consists of many stages and this is a pop message stage to check if the user click yes it will do some actions in another stage so i need to return if button yes is pressed or not. if you not understand me, i can share the screen via team viewer. Thanks!
Answer: You don't have to write @FXML everywhere! Only if you reference from your fxml file to the method/variable.
If you reference a variable like btnYes from your FXML-file it is initialized there and not in your class.
Where do you load your fxml file? if the following (I just cleaned it up) is not working, please also provide your fxml file and the code where you call isBtnYesStatus();
@FXML
private  Button btnYes;
private boolean btnYesStatus = false;

@FXML
private void handelYesBtn(){
    this.setBtnYesStatus(true);
    this.close();
}

public void setBtnYesStatus(boolean btnYesStatus) {
    this.btnYesStatus = btnYesStatus;
    System.out.println(btnYesStatus);
}

public boolean isBtnYesStatus() {
    return btnYesStatus;
}

Comment: Thanks!, @FXML was confused to me, Now i understand when to write it.
Comment: But  it not working i will attach the fxml and the code
Comment: Please edit your question instead of posting this link. So you are creating a new `StartPeriodMessage` and call .show() on it. Then you immediately calll isBtnYesStatus(). Due to the default false initialisation of btnYesStatus it will always return false. and after that you can click your button and the boolean changes.This cannot work correct, but it is not really a bug because It is wokring as you coded it. For this Usecase you should implement a Callback!

I need to return if btnYes is pressed


Can Random Forests do much better than the 2.8% test error on MNIST?

Question: I haven't found any literature on the application of Random Forests to MNIST, CIFAR, STL-10, etc. so I thought I'd try them with the permutation-invariant MNIST myself.
In R, I tried:
randomForest(train$x, factor(train$y), test$x, factor(test$y), ntree=500)

This ran for 2 hours and got a 2.8% test error.
I also tried scikit-learn, with
RandomForestClassifier(n_estimators=2000,
                       max_features="auto",
                       max_depth=None)

After 70 minutes, I got a 2.9% test error, but with n_estimators=200 instead, I got a 2.8% test error after just 7 minutes.
With OpenCV, I tried
rf.train(images.reshape(-1, 28**2),
         cv2.CV_ROW_SAMPLE,
         labels.astype('int'))

This ran for 6.5 minutes, and using rf for prediction gave a test error of 15%. I don't know how many trees it trained, as their Python binding for Random Forests seems to ignore the params argument, at least in version 2.3.1. I also couldn't figure out how to make it clear to OpenCV that I want to solve a classification problem, rather than regression -- I have my doubts, because replacing astype('int') with astype('float32') gives the same result.
With neural networks, for the permutation-invariant MNIST benchmark, the state of the art is 0.8% test error, although training would probably take more than 2 hours on one CPU.
Is it possible to do much better than the 2.8% test error on MNIST using Random Forests? I thought that the general consensus was that Random Forests were usually at least as good as kernel SVMs, which I believe can get a 1.4% test error.
Comment: remember that a random forest is taking a decision 1 variable ( ie pixel ) at a time. So it is not very good for image processing -raw. You are better off first using some sort of preprocessing ( eg PCA, etc ) to develop more meaningful decision variables
Comment: *I thought that the general consensus was that Random Forests are usually at least as good as kernel SVMs*. There is no such consensus.
Comment: Exactly what seanv507 said. OpenCV has a lot of functions for feature extraction which can detect quite useful explanatory variables for random forest to work with.
Answer:
Is it possible to do much better than the 2.8% test error on MNIST using Random Forests?

Probably, yes. But that doesn't mean you'll be using the same features that you get by default. Decision trees in general don't work well on high dimensional problems like this, as you are only splitting on one feature at a time. Random Forest extends the usefulness of Decision Trees, but they still have the same issue. Beating 2.8% with RF will probably require you to do some feature pre-processing and transform the features into a more useful subset.
Neural Networks and Kernel SVMs are implicitly doing some feature transformation/engineering. So in some sense its impressive that Random Forest gets decently close without any extra work (indeed the real reason RF became popular is it was stupidly easy to get "good enough" results).

I thought that the general consensus was that Random Forests are usually at least as good as kernel SVMs

There is no such consensus. They often have similar results in terms of accuracy - but they are very different algorithms with different strengths / weaknesses. On many problems there accuracies are similar, on others SVMs win by a good margin, on some RF wins by a good margin.


Reading script and replacing specific line. vbscript

Question: I'm developing a script that encrypts a users Tacacs-password, and writes this string into another script. My script opens, reads & writes the Tacacs-password into my other script but it doensn't overwrite it.
First run:
strTacacs = "Test1234"
Second run:
strTacacs = "Test1234"strTacacs = "Test1234"
My current script:
'***********Write to auto-logon script************

Const ForReading = 1
Const ForWriting = 2
newline = "strTacacs = " & chr(34) & Tacacs & chr(34)
line = 30

Set objFSO = CreateObject("Scripting.FileSystemObject")

Dim lineCount : lineCount = 0
Dim firstContent : firstContent = ""

Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
    If LCase(objFSO.GetExtensionName(objFile)) = "vbs" Then
        lineCount = 0
        firstContent = ""
        FileName = objStartFolder & objFile.Name
        Set objStream = objFSO.OpenTextFile(strFile, ForReading)
        Do Until objStream.AtEndOfStream
            lineCount = lineCount + 1
            firstContent = firstContent & objStream.ReadLine & vbCrLf
            'msgbox(firstContent)
            if lineCount = 30 Then
                firstContent = firstContent & newline
                msgbox(firstContent)
            End if
        Loop
        Set objStream = objFSO.OpenTextFile(FileName, ForWriting)
        objStream.WriteLine firstContent
        objStream.Close
    End If
Next

.
Does anybody know what I'm doing wrong?
I'm new in the world of scripting so your help is greatly appreciated!
Thx!
Answer: It looks like you are writing both the original line and the new line when you get to line 30. You should only write newline when lineCount is 30 and write the original line otherwise:
Do Until objStream.AtEndOfStream

    lineCount = lineCount + 1

    If lineCount = 30 Then
        ' Replace line with newline
        firstContent = firstContent & newline & vbCrLf
    Else
        ' Write original line
        firstContent = firstContent & objStream.ReadLine & vbCrLf
    End If
Loop

If you know the password in the original file, you could read the whole file content in one shot using ReadAll method:
Set objStream = objFSO.OpenTextFile(strFile, ForReading)
firstContent = objStream.ReadAll

then use Replace to replace the password, and finally write the content back.
You current line-by-line approach is easier if you don't know the password and simply replace a specific line. You could also check if line starts with strTacacs = which gets you away from hardcoding the line number:
Dim sLine
Dim sPasswordLine
sPasswordLine = "strTacas ="

Do Until objStream.AtEndOfStream

    ' Read line
    sLine = objStream.ReadLine

    If Left(sLine, Len(sPasswordLine)) = sPasswordLine Then
        ' Replace line with newline
        firstContent = firstContent & newline & vbCrLf
    Else
        ' Write original line
        firstContent = firstContent & sLine & vbCrLf
    End If

Loop

Comment: Good explanation.


Help with two injection and surjection examples

Question: I've been reading up on injection, surjection and bijection, but I haven't been able to find any examples that can help me figure out the solutions for these two:

Let A = {1, 2, 3} and B = {a, b, c, d}. Find one surjection from B to A.
Prove/disprove that the following function is injection and surjection (bijection): $f: (0,1) \rightarrow (1, e), f(x) = e^x$

Any help is much appreciated :)
Answer:
A surjection from B to A is simply a function where every element in A is an output of the function. One such function could be defined by $f(a) = 1, f(b) = 2, f(c) = 3, f(d) = 1$.
To prove that the function $f(x) = e^x$ is a bijection, we can find the inverse. $f^{-1}(x) = \ln x$ (which is defined for this particular domain).
Comment: Thanks! Is it really enough to just find the inverse function to prove it is bijection?
Comment: Yep! The fact that a function is bijective is equivalent to the fact that it has an inverse. Don't forget to prove that it is an inverse though (show that $(f \circ f^{-1})(x) = (f^{-1} \circ f)(x) = x$.


Repository pattern and Joining table in go

Question: I'm currently trying to build my app around the Domain driven design , entities , services , repos,...
All the basic crud operation are simple where basically 1 entity => 1 table => 1 repository => 1 service
But i can't figure out the cleanest way to handle join table between two entities.
It would be possible to make 1 query by table inside of the join and it would be " clean" ( so to say ) but it wouldn't be efficient as a simple join would have resulted in one query.
Where do tables join live in this pattern ?

I have been thinking of building now entities that would encapsulate the answer but that would effectivitly create 1 entity + repository for just 1 query...
I'm also thinking that merging multiple entities into a single interface might partially solve it but it would result in many empty param of my entities ( it's rare that you require ALL field from ALL tabes when you're performing a join )

What is the proper way/pattern to solve this issue that would fit in the DDD or at least be clean ?
--
Edit example :
type User struct {
    ID          int       `db:"id"`
    ProjectID      int    `db:"project_id"`
    RoleID      int       `db:"role_id"`
    Email       string    `db:"email"`
    FirstName   string    `db:"first_name"`
    LastName    string    `db:"last_name"`
    Password    string    `db:"password"`
}

type UserRepository interface {
    FindById(int) (*User, error)
    FindByEmail(string) (*User, error)
    Create(user *User) error
    Update(user *User) error
    Delete(int) errorr
}

type Project struct {
    ID          int       `db:"id"``
    Name   string    `db:"name"`
    Description    string    `db:"description"`
}

Here i have a simple user repository. I have something similar for the "Project" table. can create table , get all info on the project , delete , etc etc.
As you can see UserID has the foreign key of the project ID it belongs to.
My issue is when i need to retrieve all the information from the user and , say the " project name " and description. ( i reality the table/entity has much more parameters )
I need to do a simple join in user.project_id and project.id and retreive all the information of the user + project name + description in one query.
Sometimes it's more complex because there will be 3-4 entities linked like this. ( user , project , project_additional_information, roles , etc)
Ofcourse i could make N queryies, one per entity.
user := userRepo.Find(user_id)
project := projectRepo.FindByuser(user.deal_id)

And that would "Work " but i'm trying to find a way to do it in one query. since a simple sql join on user.project_id and project.id would give me all data in on query.
Answer: As for join part your question is quite trivial to answer, however for DDD there are a lot of hurdles from current language possibilities. But I will give a try..
Ok, let's imagine that we are developing an educational courses backend with multilanguage support where we need to join two tables and subsequently map to object. We have two tables (the first one contains language-independent data and second which contains language-dependent)
If you are a repository advocate, then you will have something like that:
// Course represents e.g. calculus, combinatorics, etc.
type Course struct {
    ID     uint   `json:"id" db:"id"`
    Name   string `json:"name" db:"name"`
    Poster string `json:"poster" db:"poster"`
}

type CourseRepository interface {
    List(ctx context.Context, localeID uint) ([]Course, error)
}

then implementing it for sql db we will have something like that:
type courseRepository struct {
    db *sqlx.DB
}

func NewCourseRepository(db *sqlx.DB) (CourseRepository, error) {
    if db == nil {
        return nil, errors.New("provided db handle to course repository is nil")
    }

    return &courseRepository{db:db}, nil
}

func (r *courseRepository) List(ctx context.Context, localeID uint) ([]Course, error) {

    const query = `SELECT c.id, c.poster, ct.name FROM courses AS c JOIN courses_t AS ct ON c.id = ct.id WHERE ct.locale = $1`
    var courses []Course
    if err := r.db.SelectContext(ctx, &courses, query, localeID); err != nil {
        return nil, fmt.Errorf("courses repostory/problem while trying to retrieve courses from database: %w", err)
    }

    return courses, nil
}

The same applies to different related objects. You just need patiently model a mapping of your object with underlying data. Let me give another example.
type City struct {
    ID                      uint            `db:"id"`
    Country                 Country         `db:"country"`
}

type Country struct {
    ID   uint  `db:"id"`
    Name string `db:"name"`
}

// CityRepository provides access to city store.
type CityRepository interface {
    Get(ctx context.Context, cityID uint) (*City, error)
}

// Get retrieve city from database by specified id
func (r *cityRepository) Get(ctx context.Context, cityID uint) (*City, error) {

    const query = `SELECT
    city.id, country.id AS 'country.id', country.name AS 'country.name',
    FROM city JOIN country ON city.country_id = country.id WHERE city.id = ?`

    city := City{}
    if err := r.db.GetContext(ctx, &city, query, cityID); err != nil {
        if err == sql.ErrNoRows {
          return nil, ErrNoCityEntity
        }
        return nil, fmt.Errorf("city repository / problem occurred while trying to retrieve city from database: %w", err)
    }

    return &city, nil
}

Now, everything looks clean until you realize that Go actually (as for now) does not support generics and in addition people in most situations discourage to utilize reflect functionality because it makes your program slower. In order to completely upset you imagine that from this moment you need transactional functionality....
If you came from other languages, you can try achieving it with something like that:
// UnitOfWork is the interface that any UnitOfWork has to follow
// the only methods it as are to return Repositories that work
// together to achieve a common purpose/work.
type UnitOfWork interface {
    Entities() EntityRepository
    OtherEntities() OtherEntityRepository
}

// StartUnitOfWork it's the way to initialize a typed UoW, it has a uowFn
// which is the callback where all the work should be done, it also has the
// repositories, which are all the Repositories that belong to this UoW
type StartUnitOfWork func(ctx context.Context, t Type, uowFn UnitOfWorkFn, repositories ...interface{}) error

// UnitOfWorkFn is the signature of the function
// that is the callback of the StartUnitOfWork
type UnitOfWorkFn func(ctx context.Context, uw UnitOfWork) error

I intentionally missed an implementation because it looks monstrous for sql and deserves its own question (the idea is that unit of work has its versions of repositories decorated with started tx under the hood) and after you beat this problem you will have more or less
err = svc.startUnitOfWork(ctx, uow.Write, func(ctx context.Context, uw uow.UnitOfWork) error {

            // _ = uw.Entities().Store(entity)
            // _ = uw.OtherEntities().Store(otherEntity)

            return nil
        }, svc.entityRepository, svc.otherEntityRepository)

so here you reach the final and in most cases people started to say that you write code which seems not idiomatic referring something like that. The point is that concepts are written too abstract and it is a philosophical question whether materialized DDD is even applicable in Golang or you can just partially mimic it. If you want flexibility, choose database once and operate with pure db handle
Comment: Hello thanks for the answer. Doesnt exactly answer my question as your entity has the same field as the extra field from the join table. better example would be if your course entity stayed the same and but your query tried to retreive : `SELECT c.id, c.poster, ct.name, ct.subject,ct.content,ct_teacher,ct_field2,ct_field3`  where would those field be stored. because i can't have an entity with all possible field from all the the possibles join for all my tables with it's PK is FK
Answer: Depending on the data you want to read the solution will be different:
If the tables you want to join form a single aggregate, then just join them in your query and always return and store the full aggregate. In this case, you have only a repository for the root entity. This is likely not your scenario because you said you have repositories for the other entities you want to join (unless you have a design issue).
If the tables you want to join belong to different bounded contexts, you shouldn't join them. A better approach is to submit one query on each bounded context so that they remain decoupled. These multiple queries will come from different places, depending on your architecture: directly from the client, from an API gateway, from some sort of application service, etc.
If the tables belong to a single bounded context, but from multiple aggregates, then the cleanest approach is to follow CQRS (Command/Query segregation). In simple terms, you define a specific interface for your query, with the inputs and outputs that you need for the use case that you are implementing. This separation frees you from the limitations that you find trying to use your Commands infrastructure for queries (the 1 to 1 entity/repository relationship that you have). The naive implementation of this query interface could be a query that does a join of your existing tables. This is quick and easy to implement, but it means that your Commands and Queries are separated in code, but not at the DB level. Ideally, you would create a (denormalized) read model table in your database, with all the columns that you need for that specific query and updated every time one of the source tables is updated (this is normally done through domain events). This allows you to optimize your tables for your queries, with the right columns, data format, and indexes, but as a downside, it introduces some complexity and eventual consistency between the write and the read model.
Comment: Hello,Thanks for answering me althought i'm not sure i understand it all. Indeed the first point doesn't fit me as i don't always need all the agregate and something there's different aggregate. 2 and 3rd point i'm not sure to understand but i might nee to read more.  I've updated my question with an example if you could have a look ! thanks
Comment: Probably the most important part of DDD is defining bounded contexts, aggregates and domain model in general. While doing this, you will split your domain in a way that is basically optimized for Commands (applying business logic, enforcing invariants, transactionability, etc). The "downside" of this design is that when you want to read data to show it to the user, the data will be spread across multiple tables and even multiple databases. Using read models (point 2) and UI or ViewModel composition (point 3) are ways to workaround this issue.
Comment: Before deciding the approach for the queries, you need to make sure your domain model is designed correctly. For example, in your example, User contains a ProjectId. This could be correct in your case, but it's a bit unusual. Managing user information is rarely a core concern (all apps do that), you could even use a ready made solution for that. Managing Projects seems more like your core domain and a Project could contain a list of UserIds. If this was the case, it would make sense to me to read the Project information from a read model and let the client application get (and cache)
Comment: the user information from its source. If instead, your current design is correct, you might want to create a read model with the project information and user information and read it directly from there in a single query. So, as you see, the design of your boundaries will affect the way you implement these reads.
Comment: Tyvm for the help, I'd accepted both answer if i could


Print commerce pricing attributes to email receipt

Question: Users cannot see what size or color shirt they purchased in the email receipt because tokens won't print the attribute fields provided by Commerce Product Attributes / Commerce Pricing Attributes / Commerce Product Option combo.

User selects shirt size: XL and color: Green
Both fields can be previewed during checkout.
Email receipt received doesn't show any attributes, user cannot check what size/color they ordered.
(All this can be achieved using default CCK fields under product type, but we're using the combination mentioned above for multiple reasons, many products got different option sets to chose from and certain attributes selected adds extra price to total, like eg size: XXXL costs extra $3+ and this cannot be achieved with default fields).

One of the tokens I found is like eg. [commerce-order:commerce-line-items:0:commerce-pricing-attributes] and email on checkout prints it like this:
Product: BK Test

a:1:{s:9:"coveralls";a:8:{s:25:"field_coverall_embroidery";N;s:25:"field_coverall_text_color";N;s:10:"field_font";N;s:16:"field_shirt_name";N;s:16:"field_patch_side";N;s:12:"field_length";s:1:"2";s:21:"field_coveralls_color";s:1:"4";s:19:"field_coverall_size";s:2:"16";}}

Also more tokens available at admin/help/token like eg.: Attributes  [commerce-line-item:commerce-product:field_attributes]  Pricing Attributes field. and combining them with [commerce-order:commerce-line-items:0:commerce-product] won't work, already tried dozens of variations.
E.g. in Order's view page I addded the view Commerce Line Item: Product Attributes and it displays correctly.

How to print this in the email receipt?
Comment: Have you tried write your own token or write a custom function with order parameter?
Comment: It's easy using entity_metadata_wrapper to find what you want and print it.
Comment: Well,  all the tokens already exist in the token help list for each and every field,  they just won't print if it's order/line item.
Comment: i think can you use hook_tokens
Answer: <?php

/**
 * Implements hook_token_info().
 */
function mymodule_token_info(){
    $info['tokens']['commerce-order']['line_item_detail'] = array(
        'name' => t('Line Item Product Detail List'),
        'description' => t('List all the Product Line Item Detail of the order')
    );
    return $info;
}

/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if($type == 'commerce-order'){
    $order = $data['commerce-order'];
    $order_wrapper = entity_metadata_wrapper('commerce_order',$order);
    $lineItems = $order_wrapper->commerce_line_items->value();
    $lineItemArray = array();
    foreach($lineItems as $key => $value){
        $line_item_wrapper = entity_metadata_wrapper('commerce_line_item',$value);
        if($line_item_wrapper->type->value()=='product'){
            $product_title = $line_item_wrapper->commerce_product->title->value();
            $quantity = $line_item_wrapper->quantity->value();
            $lineItemArray[] =  $product_title.' x '.$quantity;
        }
    }

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'line_item_detail':
            $variables = array(
                'items' => $lineItemArray,
                'type' => 'ul',
            );
            $replacements[$original] = theme('item_list', $variables);
            break;
      }
    }
  }
  return $replacements;
}

This is the sample code.
You can modify the result you want at hook_tokens().
I hope this will help you.
Comment: this shows only title and quantity. I tried adding `product_attributes` or simple `sku` I get error `Unable to get a data value. Error: Unknown data property sku.`
Comment: I was missing `->commerce_product->` for SKU to be printed, but still can't figure how to print product attributes like in the given screenshot.
Comment: `product_attributes` (seen in screenshot, displays correct via views) gives error mentioned before and field `field_custom_attributes` that is Pricing Attributes field type prints `Array` and notice `Array to string conversion line 30`
Comment: you can use follow this https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers, and then you can get what you want.
you can use $wrapper->commerce_price->amount->value(), and change amount to decimal by using commerce_currency_amount_to_decimal($amount,$currency);
Answer: install views rules module, make a views-rules of orders, you will need OID as a contextual filter, add it as allways, then in middle column, in parameters settings set your OID as:integer, add all fields/attributes you wish, now in middle column settings, set your fields/attributes values as text, choose 'use rendered output'.
Then in your send-email-to-customer rule, add a views-rule with your new view, actions: fecth entity by id:ORDER with your variable OID, now you have all fields/attributes you added avilable as tokens, built your email body like: thanks [user:name], your order [OID] is in proccess, you bought : T-shirt [tshirt:value],  T-shirt-size: [tshirt-size:value], ............. .
if you can not use HTML tags, here is an exported rules_action_info() rules code that i used in one site, adds a new action: build-email-body, it shows you how to built a row for a 'nice'
html look alike. if you need this feature, you will need to make a custom module called: rulesbodyemail, change all $variables and code as needed, take a close look how is built variable:  $text_formatted_body, and is how is returned.
<?php
/**
 * Implement hook_rules_action_info()
 * Declare any meta data about actions for Rules
 */

 function rulesbodyemail_rules_action_info() {

 $actions = array(
'buitl_email_body' => array(
    'label' => t('build-email-body'),
    'group' => t('cadena'),

    'parameter' => array(

      'node_id' => array(
              'type' => 'integer',
              'label' => t('node id'),
              ),

      'parcialidad_title' => array(
              'type' => 'text',
              'label' => t('parcialidad_title'),
              ),

      'parcialidad_monto' => array(
              'type' => 'decimal',
              'label' => t('parcialidad monto'),
              ),
      'parcialidad_cliente' => array(
              'type' => 'text',
              'label' => t('cliente'),
              ),

      'parcialidad_fecha' => array(
              'type' => 'date',
              'label' => t('parcialidad fecha'),
              ),
      'parcialidad_aseguradora' => array(
              'type' => 'text',
              'label' => t('cia aseguradora'),
              ),

      'parcialidad_ramo' => array(
              'type' => 'text',
              'label' => t('ramo'),
              ),

        'parcialidad_cobertura' => array(
                'type' => 'text',
                'label' => t('cobertura'),
                ),

        'parcialidad_fecha_formateada' => array(
                'type' => 'text',
                'label' => t('feha formateada'),
                ),

          ),

    'provides' => array(
        'text_formatted_body' => array(
                'type' => 'text',
                'label' => t('text_formatted body'),
                'wrap' => TRUE,
                //'format' => 'full_html'
                ),
              ),
  ),
);
  return $actions;

 } // fin de actions_info

// rules function procesar row
function buitl_email_body($node_id, $parcialidad_title, $parcialidad_monto,
$parcialidad_cliente, $parcialidad_fecha, $parcialidad_aseguradora,
$parcialidad_ramo, $parcialidad_cobertura, $parcialidad_fecha_formateada) {

// variable $hoy esta en UNIX
$hoy = time();
$formatted_hoy = date('j/M/y', $hoy);

  //drupal_set_message($parcialidad_fecha_int . ' $parcialidad_fecha ', 'status', FALSE);
  //drupal_set_message($formatted_fecha . ' $formatted_fecha ', 'status', FALSE);

  //prepara las variables y calcula dias vencidos
  $parcialidad_fecha_int = strip_tags($parcialidad_fecha);
  $hoy_int = (int)$hoy;
  $fecha_int = (int)$parcialidad_fecha_int;
  $diff = $hoy_int - $fecha_int;
  $diff = round($diff/86400);

  // formato fecha y $ pesos

  $monto_format = "$".number_format($parcialidad_monto, 2);
  $formatted_fecha = date('j/M/y', $parcialidad_fecha_int);

  //hace el render del row
  $text_formatted_body =
  "
  ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁

  ▲ PARCIALIDAD ▲ $parcialidad_cliente

    Parcialidad: $parcialidad_title
    Monto:  $monto_format
    Venció: $formatted_fecha; Días vencidos: $diff

    Aseguradora : $parcialidad_aseguradora
    Ramo: $parcialidad_ramo; Cobertura: $parcialidad_cobertura

  " ;

  //return $text_formatted_body
  return array('text_formatted_body' => $text_formatted_body);

  } // fin de funcion rules procesar row

it returns this as the email body:

image of rule to send emails:

image of body email value
Comment: Insane solution, holy moly, can't believe this works, this Views Rules module is really powerful and it's not updated since 2k12! And for formatting, I didn't need custom module, just add internal `` at the top of the body above all the tokens in the rules. Thanks for helping.
Comment: hi @pinueve, it sends separate email for each line item in the cart. So if ordering 5 items, user gets 5 emails with each product. Should be all products in one email. Can you make a screenshot of your rules setup?
Comment: it could be that your rules-view is returning same order several times, in query settings toggle 'unique results', or in rule-email do send email outside the views-loop, to do this, add a text-token variable first and outside views-loop, built body as you did, and asign your text-token-variable with email-body value, and send email with variable-token, let me know if this helps.
Comment: i added images of my rule and email body value.
Comment: Here's mine https://i.imgur.com/apQ5IUx.png everything you move outside loop does not get picked up, no tokens available and email is empty. I do not see the fetch ID part in your screenshot and seem like yours using author ID and not order ID and you have multiple data fields. I ticked the disctinct in the view, but I don't think it's the problem, the emails are not dupes, it sends separate email for separate line item in the order with its details.
Comment: here is my complete COMPONENT, i did component because my emails are send everyday scheduleded, i pull UID's from a node-view with aggregations, this you don't need that,     https://imgur.com/rhfZj73
https://imgur.com/c6n1LDB
https://imgur.com/ex9zuiy
Comment: https://drupal.stackexchange.com/questions/258194/how-to-create-a-rule-to-email-all-users-with-a-profile-field-x-with-same-value-a/258195#258195
Comment: The `products_attribute` that is pulled by views rules cannot be before the loop in the variable action with the rest off the email body. Email won't print the field. Email won't print anything that's outside the loop. And if it's inside, you get separate emails for each line item. Eg this is the only order I get to work: https://i.imgur.com/icgVkre.png
Comment: more hints: set in your views-rule to show only one row; check that your email should be sent in 'check-out-proccess'; play with rules-conditional-module, it adds new conditionals inside actions.
Comment: I don't see where to set to show one row, my field doesn't have that, unless you meant pager. It's set to checkout process. Here's a gif of my view: https://i.imgur.com/k5vW41a.gifv
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/88588/discussion-between-pinueve-and-user3108268).
Comment: HI, could you ponit me wich module you are using to provode full HTML emial-body, and please share your email-body
Comment: mailsystem with mimemail and CSS is just font size and colors, you can put anything (I get field classes by exporting the email as .html)


Group by column with preference for rows in which another column is not null

Question: Say I have a table which looks like this, with two foreign keys:
| col1 | fkey1 | fkey2 |
|------|-------|-------|
| foo  | 123   | null  |
| foo  | 123   | 456   |
| bar  | 789   | null  |

How would I group by col1, with a preference for the row in which fkey2 is not null? So that the result would look like this:
| col1 | fkey1 | fkey2 |
|------|-------|-------|
| foo  | 123   | 456   |
| bar  | 789   | null  |

One other consideration is that fkey1 has a not null constraint on it, while fkey2 does not.
Comment: Is `fkey2` defined `UNIQUE`? If not, which row to pick from peers with distinct non-null values? Will more columns be involved? The question would be much more useful with a `CREATE TABLE` statement showing data types and constraints.
Answer: For this dataset, you could use simple aggregation:
select col1, fkey1, max(fkey2) fkey2
from mytable
group by col1, fkey1

But I suspect that you actually want distinct on:
select distinct on(col1) t.*
from mytable t
order by col1, fkey2