Regression line

Question: A random sample of size $n$ from a bivariate distribution is denoted by $(x_r,y_r), r=1,2,3,...,n$. Show that if the regression line of $y$ on $x$ passes through the origin of its scatter diagram then
$$\bar y\sum^n_{r=1} x_r^2=\bar x \sum^n_{r=1} x_r y_r$$ where $(\bar x,\bar y)$ is the mean point of the sample.
I don't really know how to begin. I am aware the line equation is $b=\frac{y}{x}=\frac{\sum xy-\frac{\sum x\sum y}{n}}{\sum x^2-\frac{(\sum x)^2}{n}}$
Not sure what to do next.
Comment: If it passes through the origin, then $a=0$.
Comment: Yes I am aware of that.
Answer: Recall that the OLS estimators are
$$
\hat{\beta}_0 = \bar{Y}_n - \hat{\beta}_1\bar{X}_n, \quad \hat{\beta}_1 = \frac{\sum X_i Y_i-n\bar{X}\bar{Y}}{\sum X_i^2 - n\bar{X}^2},
$$
because the line passes through the origin, you have that $\hat{\beta}_0 = 0 = \bar{Y} - \hat{\beta}_1\bar{X}$, thus
$$
\frac{\bar{Y}}{\bar{X}} = \frac{\sum X_i Y_i-n\bar{X}\bar{Y}}{\sum X_i^2 - n\bar{X}^2},
$$
or
$$
\bar{Y}\sum X_i^2 - \bar{Y}n\bar{X}^2=\bar{X}\sum X_i Y_i -n\bar{Y}\bar{X}^2,
$$
hence
$$
\bar{Y}\sum X_i^2=\bar{X}\sum X_i Y_i .
$$
Comment: Can you tell me how did you decided which is the intercept?
Comment: It is a matter of derivation, rather than "decision". If you solve $\min_{\beta} \sum (y_i - \beta_0 - \beta_1x_i)^2$, then you'll get that the OLS of the intercept is $\bar{y}-\hat{\beta}_1\bar{x}$.
Comment: Just one last thing. What is the variable $\beta_0$ that you used? Moreover can you please provide a proof for the intercept? (I am not that good in statistics to carry out the operation you suggested)
Comment: You can find [here](https://isites.harvard.edu/fs/docs/icb.topic515975.files/OLSDerivation.pdf)  a full proof.

Regression line


Hessian for linear regression with regularization

Question: I'm using matlab to solve a regularized linear regression via the fminunc() function.  The cost function is from the standford machine learning class.
It's pretty slow so and I think it could be sped up if I use a Hessian multiply function via the Hessian 'on' option.
Can someone provide me with the formula for computing the hessian?  I'm a bit of a novice here.
Thanks.
EDIT:
So I think I've got it but can anyone confirm?  It's based on my less than expert attempt at calculus.  I'm using:
hessian = (X' * X + lambda * eye(length(theta)))./ m;
Comment: Coul you state the expression of the regularization you are using? Is it a "Ridge" regularization or is it more exotic?
Comment: yes, ridge regularization. (cost function penalized by lambda * sum(theta.^2))
Comment: is the hessian $X^T X$ or $X X^T$?
Answer: I think you're right (ignoring the $\frac{1}{m}$ to simplify the notation)
$$ L(\beta) = (y - X \beta)^t (y - X \beta) + \lambda \beta^t \beta $$
$$ \nabla L (\beta) = - X^t (y - X \beta) + \lambda \beta $$
$$ \nabla^2 L (\beta) = X^t X + \lambda I $$
Though, as an observation, the equation $\nabla L (\beta) = 0$ is linear in beta
$$ (X^t X + \lambda I) \beta = X^t y $$
so you're better off using a linear equation solver than a general non-linear optimizer.
Comment: Hi Matthew, Would linsolve() be the preferred matlab function to use?
Comment: It looks like that should work.  I'm not familiar with the ecosystem of matlab linear algebra function, so there may be a better choice that takes advantage of the structure of the coefficient matrix.
Comment: is the hessian $X^T X$ or $X X^T$?


Disable/Remove floating label hint text in TextInputLayout XML

Question: This may seem counter-intuitive but is there a way to disable or remove the floating label hint in TextInputLayout? The reason I want to use TextInputLayout instead of just an EditText is for the counter that TextInputLayout provides.
Here is what I have so far:
<android.support.design.widget.TextInputLayout
            android:id="@+id/textContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="vertical"
            app:counterEnabled="true"
            app:counterMaxLength="100">

            <EditText
                android:id="@+id/myEditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="top|left"
                android:inputType="textMultiLine|textCapSentences"
                android:maxLength="100"
                android:scrollbars="vertical"
                android:hint="This is my cool hint"/>

        </android.support.design.widget.TextInputLayout>

Comment: Best idea to programatically you have to give hint and textChange event time Give to null hint in editbox that idea may help you
Comment: Problem is the hint color. It becomes white when typing something. Please change the hint color or change the background color. You will see the hint while typing.
Answer: Starting version 23.2.0 of the Support Library you can call
setHintEnabled(false)

or putting it in your TextInputLayout xml as such :
app:hintEnabled="false"

Though the name might makes you think it removes all hints, it just removes the floating one.
Related docs and issue: http://developer.android.com/reference/android/support/design/widget/TextInputLayout.html#setHintEnabled(boolean)
https://code.google.com/p/android/issues/detail?id=181590
Comment: Extra note: In order for this to work, you need to set the hint on the `TextInputEditText`. If you set the hint on the `TextInputLayout` it won't be shown.
Comment: But it adds some strange padding on top when you set app:hintEnabled="false"
 :( If you use icons on the right, it will be noticeable. I've added paddingTop="12dp" to TextInputEditText, it looks fine then.
Comment: I'm having this hide the error as well, which is a little unexpected (version 27.1.1)
Comment: I don't know why android decided to change what a hint is, they should have referenced the label with another property.
Answer: There may be three ways to go about achieving this:
1 Set android:hint on TextInputLayout to a space _ character, and keep android:hint="This is my cool hint" set on the EditText.
<android.support.design.widget.TextInputLayout
    ....
    ....
    android:hint=" ">       <<----------

    <EditText
        ....
        ....
        android:hint="This is my cool hint"/>    <<----------

</android.support.design.widget.TextInputLayout>

This works because TextInputLayout performs the following check before using the EditText's hint:
// If we do not have a valid hint, try and retrieve it from the EditText
if (TextUtils.isEmpty(mHint)) {
    setHint(mEditText.getHint());
    // Clear the EditText's hint as we will display it ourselves
    mEditText.setHint(null);
}

By setting android:hint=" ", if (TextUtils.isEmpty(mHint)) evaluates to false, and the EditText retains its hint.
2 Second option would be to subclass TextInputLayout and override its addView(View child, int index, ViewGroup.LayoutParams params) method:
public class CTextInputLayout extends TextInputLayout {

    public CTextInputLayout(Context context) {
        this(context, null);
    }

    public CTextInputLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CTextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void addView(View child, int index, ViewGroup.LayoutParams params) {
        if (child instanceof EditText) {
            // cache the actual hint
            CharSequence hint = ((EditText)child).getHint();
            // remove the hint for now - we don't want TextInputLayout to see it
            ((EditText)child).setHint(null);
            // let `TextInputLayout` do its thing
            super.addView(child, index, params);
            // finally, set the hint back
            ((EditText)child).setHint(hint);
        } else {
            // Carry on adding the View...
            super.addView(child, index, params);
        }
    }
}

Then use your custom CTextInoutLayout instead of the one from the design support library:
<your.package.name.CTextInputLayout
    ....
    .... >       <<----------

    <EditText
        ....
        ....
        android:hint="This is my cool hint"/>    <<----------

</your.package.name.CTextInputLayout>

3 Third, and probably the most straight-forward way would be to make the following calls:
// remove hint from `TextInputLayout`
((TextInputLayout)findViewById(R.id.textContainer)).setHint(null);
// set the hint back on the `EditText`
// The passed `String` could also be a string resource
((EditText)findViewById(R.id.myEditText)).setHint("This is my cool hinttt.");

Comment: This actually is solution for one more problem. When you set app:hintEnabled="false", you can get strange bug - top or bottom line of the box (with OutlinedBox style) is cut or even missing. CTextInputLayout is perfect solution for this bug. (I am using material:1.0.0, and tested on material:1.1.0 alfa 1 and 2)
Answer: With  com.google.android.material you can hide by
<com.google.android.material.textfield.TextInputLayout

               ....

               app:hintAnimationEnabled="false"
               app:hintEnabled="false"
               >

                <com.google.android.material.textfield.TextInputEditText
                    ........
                    android:hint="@string/label_hint"
                    />

</com.google.android.material.textfield.TextInputLayout>

Answer: I've tried all of answers, but non of them are working now (specifically for com.google.android.material:material:1.1.0-beta01). Even if we make changes to EditText addition logic in TextInputLayout, we have empty space on top of field that blanking half of text and hint. Now I have a solution for the problem. Main thing is a padding in EditText, as mentioned in material.io:
<com.google.android.material.textfield.TextInputLayout
             . . .
    android:layout_height="wrap_content"
    app:hintEnabled="false"
    app:startIconDrawable="@drawable/ic_search_black"
    app:endIconMode="clear_text">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/et_search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="12dp"
        android:hint="@string/showcase_search_hint_text"
        android:inputType="text" />

</com.google.android.material.textfield.TextInputLayout>

It allows us to implement a 'SearchView'-like view with search icon and text deletion button without any ugly "magic" with custom views
Comment: using  android:paddingVertical="10dp" is better
Comment: See https://github.com/material-components/material-components-android/issues/366 to change padding between drawable and hint.
Comment: To achieve same overall height as with hint, android:paddingVertical="16dp" looks more like it
Answer: if you have used app:hintEnabled="false" then also set android:paddingTop="8dp" in EditText and boom top hint space is gone, this worked for me hope this works for you too
Comment: Looks like there is no built-in way to fill hint space, thanks for the hack!
Answer: If someone have problems like me:

The label make the text padding show wrong then do this:
<com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:paddingTop="@dimen/default_padding"
                    android:paddingBottom="@dimen/default_padding"
                    android:layout_height="wrap_content"
                    android:hint="@string/search_hint" />

Add padding top and padding bottom to the TextInputEditText that will fix the problem
Answer: Answer by @Gauthier is correct, but in case you don't want just the floating Hint but you want the Hint before text edit then in addition to disabling Hint for TextInputLayout you should provide hint in EditText widget.
I guess this answers few of the question raised by some people in above comments.
Answer: myEditText.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) textContainer.hint = null
            else myEditText.hint = getString(R.string.your_string)
        }

it makes your hint gone perfectly in your textInputLayout, because if you want to make it gone with app:hintEnabled="false" that's make your textInputLayout not cool :)
Answer:  <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/etemailLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint=" ">

            <EditText
                android:id="@+id/txtemail"
                style="@style/login_edittext"
                android:hint="Enter Your Email Address"
                android:inputType="textEmailAddress" />

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/etPasswordLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint=" "
            android:scrollbars="vertical"
            app:counterEnabled="true"
            app:passwordToggleEnabled="true">

            <EditText
                android:id="@+id/txtpassword"
                style="@style/login_edittext"
                android:fontFamily="@font/ubuntu"
                android:hint="Enter Password"
                android:inputType="textPassword"
                android:maxLength="8"
                android:scrollbars="vertical" />

        </com.google.android.material.textfield.TextInputLayout>

for apply style to your EditText put below code in Styles.xml ..

for backgroud effect create edittext_background.xml in drawable..
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle"
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <corners android:radius="7dp" />
    <solid android:color="#80ffffff" />
    <padding android:left="10dp" android:right="10dp"
        android:top="10dp" android:bottom="10dp" />
    <stroke android:width="2dp" android:color="#FFFFFF" />
</shape>

Comment: This is easiest way to apply Hint but don't show it on upside when user clicks on EditeText.
Comment: Must Try This Solution, It Will Not Have Any Error In Code. And No Need To Change Code.Directly Put This Code.
Answer: I think this will help you:
textContainer.setHintAnimationEnabled(false);

Comment: Does not work my friend. I tried in code and via XML `app:hintAnimationEnabled="false"` and neither worked. I think this just disables the animation of that label floating up.
Comment: So, you want to remove hint text, is it?
Comment: I want the hint text to appear inside of the `EditText` faded. Then when you click the `EditText` I want the hint text to disappear, instead of moving up to the floating label. Just like a regular `EditText` does it.
Answer: update the design library to v23 and add app:hintAnimationEnabled="false" in the TextInputLayout


Call Get-ADComputer in a loop until the object is found

Question: I want to call Get-ADComputer from Powershell in a loop until the computer object is created in Active Directory.
I'm using the following code. The script won't loop. How can I write the code so it loops correctly?
<code>    do {(Write-Host "." -nonewline -ForegroundColor Red),(sleep 3)}
    until(Get-ADComputer -name ComputerName)
</code>
I can't figure out what's missing. I hope you guys can help me out.
Answer: Use the -Filter parameter, with the Name parameter you get a terminating error in case the computer in question cannot be found.
<code>do {
  Write-Host "." -nonewline -ForegroundColor Red
  sleep 3
} until(Get-ADComputer -Filter {Name -eq 'ComputerName'})
</code>


Making responses to public nodes only viewable by the creator and the originator

Question: I've got a prototype site built in D6, pertinent modules:

CCK
Comment block
Node Comment
Views
Views Or

The site is built around a list of open requests; to solicit a private response. These nodes are of content type Request.
All open requests are public in that all users (logged in or not) can view these nodes.
When a response (comment) is received to an open request it should only be viewed by the author of the original request, or the author of the response.
These responses should be shown to these users on the original node as comments and on a seperate list.
How do I do this?
Answer: A quick search on D.o. came up with this forum post asking to do the exact same thing: http://drupal.org/node/919914
They suggest using Node Comment and Content Access together to achieve it, but I'm not certain Content Access will give you the specific option you're looking for.
It would be a start though, and you might be able to hook into Content Access and create a new "Parent Node author" or similar option if you are up for a coding session.
Comment: I'm always up for coding; but often with Drupal there is a better way of doing things than simply writing code. Writing code where I should have been using modules was my first mistake.
Comment: I do get that, but hooking into modules to extend functionality or simply modifying code to provide new functionality as a patch is also the Drupal way :)


What's the limit of this function as $(x,y) \to (0,0)$?

Question:
Im trying to find the limit of this function or check if the limit exists as $(x,y) \to (0,0)$. Every line I've tried such as $y=x, y=-x, y=x^2$, etc all lead to the limit being $0$ but I'm sure this isn't right. Can anyone find a line that proves the limit doesn't exist or prove its equal to $0$?
Answer: To find counter example a good idea is to homogeneize the formula with $y=tx$ (note that $t$ is not necessarily a constant, see it like the ratio $t=\frac yx$).
$f(x,y)=\dfrac{tx^2(x^2-t^2x^2+t^2x^4)}{x^4+t^4x^4}=\dfrac{t(1-t^2+t^2x^2)}{1+t^4}$
Since now the denominator $>1$, we want to find a suitable $t$ such that the numerator does not go to $0$ while $y$ still go to $0$.
$N(x,y)=t-t^3+t^3x^2\not\to 0$ a trivial choice is $t=2$.
Indeed $f(x,2x)=\dfrac{8x^2-6}{17}\to -\frac 6{17}\neq 0$
Comment: +1 I like this because it introduces readers to the idea of trying 'many' paths at once. Moreover, any readers could also switch to polar coordinates using $x= r \cos \theta, y= r \sin \theta$ and then simplify to see that the limit depends on $\theta$. Choosing 'nice' $\theta$ one could find lines, i.e. $t$ values where the limits will be different. The two methods are the different approaches to the same end and are useful approaches for the limit 'toolbelt.'
Comment: Yes, this is a general method. Note that in case of a true zero limit, you often get $f(x,y)=\phi(t) x^\alpha\to 0$ showing the $\phi$ is a bounded function of $t$. So it does not serve only for finding counter-examples.
Answer: Hint: Look at the limit along $x=y^{1/3}, y>0$.
Comment: What motivates that choice of path?  Or do you have to just keep guessing until you find something that works?
Comment: Usually taking $x$ to be a power of $y$ works. But you have keep trying various powers until you get a choice that gives the answer. @RobertShore
Answer: Take the path $(x,y)=(-2y,y)$. Then on this path, we have
$$f(x,y)=f(-2y,y)=\frac{(-2y)\cdot y\cdot(4y^2-y^2+4y^4)}{16y^4+y^4}$$
$$=\frac{-6y^2-8y^4}{17y^2}\rightarrow -\frac{6}{17}$$
as $y\rightarrow 0$. We conclude that (combined with your previous work) that the limit does not exist.

What’s the limit of this function as $(x,y) \to (0,0)$?


Spring Data JPA findAll(Iterable ids) doesn't allow duplicated ids

Question: So I have a list of Ids
List<Integer> ids = [1,1,1,5];

And when I pass that list to findAll(Iterable<ID> ids),
instead of returning 4 entities, it will only return 2 with id 1,5.
Is there any way to change findAll() so it wouldn't remove the duplicates?
Comment: Are you sure that the `ids` list it's the representing your PK?
Comment: Just curious, why don't remove the duplicates from the original list?
Comment: only because I need multiple same entities for some calculation in cases
Answer: I don't think it's possible: SELECT * FROM foo WHERE id in (1, 1, 1, 5) will also return 2 rows, not 4. It's not the repositories job to create cloned objects for you. Just create a clone method/copy constructor if you need to clone the entity.
Answer: You can rebuild this list after the findAll complete, here is the code:
List<Integer> ids = [1,1,1,5];

List<Foo> fooList = fooDao.findAll(ids); // Only two objects

List<Foo> newFooList = new ArrayList<>();

for (Integer id : ids) {
    Foo f; // Find the object from the origin list using `CollectionUtils` etc.

    newFooList.add(f);
}


How to grab last modified file with certain keyword on page

Question: I have a snippet of code here that grabs the last modified file from a directory. However, I want it to exclude any file that has the word "placeholder" written on it. How do I modify this so that it does exclude those files, especially since the file that has "placeholder" written on its page is usually the last modified file?
Here is the code that I have:
<?php
$dir = "path goes here";
$pattern = '\.(php)$'; // check only file with these ext.
$newstamp = 0;
$newname = "";

if ($handle = opendir($dir)) {
       while (false !== ($fname = readdir($handle)))  {
         // Eliminate current directory, parent directory
         if (ereg('^\.{1,2}$',$fname)) continue;
         // Eliminate other pages not in pattern
         if (! ereg($pattern,$fname)) continue;
         $timedat = filemtime("$dir/$fname");
         if ($timedat > $newstamp) {
            $newstamp = $timedat;
            $newname = $fname;
          }
         }
        }
closedir ($handle);
$name = basename($newname,".php");
 echo "Latest Chapter:   $name";
?>

Answer: To skip over files which contain the string "placeholder":
if(strpos(file_get_contents($fname), 'placeholder') !== false) continue;

Comment: Thanks much! This has helped. I just had to change $fname to $dir/$fname
Answer: You could save a lot of code:
array_multisort(
    array_map('filemtime',
        $files = preg_grep('/placeholder/',
            glob("$dir/*.php"), PREG_GREP_INVERT)),
    SORT_ASC, $files);

$name = basename(end($files), '.php');


Challenge - Ninjascript C# interface with a C++ dll

Question: Alright, here is the deal.  I am trying to interface a C++ dll with an indicator written for the NinjaTrader platform (which is written in ninjascript...essentially C# with some platform specific code additions).  TO make my dll work the way it is intended, I need to be able to pass a struct array from the indicator to the dll.  In the indicator code, I am passing the struct array via ref.  In the dll, I am trying to accept the struct array as a pointer.  This allows me to edit the contents in the dll, without trying to figure out a way to pass a horde of information back to NinjaTrader.  Basically, the dll receives the struct array pointer, which gives it access to the contents directly.  Then, when the dll function returns a bool true flag to Ninja, it accesses the struct array and renders the information to the chart.  Sounds simple right?  I thought so too.
Here is the problem.  NinjaTrader does not allow unsafe code.  So, when I try to pass the struct array to the dll, and receive it as a pointer, it immediately crashes the platform.  If I receive the struct array as a pointer to a ref (*&), then it works, but....once control is passed back to Ninja, all the edits done in the struct array are non-existent.
So, to speed up this process, I have created a very brief indicator, and dll code set which demonstrates what I am trying to do.
Here is the ninja indicator code:
[StructLayout(LayoutKind.Sequential)]
public struct TestStruct
{
    public int x, y;
}
TestStruct[] test = new TestStruct[2];

protected override void OnBarUpdate()
{
    if(CurrentBar < Count - 2) {return;}
    test[0].x = 10;
    test[0].y = 2;
    test[1].x = 0;
    test[1].y = 0;

    Print(GetDLL.TestFunk(ref test));
    Print("X0: " + test[0].x.ToString() + "  Y0: " + test[0].y.ToString());
    Print("X1: " + test[1].x.ToString() + "  Y1: " + test[1].y.ToString());
}

class GetDLL
{
    GetDLL() {}
    ~GetDLL() {}
    [DllImport("testdll.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "TestFunk")]
    public static extern int TestFunk(
            [In,MarshalAs(UnmanagedType.LPArray)] ref TestStruct[] test );
}

And now the C++ dll code:
#define WIN32_LEAN_AND_MEAN
#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>

struct TestStruct
{
   int x, y;
};

extern "C" __declspec(dllexport) int __stdcall TestFunk( TestStruct *testy )
{
   testy[1].x = 20;
   testy[1].y = 9;
   int one = testy[1].x;
   int two = testy[1].y;

   return (one + two);
}

Now, please keep in mind, this code I have pasted in above WILL cause NinjaTrader to crash the moment you place the indicator on a chart and it becomes active.  The only way I have been able to make it NOT crash is to change the arg in the C++ TestFunk function to either TestStruct *&testy or TestStruct **testy, noting that the . operators will have to be changed to -> also.
Now that I have said all that, does anyone know how to get around this limitation and get access to the actual pointer, so the dll can edit the actual values stored in the struct array, which will be reflected inside NinjaTrader....but not crash?
Comment: Not without using unsafe code. That is one of the biggest differences between managed (C#) and unmanaged(C++) code, i.e. the use of pointers.
Comment: That has been my conclusion thus far.  I just can't shake the feeling there is something that could be done in the C++ side to capture the memory addresses.
Comment: Based on your constraints, you can always pass the array or structure, and pass back a string in a format that you can easily do something like a returnString.split(',') to get back what you want/need.
Comment: Too much data to return via that method.  The system would take a major performance hit to compile it into a string, and then decode the string into useable data.  This would destroy the entire point of coding the system in C++, which is almost entirely for the performance.
Comment: what about passing the struct and returning a struct?
Comment: I had considered that, but was avoiding it unless there was literally no other possibility.  I suppose I could at least try it and see what kind of performance penalty I am looking at dealing with.
Answer: Huzzah!  I finally figured it.  First, let me post the relevant code, then I will explain.
First the C#/Ninjascript
public class TestIndicator : Indicator
{
    [StructLayout(LayoutKind.Sequential)]
    public struct TestStruct { public int x, y; }
    static TestStruct[] testy = new TestStruct[2];

    protected override void OnBarUpdate()
    {
        if(CurrentBar < Count - 2) {return;}

        GetDLL.TestFunk( ref testy[0] );
        Print("X0: " + testy[0].x.ToString() + "  Y0: " + testy[0].y.ToString());
        Print("X1: " + testy[1].x.ToString() + "  Y1: " + testy[1].y.ToString());
    }

    class GetDLL
    {
        GetDLL() {}
        ~GetDLL() {}
        [DllImport("testdll.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "TestFunk")]
        public static extern void TestFunk( ref TestStruct testy );
    }
}

And the C++ code:
struct TestStruct { int x, y; };

extern "C" __declspec(dllexport) void __stdcall TestFunk( void *t)
{
    TestStruct* ptE = (TestStruct*)t;
    ptE->x = 10; ptE->y = 2;
    ptE++;
    ptE->x = 20; ptE->y = 9;
}

First, I had to declare the struct array as static, using new, giving it a fixed memory location on the heap.  Then I pass it as a ref to my C++ dll.
Inside the dll, the arg is captured as a void* data type.  Next, I typecast the arg into a `TestStruct* and store it in another pointer variable (to keep my zero element reference intact).
From that point, I have a pointer that references element zero, which I can use to edit the values at element zero in the struct array.  To gain access to the following elements, all I needed to do was increment the pointer.  Once I did that, I had access to element one in the array.
Nothing was passed back to NinjaTrader because the dll was editing the actual values in their original memory locations.  No need to pass anything back, thus attaining the reduced cpu cycles/memory operations necessary...which was my original intent.
Hopefully this helps someone stuck in a similar situation.


interpreting poisson regression models with log transformation and factors/qualitative variable

Question: I have a dataset with both quantitative ($x_1,x_2, \text{and} \ x_3$) and qualitative variables ($x_4$ - 4 levels ~0,1,2,3). 3 variables ($x_1,x_2,x_3$) have been log transformed. I do not know how to interpret coefficients when its log transformed.
glm(formula = y ~ log(1 + x1) + log(1 + x2) +
      log(1 + x3) + factor(x4), family = "quasipoisson",data = data)

                Estimate
(Intercept)     0.20
log(1 + x1)     0.76
log(1 + x2)     -0.1
log(1 + x3)     0.25
factor(x4)1     0.4
factor(x4)2     0.45
factor(x4)3     0.57

Let's suppose, if I want $x_4$ (for levels 0,1,2,3) to vary $x_1$ from 0,1,2,...,40 how would it effect my response considering everything being equal ? In addition, how to interpret $x_1,x_2, \text{ and } x_3$ ?.
Numerical Example, I want to vary $x_3$ between 0,1,2,3,4,5,... and so on and determine its impact on y for 4 different levels in variable $x_4$:
Let's suppose I want to predict for factor 0 which is when $x_4$ at 0 when $x_3 = 5$:
$$y = exp^{(0.20+0.25*5)}$$
Let's suppose I want to predict for factor 2 which is when $x_4$ at level 1 when x3 = 5:
$$y = exp^{(0.25*5+0.45)}$$
is my interpretation correct ?
Answer: Interpreting the coefficient  of a log-transformed variables is reasonably straightforward: it represents the predicted change in the dependent variable for a 1-log-unit change in the independent variable.
Here, the dependent variable (in the default log-link for the quasipoisson family in glm) is $log(y)$. After the transformations of the variables $x_1$ through $x_3$, they are no longer the independent variables for the regression. The regression coefficients need to be interpreted in terms of the new independent variables $log(1+x_1)$ through $log(1+x_3)$.
So for the relation of $x_1$ to $y$, with the other independent variables held constant, you have a change of 1 log unit in $(1+x_1)$ corresponding to a change of 0.76 in $log(y)$. That pesky 1 in $log(1+x_1)$ makes is hard to provide a more general direct relation between $x_1$ itself and $y$.
Comment: Thank you @EdM, I have added 1 to x1 to avoid taking log(0) if that makes sense.
Comment: @forecaster : That is what I thought you had done.
Comment: Thank you, how would you interpret factors? So for instance how would you determine the impact of x4 at lev ps 0,1,2,3?
Comment: The default in R is for the Intercept to correspond to the reference levels of all categorical factors. The reference level of $x_4$ here is level 0. So as an example, for level 2 of $x_4$, $log(y)$ is 0.45 units higher than it is for level 0 of $x_4$.
Comment: Thanks again, I have edited by question with a numerical example, can you please let me know if this correct. I'm confused because this is a log-log regression with qualitative variable. I really appreciate your response.
Comment: Not quite right. When $x_3 = 5$ you need to use $0.25 log(1+5)$, not 0.25 * 5, in both examples, and in your second example you forgot the Intercept.
Comment: Also in your prediction examples, you have implicitly done the prediction for $log(1+x_1)=log(1+x_2)=0$, or equivalently $x_1=x_2=0$.


GTK Scrolled Window - Keep Scroll Bar at bottom

Question: I have a GTK/C++ program that uses a ScrolledWindow.  I keep adding data to the list within the scrolled window, and I want to keep focus on the newest item.
But I also want to allow the user to scroll through the data to select an old item.
Is there a way to do this?  I've looked everywhere but can't find anything.
Answer: It's not quite clear to me what you mean by your question, but here's what I think you mean: when you add items to your list, they are added below the current visible portion of the list. So if you start out looking at the bottom of the list, then add a lot of items, you end up looking at the middle of the list. What you want is to scroll to the bottom of the list every time an item is added.
If that's correct, then just scroll the window to the bottom every time you add an item:
<code>Gtk::Adjustment *adj = scrolled_window.get_vadjustment();
adj->set_value(adj->get_upper());
while(Gtk::Main::events_pending())
    Gtk::Main::iteration();
</code>
Answer: I had the same issue (developing on GTKmm)
as suggested by @ptomato
but the while loop should come up first before setting
the value for vadjustment. (worked for me)
<code>   while(Gtk::Main::events_pending())
         Gtk::Main::iteration();
   Gtk::Adjustment *adj =scrolled_window.get_vadjustment();
   adj->set_value(adj->get_upper());
</code>


looping Get-ReceiveConnector to grab multiple receive connectors

Question: This is on a Windows 2008R2 server running Exchange2010.
I would like to use powershell and "Get-ReceiveConnector" to grab information from about 20 configured receive connectors.  Ultimately we are migrating to a different exchange server, so my goal is to export them to text and then import them later.
This article: http://terenceluk.blogspot.com/2010/11/how-do-i-exportimport-exchange-20072010.html gives some good info on pulling the data from individual receive connectors, but I'd like to use foreach or something similar to loop through all receive connectors on that particular server - I'm just not sure how to do it.
Thanks!
Answer: This isn't too tough, it's Powershell 101 really. If you're going to be doing a bunch of Exchange work, you'll definitely need to learn PS front to back.
<code>$conns = Get-ReceiveConnector
foreach ($conn in $conns) {$conn.name }
</code>
If you need to limit it to only a specific server, do this
<code>$conns = Get-ReceiveConnector -server MyServerName
foreach ($conn in $conns) {$conn.name }
</code>
In the examples, above, I'm just listing the connector name in the body of the loop - the statement in between the curly brackets. You would replace that with whatever it is that you want to do with each connector.


plotly scatter with x =df2.index .values, y = df2.coulmn.values

Question: I have a dataset which is a time series which consist of sold item and how much sold on each date. i am using the following code for plotly scatter after transpose. i have defined x =df.index.values, y = df.coulmn.values for scatter but i get a blank graph.
I am not getting error either need your expert guidance to fix the same.
import plotly.graph_objs as go
import plotly.express as px
import plotly.offline as pyo

df2 =df1[ df1['Country']== 'Pen'].groupby(['Pen']).sum()

df2= df2.transpose()

trace = go.Scatter(
x= [dict(values=list(df2.index))],
y= [dict(values=list(df2.columns))],mode='lines')
layout = go.Layout( title='Sold item count')
data= [trace]

fig = go.Figure(data=data, layout=layout)

pyo.plot(fig)

even i tried  with x =df2.index.values, y = df2.coulmn.values still the same.
Comment: Please, provide the dataframe in a usable format. Thanks.
Comment: Thanks for looking into this
Comment: there was issue with the date format  after changing the date format issue fixed @sentence
Answer: Issue was with the date format with few data in dataset pd.to_datetime helped to resolve the issue.


How to get the list of all entity reference fields and their params?

Question: I'm trying to build a new widget for the entity reference module.
(nested checkboxes = tree according to entity references between nodes)
The only answer I'm looking for is :
"How to get the list of all entity reference fields and their params? (child and parent node)
Thank you for your help!
Ludovic
Edit : working on D7
Comment: I can get the list of all entity reference fields for one child, but I don't know how to get the parent node type of each field.
Comment: I have the same problem. You can get parent entity in field table "field_data_$field_name" but i cant get all field names of all entityreference fields
Comment: see my solution in the answer below
Answer: Here is my custom function that gets id's of all files referenced entities and their parents. Also get's all field names, entity types and bundles of entityreference fields.
<code>function _my_module_get_entityreferences_settings() {
  $child_ids = $field_names = $settings = array();

  // Get all entityreference field names
  $query = db_select('field_config', 'f');
  $query->fields('f', array('field_name'));
  $query->condition('f.type', 'entityreference');
  $query->distinct();
  $rows = $query->execute();

  foreach ($rows as $row) {
    $field_name = $row->field_name;
    $field_names[] = $field_name;
  }

  // Loop all entityreference fields. Get all child and parent Ids
  foreach ($field_names as $field_name) {
    $table = 'field_data_' . $field_name;
    $target_id = $field_name . '_target_id';

    $query = db_select($table, 'f');
    $query->fields('f', array('entity_id', $target_id, 'entity_type', 'bundle'));
    $query->distinct();
    $rows = $query->execute();

    foreach ($rows as $row) {
      $settings[$row->entity_type][$row->bundle][$field_name] = $field_name;
      $child_ids[$row->{$target_id}] = array(
        'id' => $row->{$target_id},
        'parent' => $row->entity_id,
      );
    }
  }

  return array(
    'childs' => $child_ids,
    'settings' => $settings,
  );
}
</code>
Maybe you don't need all this stuff. When you get $field_names array you can use
<code>$field = field_info_field($field_name);
</code>
to get settings of current field. You can find here referenced bundles, field type, handler_settings etc.


How do I create a ruleset component?

Question: I would like to create a custom ruleset component like the one described in  How to automatically generate multiple aliases for one node?
That answer is for Drupal 7, and I am using Drupal 8. When I go to Rules/Components, none of the plugin options that I see in screenshots of Drupal 7 appear to be available (e.g. rule set, condition set, action set). Basically, the Components tab looks nothing like the one found in Drupal 7, so it's unclear to me how to create a ruleset. I'm not a module developer, but when I look through the module folder, I see a folder named Plugins/RulesExpression which contains files that seem to correspond to these component plugin types. Is there something I have to do to enable them to be available in the administration pages?
The documentation for Drupal 8 Rules is basically empty. The only documentation I found is for contributing developers; it doesn't seem there is any updated documentation for administrator users of the module, and I have searched far and wide for any insight on this and found nothing.
Answer: While Rules components may successfully be created and used programmatically, as of Rules 8.x-3.0-alpha4 there is only minimal support for doing this in the UI. Adding these UI features is part of the last meta task needed to be completed before a beta version of Rules is released. You can discover the current status of these UI porting issues by reading the Rules issue queue at https://www.drupal.org/project/issues/rules

How do I create a ruleset component?


How to Invert the Euler Lagrange Equations?

Question: Suppose I have a functional L. For example $L = y+3y'$. Where y is itself a function of real variable x
It's easy for me to evaluate the Functional Derivative of L via the Euler Lagrange Equations:
$$ \frac{\partial L}{\partial y} - \frac{d}{dx} \frac{\partial L}{\partial y'}$$
But how does one do the inverse? Given a functional L, find the functional G that when applied by the above gives L.
The d/dx term makes thing very hard as the two partial derivatives are independent of each other but this differentiation forces a relationship between the two.
Comment: I'm a little confused about the question. Are you asking to find $G$ that satisfies $P[G] = L$, where $P$ is the E-L operator?
Comment: It seems OP is asking the inverse problem for Lagrangian mechanics: Given an ODE, find a Lagrangian such that the Euler-Lagrange equation becomes the ODE.
Comment: Yes @Gregory that is the goal
Answer: Your problem is the classical inverse problem formulated by Helmholtz in 1887. This problem is, as far as I know, completely solved by Mayer and Hirsch in 1897. If you want a complete and modern study of this problem, you can read the book of Olver "Applications of Lie groups to differential equations". In this book, the multidimensional case (PDE) with general order is studied.
In my thesis (above cited by Sylvain L.), I gave an explicit formulation of the Helmholtz condition in the unidimensional case (ODE) with second order. In this particular (and simpler) case, the Helmholtz condition can be written in a very simple way. You will find it in Equation (IV.2.12) p.67. This condition is sufficient and necessary in order to ensure that a second order differential operator $O$ is a (second-order) Euler-Lagrange operator.
Now, if you consider a second order differential operator $O$ that satisfies the Helmholtz condition, and if you want to find a Lagrangian $L$ such that $EL[L]=O$ (where $EL$ is the Euler-Lagrange operator), then you can follow the step of the proof of Theorem IV-2 p.67. This proof gives an explicit way to construct such a Lagrangian $L$.
Remark: Note that $L$ is not unique since there exist some "null Lagrangian", see Section IV-2-3 p.69.
Answer: What you are looking for is called the inverse Helmotz problem I think : given a differential operator of second order, at what condition is there a corresponding lagrangian ?
You can learn more about this on the web (for example https://en.wikipedia.org/wiki/Inverse_problem_for_Lagrangian_mechanics) but I never found out that much references about it.
For what I know, there exists a sine qua none condition on the operator for being an Euler-Lagrange derivative of some Lagrangian, called the Helmoltz condition.
But I think that in practice, it's not always easy to use. However, if we are considering a problem with only one degree of liberty, which seems to be the case in your question, there is a more explicit condition that is equivalent, sometimes called the explicit Helmoltz condition. I think that in this case, there is even an explicit construction of the Lagrangian.
I'll see if I can find out where I've read that.
Update : I found it, it is http://www.unilim.fr/pages_perso/loic.bourdin/Documents/bourdin-thesis2013.pdf. It is half in french, half in english but the part you're looking for is in english. It is the section IV.2. page 65.


How is a public ip adddress accessible anywhere from the internet?

Question: If my machine has a public ip address, then any one from any corner of the world can access this ip address. How does this happen? I mean where is my ip address updated or where does the requester see if my ip address is a valid one or not?
Answer: IP Addresses are like telephone numbers, and the Internet routers like telephone exchanges.
Let's assume my phone number is 333-1234. The "333" part is the exchange ID. If I dial 333-4567, the exchange knows that I am trying to reach another phone on the same exchange. It will do a lookup of all subscriber numbers listed in its database, and connect me (assuming the destination number is listed and not busy).
If say I dial 444-2378, my local exchange knows that the number is listed in a different exchange. Depending on the routing table of the local exchange, it will either route the call directly to exchange 444, or employ the help of a 'tandem exchange'.
Let's say my complete phone number is +62-21-333-1234, and I am dialling +1-412-678-4466. My local exchange sees that the destination number is located on a different country. It doesn't have to have a routing table to the USA, but it knows by default it must route the call to the tandem exchange. The tandem exchange also doesn't have a routing table for the USA, so it will route the call to the International exchange. The International exchange does know how to route the call to "+1", but that's it. So, the International exchange sends the call to the 'nearest' International exchange in the USA. The International exchange in the USA has a routing table containing the area codes, and routes the call to the tandem exchange serving the area code. The tandem exchange looks up the route for the local exchange having the ID of 678, and transfers the call there. Finally, the '678' exchange checks for the existence of subscriber number 4466, and attempts to connect the call.
The Internet is similar : your default gateway doesn't have to know how to reach the whole Internet. If it happens upon an address that it doesn't recognize, it will send the packet to a higher-tier router. At the highest tier -- the so-called 'backbone' -- the routers know how to route to all the Internet, but only the leftmost octet of the IP address ("the zone"). Upon entering a zone, the packet gets handled by a router in the zone that knows the route to a part of the zone, and so on, hop by hop the packet gets transferred to a router with smaller 'coverage', but more detailed knowledge, similar to how telephone exchanges work.
Answer: Public IP addresses are like phone numbers.  With IPv4 addresses like aa.bb.cc.dd, anyone can start to try to knock on the door of each of these and see what services might be available.  They can start at 220.127.116.11 go to 18.104.22.168 and so on.  Like phone numbers, they can be dialed at anytime and like phone numbers you can determine approximately where in the world the IP address is.
However, if you have a specific IP address for your system and you don't make that IP address known, then if someone who knew you and they wanted to try to find your machine, they'd have to go through all the IP addresses that are out there and have to be able to identify your machine by some service it might be running.  A difficult task to say the least.  They can shorten the list by know who your ISP provider is, but they still would not be able to easily determine what public IP address is assigned to your computer.
Typically you protect yourself behind a firewall using NAT and this in turn can provide a first layer of protection from direct probing and is usually the standard method used to connect systems to the internet.
Regarding your question about how anyone in the world can get to your IP address, that is the work of routers and your IP address.  If we go back to the first example where IP addresses are in the format of aa.bb.cc.dd, I can give this a try to simplfy the explanation, steering clear of the nitty gritty details.

First there is a layer of routers at "aa".  Think of each router as assigned to a network number, being 1-254.  So there are 254 of these routers at the top level and these routers only care about the first number.
When the first router for network "aa" is found, the process repeats at step 1 for "bb", and "cc".  "dd" is now only a network of 254 nodes/hosts/computers so that is how a computer in Hong Kong can get to a computer directly in the US.

It can become more complicated than this with lots of nuts and bolts, but it seemed easiest to try to explain it like this.
Hope that helps.
Comment: The number of networks in any given class has nothing to do with a particular number of routers.  Routers can advertise that they are handling any number of networks.  Please edit.
Comment: I agree with Rapzid. The last part of the answer is needlessly complicated and generally incorrect. A simpler explanation is this: Routers close to you have routes "up" towards routers with more information about the Internet (a typical home user, for example, gets the packet 'up' to their provider). At some point, you reach a router that knows a route towards the destination's network (core routers exchange this information with each other). The packet eventually reaches a router close to the destination that has a route "down" to the destination.
Comment: thank you for answering:) When I give the destination ip address as aa.bb.cc.dd, then where does this request go first(I am using a net card i.e connected to the internet through a usb kind of device. So there is no default gateway also) or how does it know where to go?
Comment: There is always a default gateway or otherwise you'd never be able to communicate beyond your subnet.
Comment: @ErikA : but when I do ipconfig, only the ipv4 address is displayed and the default gateway section is 0.0.0.0 .
Comment: @Ashwin Your computer is not giving you useful information. You can do a traceroute to see what the next hop is. (The command is `tracert` on Windows.)
Comment: @DavidSchwartz : yes I did the tracert. what can I infer from that/
Comment: You can see the path the packet took, specifically where it went immediately after it left your machine. If you traced the route to a "random" external IP, then the next hop should be your default route. (Assuming your machine doesn't have a full Internet routing table, which it almost certainly doesn't.)
Comment: @DavidSchwartz : then why doesn't ipconfig show the default gateway. there is nothing wrong with my machine. I have tried it on other machines and tgey all show the default gateway to be 0.0.0.0 . can it be that the default gateway is hard coded in the internet card(usb).
Comment: @Ashwin: There are two possible reasons: 1) You may be looking in the wrong place in the `ipconfig` output. There's a separate block for each interface. 2) You may have a default route that's not an interface route, which `ipconfig` won't show. (The `route print` command will show it. It'll be the route with both a destination and netmask of `0.0.0.0`.)


Feeds Import Alter for Multiple Fields

Question: I am trying to setup a Feed Import from CSV.  There is an images field in the content type which can have unlimited values.  These images are in a folder and named in the following format:
<code>[identifier_from_csv]_01_large.jpg
[identifier_from_csv]_02_large.jpg
[identifier_from_csv]_03_large.jpg
</code>
Each project has a variable number of images.  I would like to be able to read from the file system and import as many images it has located there.  I've tried to research into this and from what I can see the Feeds Tamper module I would still have to know how many images there are and have them all listed in a field.
How can I setup an import that would automatically read in as many images as there are located in the file import directory?  I'm assuming there is a hook I could use and loop through there checking the file system, I'm not sure where/how to implement that.
Answer: I ended up solving this myself.  My main question I guess was really about a feeds tamper plugin that can insert multiple values.  Turns out it's pretty easy, just return an array and I think set the 'multi' value on the plugin.  I ended up copying the "explode" plugin and modifying it for my needs.  Here is the result.  It's got some hardcoded values which I'm sure could be coded into the form settings.  I kept it simple for my purposes.
<code>$plugin = array(
    'form' => 'my_feeds_tamper_image_import_form',
    'callback' => 'my_feeds_tamper_image_import_callback',
    'validate' => 'my_feeds_tamper_image_import_validate',
    'name' => 'My Image Import',
    'multi' => 'direct',
    'category' => 'List',
);

function my_feeds_tamper_image_import_form($importer, $element_key, $settings) {
    $form = array();
    return $form;
}

function my_feeds_tamper_image_import_validate(&$settings) {

}

function my_feeds_tamper_image_import_callback($result, $item_key, $element_key, &$field, $settings, $source) {
    $out = array();
    $index = 1;
    $fileExists = true;

    do {
        $filename = "public://import/" . $field . "_" . str_pad($index, 2, "0", STR_PAD_LEFT) . "_lg.jpg";

        if( file_exists($filename) ) {
            $out[] = $filename;
            $index++;
        }
        else {
            $fileExists = false;
        }

    } while($fileExists);

    $field = $out;
}
</code>

Feeds Import Alter for Multiple Fields


How to fix 'An aggregate may not appear in the WHERE clause' error in MS SQL Server

Question: For a school project, i need to create some databases in MS SQL Server , create some views, and manage the users acces. The thing is that our course was really empty, and i'm having trouble with some mechanics of MS SQL Server
I have a table with every player of the football world cup of 2018, and i want to take the 20 shortest players, so i just wanted to use ORDER BY Person.Height. If i use that, my result is something like that :
62    165    Panama    QA19
63    165    SaudiArabia    AY8
78    165    Switzerland SX23
59    166    Mexico    AJ20
etc...

but i just want to take the shortest players and order them by country, not by height, so having something like that
69    168    Argentina   SE18
66    168    Argentina   LM15
67    166    Brazil    CF22
64    169    Brazil    RF18

the 20 shortest players ordered by country in an alphabetical order
This is the code i have right now, and this give me the first result
SELECT TOP (20) Person.Weight, Person.Height, Country.NameCountry,
LEFT(Person.Name, 1)+LEFT(Person.FirstName, 1)+CAST(Player.Numero AS
nvarchar(MAX)) AS Initiales

FROM Person INNER JOIN Country
ON Person.CountryId = Country.CountryID
INNER JOIN Player
ON Person.PersonID = Player.PersonID

WHERE -----------------
ORDER BY Person.Height, Country.NameCountry

If i use MIN(Person.Height) in the WHERE clause, i have this error : An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
But i don't need any HAVING OR GROUP BY clause, so i don't really understand what i'm supposed to do.
I know that my explanation is not very clear, but if somebody could help me with that, that would be vey nice
Comment: This not looks like mysql.
Comment: `SELECT TOP (20)`? Are you actually asking about MS SQL Server?
Comment: Yes, it's MS SQL Server, sorry
Answer: Try with a subquery
SELECT * FROM (
    SELECT Person.Weight, Person.Height, Country.NameCountry,
    LEFT(Person.Name, 1)+LEFT(Person.FirstName, 1)+CAST(Player.Numero AS
    nvarchar(MAX)) AS Initiales
    FROM Person INNER JOIN Country
    ON Person.CountryId = Country.CountryID
    INNER JOIN Player
    ON Person.PersonID = Player.PersonID
    WHERE -----------------
    ORDER BY Person.Height
    LIMIT 0,20)
ORDER NameCountry


What is 'cash considerations'?

Question: I've seen quite a few trades in the NBA go by as 'Player X for cash considerations'.
But what is, actually, cash considerations? Is there any obligations to the team that gave 'cash considerations' or its just a fancy way of saying 'we traded the player for literally cash'?
Comment: Have you read this [article](https://www.sportskeeda.com/basketball/what-cash-considerations-nba#:~:text=Cash%20considerations%20in%20the%20NBA%20are%20exactly%20what%20they%20sound,the%20recipient%20team's%20salary%20cap.)?
Answer: Cash considerations is a fancy way of saying 'literal cash' with the caveat that it does not count toward the receiving team's salary cap.
The motivation to do this type of trade is:

to obtain draft picks
to obtain rights to a particular player (to be drafted or under contract)
to use as a bargaining chip to match salaries or take on salary

Article from jros:

Cash considerations in the NBA are exactly what they sound like –
actual money offered to teams as part of a deal. The only difference
here is that cash considerations do not count towards the recipient
team's salary cap.

What is 'cash considerations'?


Need help to solve a definit integral using Fourier transform.

Question: Hi I have some problem with solving the following definit integral.
$$
\int_{-\infty}^{\infty} e^{-\big(\dfrac{t}{\tau}\big)^2-\dfrac{i\omega t}{2}}\textrm{d}t
$$
My guess to solve it is by using Fourier transform. I need somehow get write it on the form
$$
F(\omega)=\int_{-\infty}^{\infty}f(t)e^{-i\omega t}
$$
And after i get it on this form I can simply look up in a table what $F(\omega)$ is.
Answer: Hint. Alternatively, one may observe that, by parity of the integrand, your integral reduces to
$$
\int_{-\infty}^{\infty} e^{-\Big(\dfrac{t}{\tau}\Big)^2-\dfrac{i\omega t}{2}}\textrm{d}t=\int_{-\infty}^{\infty} e^{-\Big(\dfrac{t}{\tau}\Big)^2}\cos \Big(\dfrac{\omega t}{2} \Big)\:\textrm{d}t
$$ then one may use the standard result:
$$
\int_0^{\infty} e^{-x^2} \cos( a x) \ \mathrm{d}x=\frac{\sqrt{\pi}}{2} e^{-\large\frac{a^2}{4}}.
$$
Comment: May I ask why you didn't include $-i\sin (\dfrac{\omega t}{2})$. Was it because it's an odd function over a even intervall os the integral win sinus will be zero?


System Center Configuration Manager: Endpoint Protection client install error

Question: EP 22.214.171.124 is installed, version is higher than expected installer version 4.1.522.0
Has anyone see that in the EndpointProtectionAgent.log on a system they have been trying to push the SCCM client to before?  We have a number of servers that haven't reported back to SCCM that their Endpoint Protection is being managed.  Looking at the log noted above has that error.
A snipped from the log:
<code> <![LOG[Service startup notification received]LOG]!><time="16:43:43.819+240" date="06-26-2013" component="EndpointProtectionAgent" context="" type="1" thread="3924" file="fepsettingendpoint.cpp:291">
<![LOG[Endpoint is triggered by CCMTask Execute.]LOG]!><time="16:43:43.819+240" date="06-26-2013" component="EndpointProtectionAgent" context="" type="1" thread="2804" file="fepsettingendpoint.cpp:265">
<![LOG[Deployment WMI is NOT ready.]LOG]!><time="16:43:43.835+240" date="06-26-2013" component="EndpointProtectionAgent" context="" type="1" thread="2804" file="epagentimpl.cpp:725">
<![LOG[Endpoint is triggered by WMI notification.]LOG]!><time="16:43:59.482+240" date="06-26-2013" component="EndpointProtectionAgent" context="" type="1" thread="3556" file="fepsettingendpoint.cpp:154">
<![LOG[Failed to get EP event code under registry key SOFTWARE\Microsoft\CCM\EPAgent]LOG]!><time="16:43:59.498+240" date="06-26-2013" component="EndpointProtectionAgent" context="" type="2" thread="3556" file="epagentimpl.cpp:1334">
<![LOG[Failed to get EP event message under registry key SOFTWARE\Microsoft\CCM\EPAgent]LOG]!><time="16:43:59.498+240" date="06-26-2013" component="EndpointProtectionAgent" context="" type="2" thread="3556" file="epagentimpl.cpp:1339">
<![LOG[EP State and Error Code didn't get changed, skip resend state message.]LOG]!><time="16:43:59.498+240" date="06-26-2013" component="EndpointProtectionAgent" context="" type="1" thread="3556" file="epagentimpl.cpp:153">
<![LOG[Failed to get EP event code under registry key SOFTWARE\Microsoft\CCM\EPAgent]LOG]!><time="16:43:59.498+240" date="06-26-2013" component="EndpointProtectionAgent" context="" type="2" thread="3556" file="epagentimpl.cpp:1334">
<![LOG[Failed to get EP event message under registry key SOFTWARE\Microsoft\CCM\EPAgent]LOG]!><time="16:43:59.498+240" date="06-26-2013" component="EndpointProtectionAgent" context="" type="2" thread="3556" file="epagentimpl.cpp:1339">
<![LOG[State 1, error code 0 and detail message are not changed, skip updating registry value]LOG]!><time="16:43:59.498+240" date="06-26-2013" component="EndpointProtectionAgent" context="" type="1" thread="3556" file="epagentimpl.cpp:205">
<![LOG[File C:\Windows\ccmsetup\SCEPInstall.exe version is 4.1.522.0.]LOG]!><time="16:43:59.498+240" date="06-26-2013" component="EndpointProtectionAgent" context="" type="1" thread="3556" file="epagentutil.cpp:519">
<![LOG[EP version 18.104.22.168 is already installed.]LOG]!><time="16:43:59.498+240" date="06-26-2013" component="EndpointProtectionAgent" context="" type="1" thread="3556" file="epagentutil.cpp:232">
<![LOG[EP 184.108.40.206 is installed, version is higher than expected installer version 4.1.522.0.]LOG]!><time="16:43:59.498+240" date="06-26-2013" component="EndpointProtectionAgent" context="" type="1" thread="3556" file="epagentutil.cpp:265">
</code>
A few of these systems were previously manged under a dev SCCM 2012 SP1 install, and some under FEP 2010.  Now we are deploying from a new SCCM site that we have setup to these servers.  Does this indicate that we need to update the EP install that we are pushing out?
Comment: We're not using Endpoint Protection however I've had all kinds of weird issues when some systems were managed under a testing implementation of SCCM and then rolled into a new implementation. Let me think about this one, maybe I can generate some leads for you...
Comment: Found the issue.  We broke the Endpoint management out from the default client settings.  Even though the new endpoint client settings were applied to that collection, and of course had a higher pri than the default, the settings were not taking affect.  Might be a bug... we have contacted MS about it.
Comment: Any SCCM 2012 SP1 users out there?
Answer: Buggy acting client settings.  Pulling back the client settings and redeploying them seemed to fix it.  We also deployed directly to a sub collection, vs just to a base, and it worked.


Integrate external DB users via their API in Drupal 7

Question: I want to integrate an external API (REST) to login users which are on that external database using the drupal 7 login form on my site.
I have the API specifications for Login, Registering, Getting member details and Check logged in. I also have a URL to test GET and POST requests on that external DB.
How do I integrate it with Drupal database so that users can log in using either Drupal's DB or external DB (integrated with the API)?
I have just discovered Services module but not sure if it is of any help.
I'm not an expert in creating custom modules either so any sample code or any pointers would really help here.
NOTE: External API requests return XML output
Answer: In order to implement external authentication you need to alter the login forms (user_login and user_login_block) to alter their validation handlers.
The default validation handlers for the forms are user_login_name_validate(), user_login_authenticate_validate() and user_login_final_validate(). You will need to replace user_login_authenticate_validate which is used to check the supplied username/password against local users table. Your replacement should invoke your API to handle the authentication.
Depending on your need, you may want to provide automatic registration (on the Drupal site) of new user on authentication. In such as case, you can use the user_external_login_register() function to create the account from your user_login_authenticate_validate replacement.
To map the Drupal user to the user on the external system, Drupal provides the user_get_authmaps() and user_set_authmaps() functions. Note that that user mapping mapping is automatically handled when using the user_external_login_register() and user_external_load() functions.
The perform your HTTP requests, you can use the drupal_http_request() function which usually do the job and support HTTPS. Of course, you can also use another HTTP library.
All of this will have to be done in a custom module and you will need good understanding of Drupal's Form API.
A comment on the documentation page for user_external_login_register() provides detailed explanation of the complete process.
Note: The Services module is useful when you need a read/write HTTP-based API for your Drupal site's data. In your case, it would not be usefull since you need to consume an existing API to authenticate the users.
Comment: Indeed, the solution presented on http://omegadelta.net/ follow the same pattern as I suggested. It even reminded me of the `user_external_login_register` function used to create user account on authentication and manage the authmaps. Since you need to authenticate the user through a call to your API over HTTP, you would use drupal_http_request() to perform that call in your replacement of `user_login_authenticate_validate`.
Comment: Thanks for your help Pierre. Your solution looks somewhat like this one [here.](http://omegadelta.net/2011/03/23/custom-authentication-with-drupal-7/) Where do I place/use the drupal_http_request() in the module (If I end up creating one for this solution)?
Comment: Thanks Pierre. That really showed me the way to go ahead with this situation. :)


Janrain server side response to Android app

Question: Here's the documentation on how to implement Janrain engine in Android.
Example of server side response is here.
Quote: "As necessary create and return access tokens or session cookies in your endpoint's response.", I don't want to save data on session or cookies, I want to get just plain text to my app as response.
How can I do this?
Also I work with php, I don't really get ruby example.
Answer: There is some sample PHP code at https://github.com/janrain/Janrain-Sample-Code/blob/master/php/rpx-token-url.php that returns a block of JSON. You could customize this code to return the plain text response you're looking for.


Missing Main Page Content Block in Blocks List

Question: I have the region for Main page content in my theme.info file which is regions[content] = Content. But still, in Blocks list, there is no Main page content block. This is causing me problems.
Can i re-create a new block with the same name. What should i do?
Comment: You also should modify page.tpl.php file of your theme to output there your new region. For more instructions you should give to us more info: at least what theme are u using?
Answer: Recently had this issue. When I enabled my custom theme some files were missing and Drupal threw some errors and warnings. After adding the files everything worked fine except the Main page content block was missing.
To fix, I did the following:

Set Bartik as the default theme
Navigated to the block interface and configured the Main page content block (which was showing now that Bartik was the default theme)
My custom theme was still enabled so it showed up in Region settings and I was able to select a region

Set my custom theme as the default again and all was good. Main page block was showing again.


Not able to set Admob Ads at bottom in ConstraintLayout

Question: I just set my webview in ConstraintLayout. I am not able to show Banner at bottom of activity. It always overlays the action bar. All i want to show id first Action bar then webview then at bottom banner ads.
Below image show the current layout:

Here is my activity_browser.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:fitsSystemWindows="true"
    tools:context=".webBrowser.BrowserActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?android:attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include
        android:id="@+id/include"
        layout="@layout/content_browser_full" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="-7dp"
        android:indeterminate="true"
        android:visibility="gone"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="@string/banner_ads"/>
</android.support.design.widget.CoordinatorLayout>

Here is content_browser_full.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fadeScrollbars="false"
    android:scrollbarFadeDuration="0"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="52dp"/>

</android.support.v4.widget.NestedScrollView>

Answer: May be you already solve but some other will help this.
You need to add bellow code
ads:layout_constraintBottom_toBottomOf="parent"

full code:
 <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        android:layout_gravity="bottom"
        ads:layout_constraintBottom_toBottomOf="parent"
        ads:adUnitId="@string/banner_home_footer">
    </com.google.android.gms.ads.AdView>

Answer: I can not see ConstraintLayout but only a CoordinatorLayout The easy way is to add this line:
 android:layout_gravity="bottom"

to your AdView. Bear in mind this will also be on top of your browser(WebView) but a the bottom of the Screen. If it fits your need use it, else elaborate what you want.
Comment: Yes, its my mistake. Its CoordinateLayout.
Comment: So did you try my solution?? @ShahbazAlam


Embedding QGraphicsScene into QML

Question: I'm writing a card game with Qt. Initially, the UI was written in C++ with Qt Widgets, but after porting to Android (Qt Widgets app looks awkwardly there, because of the settings and color choose dialogues being almost unusable) I've decided to switch into QML, keeping game logic in C++.
However, the part of game logic which cannot be separated from visual rendering (e.g. players place cards on the table) is written in QGraphicsScene-derived class:
class Table : public QGraphicsScene
{
    // some code omitted
}

Table::Table(QObject* parent) : QGraphicsScene(parent) { /* ... */ }

I've tried to register Table as QML type via qmlRegisterType(), but it doesn't work for me - placing Table object into QML results in the segfault in QGraphicsScene constructor. Here's the part of the backtrace:
#0  0x19312fa4 in std::__atomic_base<int>::load (__m=std::memory_order_relaxed, this=0xabababab) at C:/MINGW530/i686-w64-mingw32/include/c++/bits/atomic_base.h:396
        __b = std::memory_order_relaxed
#1  QAtomicOps<int>::load<int> (_q_value=...) at ../../include/QtCore/../../src/corelib/arch/qatomic_cxx11.h:227
No locals.
#2  0x193e1780 in QBasicAtomicInteger<int>::load (this=0xabababab) at ../../include/QtCore/../../src/corelib/thread/qbasicatomic.h:102
No locals.
#3  0x1940f7a7 in QtPrivate::RefCount::isShared (this=0xabababab) at ../../include/QtCore/../../src/corelib/tools/qrefcount.h:101
        count = 571316634
#4  0x1937f29d in QList<QGraphicsScene*>::append (this=0x139914c, t=@0x112e8cc: 0x362be1a8) at ../../include/QtCore/../../src/corelib/tools/qlist.h:580
No locals.
#5  0x192a1188 in QGraphicsScenePrivate::init (this=0x362be258) at graphicsview\qgraphicsscene.cpp:334
        q = 0x362be1a8
#6  0x192a61e9 in QGraphicsScene::QGraphicsScene (this=0x362be1a8, parent=0x0) at graphicsview\qgraphicsscene.cpp:1636
No locals.
#7  0x00402f53 in Table::Table (this=0x362be1a8, parent=0x0) at ..\OpenFool\src\table.cpp:41
No locals.
#8  0x0041239a in QQmlPrivate::QQmlElement
::QQmlElement (this=0x362be1a8) at J:/Qt/Qt5.8.0/5.8/mingw53_32/include/QtQml/qqmlprivate.h:99
No locals.
#9  0x0041235d in QQmlPrivate::createInto
 (memory=0x362be1a8) at J:/Qt/Qt5.8.0/5.8/mingw53_32/include/QtQml/qqmlprivate.h:108
No locals.
#10 0x01c7a5d5 in QQmlType::create (this=0x1398550, out=0x112ed70, memory=0x112ed4c, additionalMemory=72) at qml\qqmlmetatype.cpp:761
        rv = 0x362be1a8

So, is there a way to re-use the code of Table without re-writing it into QML?
Answer: As far as I know, the render engine of QtWidget and QML is fundamentally different, so it would be hard to register a Widget as a QML Type.
So I think the two best options for you are:

Adapt it to QML
Extend QQuickPaintedItem to have a most similar API to your QGraphicsScene so the changes you need on your code are only minimal. (*Thank you, @BenjaminT for pointing me to QQuickPaintedItem rather than Context2D)
Comment: Context2D has poor performances, QQuickPaintedItem is faster and should be preferred (even more in this case since the code is already C++)
Comment: I would even recommend to use `QQuickItem` instead of `QQuickPaintedItem` since the last uses OpenGL it should work more faster.
Comment: AFAIK `QQuickPaintedItem` can do that, too, if you set `QQuickPaintedItem::RenderTarget` to `QQuickPaintedItem::FramebufferObject`, or do I err?
Comment: Thank you! This seems to me as the most plausible solution.
Answer: You need a QGraphicsView widget to display a QGraphicsScene.
However you cannot embed a widget in a Qt Quick 2 interface. (If you use Qt Quick 1 see @xander answer).
But there is a solution if you take the problem the other way around. You could make a Qt Widget HMI, display your scene in a QGraphicsView widget and display the Qt Quick parts of your using one or more QQuickWidget. This has some limitations, but if you do not overlap the QtQuick and QtWidget parts this works well and can be quite efficient
Answer: As far as I know you can't embed a QWidget into Qt Quick 2 elements, however if you can use Qt Quick 1 it's still possible with a custom QDeclarativeItem and a QGraphicsProxyWidget.
Example with a custom QPushButton:
#include <QtDeclarative>
#include <QtGui>

class PushButtonItem : public QDeclarativeItem {
  Q_OBJECT
public:
  PushButtonItem(QDeclarativeItem *parent =0) : QDeclarativeItem(parent) {
    pb = new QPushButton("text");
    proxy = new QGraphicsProxyWidget(this);
    proxy->setWidget(pb);
    proxy->setPos(-pb->sizeHint().width()/2, -pb->sizeHint().height()/2);
  }
private:
  QPushButton *pb;
  QGraphicsProxyWidget *proxy;
};

#include "main.moc"

int main(int argc, char **argv) {
  QApplication app(argc, argv);
  QDeclarativeView view;
  qmlRegisterType<PushButtonItem>("PushButton", 1, 0, "PushButtonItem");
  view.setSource(QUrl::fromLocalFile("file.qml"));
  view.show();
  return app.exec();
};

In your case you might even replace the QGraphicsProxyWidget with your QGraphicsScene directly because QGraphicsScene is a base class in Qt Quick 1 (was replaced in Qt Quick 2).

Embedding QGraphicsScene into QML


I have 6 wan connections, what's the best way to load balance them?

Question: 5 diferent companies are going to share the same building, and each one of them have one internet link. I have to use all of the links because of bureaucracy stuff. My server only have 4 LAN boards. What's the best solution for this scenario? I have an Extreme X460 Switch and I'm using PFSense!
Is it possible to do link aggregation in the Extreme before the link arrive on the PFSense?
Thanks and sorry for my poor English!
Answer: Unless these companies merge, you should let each companie use their own router with their public IP
That will allow them to create their own VPN tunnel and most importantly they will be separated.
If you really need only one router you should use one that support VLAN tagging per port and that support all those IP. You create the routing rule (vlan vs what public ip they use) I dont know if pfsense allow that
Comment: The problem is: they are going to be mixed all over the building, and those are sister companies. If the companies were separated by floors or something I could separate the infrastructure.
I think the solution is going to be more network cards for the server, link aggregation on the switch + vmware
Comment: +1 for vlan and though MAC spoofing is a thing I would filter on MAC to help with future diagnostics - not sure you need more network cards as long as your OS supports VLAN and virtual interfaces eth0:1 eth1:3 things like that.


Issue certs with Windows CA?

Question: I recently installed AD cert services.  Right now everything in my home network is using certs issued by my firewall.  On the firewall, I can sign CSR's, I can simply create certs and define the lifetime, etc.
My question is, is there a way on a Windows CA to just "Make a cert"?  I've been googling for a while and everything I'm finding is pointing to CSR's.  I can't find anything on how to simply create a cert signed by the Windows CA from scratch so to speak like I can on my firewall.
Thanks in advance.
Comment: CA requires a CSR which contains signed public key and optional information about the certificate you need. So `make a cert` without CSR is kond of pointless.
Answer: One way is to use certreq.exe to create a CSR, and process it on the CA.
certreq.exe -new request.inf somename.contoso.com

Then save the issued certificate and fulfill it on the machine that created the CSR:
certreq.exe -accept <filename>

It's also possible to configure the CA for direct enrollment using certreq.
https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/certreq_1
Request.inf:
[NewRequest]
Subject = "CN=somename.contoso.com, OU=Headquarters, O=Contoso Inc, L=Washington, S=DC, C=US"
Exportable = TRUE
KeyLength = 2048
KeySpec = 1 ; Key Exchange and Digital Signatures
KeyUsage = 0XB0 ; Digital Signature, Key Encipherment, Data Encipherment
MachineKeySet = TRUE
ProviderName = "Microsoft RSA Schannel Cryptographic Provider"
RequestType = PKCS10
HashAlgorithm = SHA256

[EnhancedKeyUsageExtension]
OID=22.214.171.124.18.104.22.168.1 ; Server Authentication
OID=184.108.40.206.22.214.171.124.2 ; Client Authentication

Comment: Ok, but where in all of that do you define the lifetime of the cert?
Comment: In the template you create.

Issue certs with Windows CA?


How to host Spring boot application on cpanel?

Question: I have a Spring boot application and i want to host it in my VPS server (cpanel).
I'am using the last version of cpanel & WHM with easyapache 4.
I exactly followed the steps on this website : https://dzone.com/articles/deploying-war-file-in-easy-apache-4-tomcat-experim
But, nothing on the result. I got Error 404 when i access to my domain name.
If anyone can help me on this or anyone done this before could give the exact steps to follow.
Thank you.
Answer: I had difficulty with that too, use the link in the attachment that you will have an orientation, but it may be that not everything is 100% the same. If you have any questions during the process, you can contact!

change the name of the .war file to ROOT.war , and follow all the procedures described in the link;

In the "application.properties" file, add the "server.port" configuration for the port you found in the link (step 2, part 1).
ex: server.port=10003

Open the file "ea-tomcat85/logs/catalina.out" to see the errors thrown

link: https://suporte.hostgator.com.br/hc/pt-br/articles/360038980913-Como-configurar-o-Tomcat-


Bifurcation Near Origin of one parameter families of maps

Question: I am working on a problem out of "An Introduction to Applied Nonlinear Dynamical Systems and Chaos" by S. Wiggins. Section 3 is all about local bifurcations and I am asked to describe the bifurcation of the origin of the following systems, and to compare them.
$$\dot{x}=x-2y+\epsilon x$$
$$\dot{y}=3x-y-x^2$$
I put them in normal form,
$$\begin{bmatrix}\dot{x}\\ \dot{y}\end{bmatrix}=\begin{bmatrix}
1 & -2 \\
3 & -1
\end{bmatrix}\begin{bmatrix}x\\
y\end{bmatrix}+\begin{bmatrix}\epsilon x\\-x^2\end{bmatrix}.$$
I think this is the case because the linear part has eigen values with zero real parts. I'm supposed to introduce a parameter $\dot{\epsilon}=0$ to find the equation of the stable manifold using the standard partial differential equation $$\mathcal{N}(h(x,\epsilon))=0=D_xh(x,\epsilon)\left[Ax+f(x,h(x,\epsilon),\epsilon)\right]-Bh(x,\epsilon)-g(x,h(x,\epsilon),\epsilon)$$.
I think $A$ is the linear part of the above equation, $B$ is zero, $g$ is zero and $f$ is the nonlinear part. I am unsure of how to fully use this equation. My professors lecture is incomplete and I cannot find anything online.
The system that I am comparing it with is $$\dot{x}=x-2y+\epsilon x^2$$
$$\dot{y}=3x-y-x^2$$
Comment: @JohnB well I found the Jordan normal form of the linear part and then transformed the non linear part. I assumed the center manifold is approximated by a quadratic in two variables, $u$ and $\epsilon$, but when I write out the components for $mathcal{N}$ I keep getting only terms that are higher than order two.
Answer: In this case all turns out to be simpler. Note first that the equation can be written in the form
$$
\begin{bmatrix}\dot{x}\\ \dot{y}\end{bmatrix}=\begin{bmatrix}
1+\epsilon & -2 \\
3 & -1
\end{bmatrix}\begin{bmatrix}x\\
y\end{bmatrix}+\begin{bmatrix}0\\-x^2\end{bmatrix}.
$$
The eigenvalues of the matrix $$\begin{bmatrix}
1+\epsilon & -2 \\
3 & -1
\end{bmatrix}$$ are
$$
\frac{1}{2} \left(\epsilon\pm\sqrt{\epsilon^2+4 \epsilon-20}\right)\approx \frac{\epsilon}{2} \pm i\sqrt{5}
$$
for $\epsilon$ very close to zero.

So there are two eigenvalues with negative real part for $\epsilon<0$ very close to zero and here are two eigenvalues with positive real part for $\epsilon>0$ very close to zero.

This implies that you pass from a stable focus to an unstable focus as $\epsilon$ travels from some negative value close to zero to some positive value close to zero (since the eigenvalues have nonzero real part the term $-x^2$ does not change the topological behavior of the linear part in a small neighborhood of the origin).
These are roughly the phase portraits in a neighborhood of the origin:
$\hskip2in$
for small $\epsilon<0$ and
$\hskip2in$
for small $\epsilon>0$.
Comment: This is the way i first approached the problem, but I am being required to use the center manifold theorem and $\mathcal{N}(h(x,\epsilon))$ to approximate the center manifold. Every time i do the calculation for $h$ i get higher order terms and an overdetermined system for the coefficients. Thank you for the in depth answer though
Comment: The center manifold is $3$-dimensional on a $3$-dimensional space when you add $\dot \epsilon=0$ so nobody will do it as you say.
Comment: It seems odd to me as well, considering I did it the way you did the first time, but she said I need to redo it by finding the center manifold and using the parameter $\epsilon$. But now from you I see that the center manifold is 3D since there are 3 eigen values with zero real part. I was using an $h$ with two components. Do I need to adjust that $h$ to three components. If so how would I go  about that? Would all my terms be cubic for the components of $h$?
Comment: I have already replied to what you asked, so please ask a different question if you think that it is appropriate. As I said: nobody will do it as you say, so I really can't help more here. Sorry.


sql query for calculate age from Birth and date field

Question: In my mysql table there is two fields for date of birth and date of death, how can i calculate age by using an sql query?
For example this my table:
id |  DOB        |  DOD
-------------------------------
1  | 02-02-1968  |  07-21-2000
-------------------------------
2  | 08-01-1978  |  14-01-1988

How can i calculate age ?
Please anyone help me!!!
Comment: You have to accept some answer if you hope that someone keeps on answering you.
Comment: Moreover I hope that you've used date type to store dob and dod and not string. If this is the case consider to use str_to_date() function in order to change your format.
Answer: SELECT TIMEDIFF(DOD, DOB ) as TOTAL_AGE FROM TABLE;

Answer: select year(dod)-year(dob)-(right(dod,5)< right(dob,5) ) as age from table


Imprimir dados da Tabela MySQL em PHP

Question: Tenho o seguinte código:
<?php
//iniciando a conexão com o banco de dados
include_once("conectar.php");
if (!$strcon) {
 die('Não foi possível conectar ao Banco de Dados');
}

$sql = mysqli_query("SELECT * FROM cadastro");
$exibe = mysqli_fetch_assoc($sql);
echo "
";
echo  "
Nome:	";
echo "".$exibe["Nome"]."
";
?>

Já tentei criar a estrutura de várias formas.
Os resultados exibidos em HTML para mim são:

Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\Program Files\EasyPHP-Devserver-17\eds-www\Sites\Projetos\Agenda\consulta.php on line 18
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in C:\Program Files\EasyPHP-Devserver-17\eds-www\Sites\Projetos\Agenda\consulta.php on line 19
  Nome:

Minha linha 18:
$sql = mysqli_query("SELECT * FROM cadastro");

Minha Linha 19:
$exibe = mysqli_fetch_assoc($sql);

Já modifiquei os parâmetros de várias formas, mas não encontro o problema exato.
Answer: Você só tá passando um parâmetro para a função mysqli_query() que é a consulta em si. Sendo o correto passar uma variável de conexão seguida pela consulta:
$conexao= mysqli_connect("localhost", "my_user", "my_password", "world");
$sql = mysqli_query($conexao, "SELECT * FROM cadastro");

Provavelmente essa variável de conexão já deve estar sendo construída no seu arquivo "conectar.php" sendo a $strcon, que você no começo do script pra validar a conexão, só sendo necessária passar ela como primeiro parâmetro na função, ficando assim:
$sql = mysqli_query($strcon, "SELECT * FROM cadastro");

Retirado da documentação oficial aqui
Comment: Agora ficou show!
Comment: a variável de conexão é `$strcon`
Comment: Provavelmente, ele só deve pegar essa variável que está sendo construída nesse "conectar.php" e passar como primeiro parâmetro.
Comment: Adicionei sua observação na resposta @LeoCaracciolo.

Imprimir dados da Tabela MySQL em PHP


Adicionar cabeçalho na função getJson do JQuery

Question: É possivel adicionar algum cabeçalho na função $.getJson do jQuery?
Estou tendo problemas de cross-origin e li em alguns lugares que a adição de algumas informações de cabeçalho podem resolver esse problema.
Comment: Cross Origin deve ser permitido no servidor. Sabe se o endpoint que está querendo consumir tem essa permissão?
Comment: Qual o seu problema, especificamente? alguns sites tem bloqueios de requisições de fora, por isso, pode haver erros de Cross Origin.
Comment: Eu acho que sim, pois só da problema e uma das chamadas do getJson (essa é a que retorna mais dados)
Comment: Tento captura dados do site http://spcultura.prefeitura.sp.gov.br/ mas quando tento capturar os agentes da problema de cross-origin
Comment: Você está tentando capturar dados em json?
Comment: Sim, capturando em JSON
Answer: $.getJSON é um simplificado de:
<code>$.ajax({
    dataType: "json",
    url: url,
    data: data,
    success: success
});
</code>
Portanto, para setar um cabeçalho, é possível uma chamada como:
<code>$.ajax({
    dataType: "json",
    beforeSend: function(request) {
        request.setRequestHeader("Authority", authorizationToken);
    },
    url: url,
    data: data,
    success: success
});
</code>
Porém, se o problema é CORS, a solução somente será se o endpoint (servidor) permitir o CORS. Veja essa resposta para entender o que ele é e essa que contém um exemplo de como permitir. Mas se você não tiver autonomia para mudar alguma configuração no servidor, nada poderá ser feito no front-end.
Comment: Utilizando getJSON a requisição fica rodadno por cerca de 2:30 minutos e retorna o erro 504, utilizando ajax com o cabeçalho `request.setRequestHeader("Access-Control-Allow-Origin", "*");` a requisição é recusada de forma instantânea e retorna o erro 404. Isso pode ser indicativo que o servidor que não permite cross-origin?
Comment: 404 é not found. A URL da requisição está correta? Quando não permite, no console do browser ele diz a requisição foi bloqueada pelo cors.
Comment: A URL está correta, é a mesma que usei em getJSON, até conferi o erro pra ver se estava igual e estava. Também está dizendo que foi bloqueado por CORS mas mudou o código de erro de 504 para 404.
Comment: 404 é not found, 504 é tempo esgotado e 401 é não autorizado. Geralmente quando o problema é somente CORS, o status code é 401.
Comment: A quantidade de dados a ser buscada é bem grande, eu havia tentado limitar a quantidade de dados a ser buscada e assim funcionou. Tem como aumentar o tempo limite?
Comment: Existe o time out do Ajax, mas vai servir só se passar de 15 minutos (que o valor padrão que ele aguarda). Mas se o site retorna retornar timeout depois de um certo tempo, volta ao mesmo caso do cors, não tem o que fazer :/
Comment: Obrigado pela ajuda :)


Use Sleuth trace-and span id in log4j2 patternlayout

Question: I want to use sleuth with log4j2. Therefor I used the .properties configuration.  The problem is I can't get the sleuth parameters to the logs with my patternlayout.
Can you tell me which pattern to use to get the sleuth parameters. In my case they are always empty.
What I did:
Like mentioned here [%X{spanId}] and set spring.sleuth.log.slf4j.enabled=false
My whole pattern looks this way:
date: %d{ISO8601} loglevel: %X{loglevel} [%X{spanId}] user-agent: %X{useragent} servicename: %X{servicename} class:%X{classname} method:%X{methode} Line: %L message: %m%n

To insert the data I use the ThreadContext Object:
ThreadContext.put("trace", logdata.getTrace());

When I insert it this way I get the following for example:
NoopSpan(91406b61b7d23455/05657a824bc5c9e2)

But I want to have the data split up so i can use it with the elk stack
EDIT:
When I use
System.out.prinln(MDC.get("X-B3_TraceId"))

in my controller class I get rhe right output. But when I use in my pattern %X{X-B3_TraceId} the output is null.
UPDATE:
%X{X-B3_TraceId} works. I've had an issue with my asynchronous logging workflow.
Answer: try with this pattern :
 <property name="CONSOLE_LOG_PATTERN"
          value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>

Comment: In general I just need to know if the trace and the span id are in the ThreadContext and how I can integrate them in my logging pattern
Comment: when I use
appender.error_file.layout.type = PatternLayout and appender.error_file.layout.pattern = the pattern you mention then I get the following:%clr(2019-09-27 08:00:55.375){faint} %clr(ERROR) %clr( ){magenta} %clr(---){faint} %clr([pool-2-thread-1]){faint} %clr(error_logger                            ){cyan} %clr(:){faint}  This is an error log.


Teaching magento flow

Question: I am working with magento from last few years and now I got chance to teach magento to few of my juniors. I know most of the stuffs regarding it but I am looking for perfect teaching steps so that my juniors who have 2-3 years of experience in PHP can learn and grasp it properly.
According to my observation:
1) Give overview of magento, whats it and about zend on which its based.
2) Explaining front-end flow and how pages, product,categories are added in admin etc.
3) Admin: Order,catalog, attributes, extension configuration etc.
4) Extension development and so on.
Please provide more suggestions so that I can train them in better way.
Comment: Great question, but no one answer will suffice. Moving to Meta.
Comment: good and looking for few awesome responses from community.
Comment: I have started teching magento to my team. I am looking response from magento genius present on magento community. There input would will benefit me and my team.
Comment: Ben, I'm less familiar with Meta, but this post appears to fall outside of what's supposed to the core of Meta Magento SE :...Magento Stack Exchange users to communicate with each other about Magento Stack Exchange (asking questions about how the websites work, or about policies and community decisions)" http://magento.stackexchange.com/help/whats-meta  Isn't this the kind of question that SHOULD be on Magento SE, but be a Community Wiki instead of a Normal Q&A?
Comment: @ benmarks ..Can you please provide your input. I want this for magento2 and more detailed will be benefical for me. Thanks Sir
Answer: What I would do is :

First Introduce Magento : This involves

What is the purpose ?
When it is built ?
Small description on history of Magento and
Why it  is important to study ?

Now describe Magento folder structure : Try to give some idea on how magento is distributed the application logic in folder wise.
Introduce admin section of Magento : The purpose of this is to give a proper understanding on what are the features that magento offers by default from admin side.
Introduce frontend section of Magento : Show the frontend, so that they will understand how frontend is connected with backend. You can use sample data installed magento instance for this.
Modular structure of Magento :- It is time to explain

What is a module ?
Importance of module in Magento.
Different codePools in Magento and their purposes.
May be you can  introduce some core modules and their structure.
Finally briefly explain how modules work together.

URL processing :- It is now the time to explain how magento process the url. This involves :

General url structure of magento.
Frontname, controller and action theory.
Default routers in magento and what are their purposes.
Show an example.

Page Rendering process :- You can now deal with rendering of a particular page in Magento. This involves :

What is layout ? How can we specify layout structure in Magento.
What is block ? How they relate to a layout ?
What are layout update handles and how they relate to a page request?
Then explain how blocks, layout update handles together work and thus constitutes a page.

A small "Hello World" Module - Magento study actually starts when you creates a module in Magento. The above steps are just preliminary understanding that we required in this system to attempt to develop our first module. This involves

Activation file of the module and it is importance
Which codepool is going to hold our helloworld module and why.
Define a block and layout update xml file in config.xml. It is very important to describe the purpose and importance of configuration file for a module.
Use layout update xml file declare your own block and show how layouts and blocks work together in Magento.

Introduction to Model : It is perfect time to introduce Model section and it's importance. This involves.

Normal model and EAV model, How they differ
Importance of EAV model. Where they are using in default Magento.
May be you can explain setup classes and it's importance.

Module that involves a CRUD operation : This can be considered as an advanced topic. It involves

Define a new entity in Magento.
Define new entity collection
How can use new table for an entity
The Magento way of creating, reading, updating, deleting an entry from table.

List is endless and make an impression at the end that, no one in the world who completely knows Magento fully. Because that is an ultimate truth and I believe that is the big lesson that we really need to understand and teach.
Good luck :)
Comment: Thx it will really help and looking for more responses.
Comment: Sir .....   Voted Up your answer. Can you please provide detailed info for magento2 as well. I am also on initial stage of magento2 so it will beneficial for me and my team as well. Thanks

Teaching magento flow


Listar telefones de usuários a partir de um join sem duplicar as linhas

Question: Boa noite,
Galera, estou com o seguinte problema:
Preciso fazer um join em duas tabelas, USUARIO e CONTATO.
Cada usuário possui mais de um contato (Telefone), por isso quando listo os dados ele me retorna linhas "duplicadas" com telefones diferentes pois, EX:
ID  | Nome      | Telefone
1   | Felipe    | 968181444
1   | Felipe    | 37056781
2   | Claudio   | 37059999
2   | Claudio   | 968899999

É possível eu criar uma coluna dinâmica de telefone para listar os dados desta forma  abaixo?
ID  | Nome      | Telefone 1    | Telefone 2
1   | Felipe    | 968181444     | 37056781
2   | Claudio   | 37059999      | 968899999

Pesquisei muito no google, achei algo sobre PIVOT mas não consegui desenvolver algo parecido pro que eu preciso.
Segue a query:
SELECT u.ID, u.NOME, c.TELEFONE
FROM USUARIO u INNER JOIN CONTATO c
ON c.USUARIO_ID = u.ID
ORDER BY u.NOME

Alguma solução pra isso?
Comment: Coloque na sua questão o código que já testou para tentar chegar a uma solução.
Comment: Isso não será fácil de fazer, visto que o número de telefones é dinâmico. A única forma que talvez solucione é com SQL dinâmico.
Comment: Oi, Philippe, estava verificando aqui e tem um [artigo do StackOverflow-EN](https://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query) que responde sua pergunta.
Comment: Tente com subquery, algo do tipo: SELECT u.usuario_id AS usu , u.nome , c.telefone AS telefone1,
(SELECT telefone from telefone t where t.usuario_id = u.usuario_id AND t.telefone != telefone1 LIMIT 1)   AS telefone2
FROM usuario u INNER JOIN telefone c
ON c.USUARIO_ID = u.USUARIO_ID
GROUP BY u.usuario_id
ORDER BY u.nome
Comment: Pesquise pelo operador pivot.
Comment: Consegui através da dica do graciomar.
Coloquei uma subquerie para o telefone 2 para criar auma nova coluna.
Comment: https://docs.oracle.com/cd/E11882_01/server.112/e41084/functions089.htm#SQLRF30030 ,  listagg cria uma só coluna mas concatena os valores , outra solução e , tendo algo qu identifique fazer um case com max e group by
Answer: Consegui através da dica do graciomar. Coloquei uma subquerie para o telefone 2 para criar uma coluna, com uma mudança, tive que inserir uma coluna na tabela CONTATO para saber se o telefone é 1º ou 2º. Não é a forma mais elegante mas resolve.
SELECT DISTINCT u.ID as ID, u.NOME as NOME, (select
t1.TELEFONE FROM CONTATO t1 WHERE t1.USUARIO_ID = c.ID AND t1.TELEFONE_POS =
'1')  as TELEFONE, (select t2.TELEFONE FROM CONTATO t2 WHERE t2.USUARIO_ID =
c.ID AND t2.TELEFONE_POS = '2') AS TELEFONE2
FROM USUARIO u INNER JOIN CONTATO c
ON c.USUARIO_ID = u.ID
ORDER BY u.NOME