non normal distribution and normal distribution ttest

Question: I have one data is normal distribution (VAR00004) and another data is non normal distribution (VAR00002). If I want to compare this both data, what should I do in the T-test or is there another available test?

The both Graphs are showing here too.
Comment: How you want to handle this depends on a couple of things.  1) What hypothesis you want to test.  That is, if you are interested in the means *per se*.  2) The distribution of the data (or underlying population) of the two groups.  If one is very skewed, comparing means may not be the most meaningful comparison. ... It may be helpful if you can post histograms of each group of observations.
Comment: @SalMangiafico I have updated my post. thks
Comment: My two cents:  The distributions are somewhat similar.  And the sample size is relatively small. ... If you are interested in comparing means, a permutation test should work well.  However, for comparing two samples, there are many measures you could look at.  There are the means.  The Wilcoxon-Mann-Whitney test will examine the probability that an observation in one group will be larger than an observation in another group (stochastic dominance).  You could also compare medians, another quantile (like the 90th percentile), the overall distribution, and so on.
Comment: @SalMangiafico With sample sizes 31 and 26 respectively, wouldn't it be challenging to compare the 90th percentiles?
Comment: @dipetkov , you have a point.  But it's no different that estimating the median with a sample with an even number of observations:  the quantile has to be interpolated either way.
Answer: If one population has a non-normal distribution, you should try using a nonparametric test such as the Wilcoxon rank-sum test to test whether distributions differ. Nonparametric tests do not make assumptions about normality.
Comment: +1, since this is a viable solution. (And someone downvoted without comment). ... However, the Wilcoxon rank sum test is ***not*** under most circumstance a test of the medians.
Comment: @SalMangiafico So should I use this Wilcoxon rank sum test?
Comment: @SalMangiafico thanks for the clarification, I should have specified the location shift assumption.

Regardless, a Wilcoxon rank sum test should be used here.
Comment: Just to peevish, I also dislike using the phrase "to test whether distributions [ or populations ] differ".  It seems that we use this phrasing a lot when teaching, e.g.   *t*-tests.  But that doesn't really capture what the test is testing for.  For example, `A = (1,1,1,1,1,5,5,5,5,5); B = (2,2,2,2,2,4,4,4,4,4)` . Clearly the distributions are different, but a rank-sum test will return a *p*-value of 1.  As will a *t*-test.  But a Kolmogorov-Smirnov test will give a different result.


How should I filter my VMWare Logs?  What should I search for?  What should I exclude?

Question: My VMWare logs are full of SSL errors and some other things that appear less than important.  (e.g. SSL Errors from the admin console)
What is the best way to extract valuable information from these logs, in hopes of providing better/more reliable service?
I'm looking for specific key words or phrases that will assist in this.  I'm not needing regex expressions, just english words to focus on or ignore.  My intent is that I'll later tie this into my monitoring solution.
Answer: There are two basic methods.

Run the logs through a filter that will extract those things you do want to see.
Run the logs through a filter that will ignore those things you don't want to see.

There are an almost infinite number of way to do the filtering. What will work best for you will depend on just what you want to see and what your level of skill is in scripting and/or programming. My personal preference is to parse the logs through a Perl script that will ignore all those things I don't want to see. The output can be anything from a simple text file to an Excel spreadsheet, depending on what logs I'm processing. Of course the details of the implementations are beyond the scope of SF and are a better fit for StackOverflow.
Comment: Perhaps I'll revise the question so I can get the SO community to recommend something
Comment: Thank you... do you have any key words I should search for ignore based on your VMWare Experience?  Do all "errors" have "error" in the string?  There doesn't appear to be a logical structure to the class of each line... it's more like a kernel braindump when I look at it.
Comment: @makerofthings7, this is where it gets hard. You need to study the log format to determine how to create the filters. Not being familiar with those particular logs I can offer no advice in this regard.
Answer: By far the best method I've seen for managing VMware logs is Splunk - I dump all my logs there and create saved searches looking for any unusual errors. I started with Perl scripts / grepping results on a syslog collection server and found my log analysis to still be... lacking.
Simply set your Splunk host as a syslog forwarding destination and add the appropriate listener. Splunk makes the field extraction process easy so cross correlation becomes a much simpler task as well.
The 500 megabyte / day free license and cross platform support made it a great choice for my environment.


Prove that $H$ is normal in $G$.

Question: If $|G| = pn$ with $p > n$, $p$ prime and $H$ is a subgroup of order $p$, then prove that $H$ is normal in $G$.
Comment: @Crostul: Yes, I know the ff characterization of normal subgroup. If $H$ is the only subgroup of order $p$ then $H$ is normal. But I don't know how to show that it is the only subgroup of order $p$.
Comment: what is the condition of $n$ ?
Comment: What have you tried to solve it? Do you know what is the normal core of a subgroup and its properties?
Comment: @SiXUlm: the only condition given is that $n<p$.
Comment: @Crostul: I've also tried in an other way; Since the index of $H$ in $G$ is $n$ and $n<p$. The number of cosets are less than $p$. But I don't know the implication.
Answer: This is a typical exercise which follows quickly from the Sylow theorems.
There are solutions available anyway - Sample final exam solutions, so let me give a help here.
In general we have the following result:
Proposition: Let $G$ be a group of order $p^mn$, where $p$ is prime and $n < p$, then there is only one $p$-Sylow group, which is then normal.
Proof: The number $t$ of $p$-Sylow subgroups divides $n$ and is congruent to $1 \bmod p$. The numbers congruent to $1 \bmod p$ are either $1$ or are greater than $p$, and so greater than $n$. Since $t\mid n$ , we have $t < n$ and so,
$t = 1$.
Comment: The number $t$ denotes the number of $p$-Sylow subgroups. If $t=1$, then it is normal.
Comment: Could you elaborate the proof please?
Comment: Can you say where you got stuck  ?
Comment: The number $t$?

Prove that $H$ is normal in $G$.


Microsoft Exchange

Question: I am using Exchange 2013 Trail version. I am able to receive email from Internet. I have enabled the send connector with asterisk SMTP Domain in Address Space in Scoping. I have forwarded all the appropriate ports in my system.
NOTE: There is no PTR record set by my ISP.
Question: Port 25 is open when I check https://canyouseeme.org/ . With Telnet and Delivery Report I am assuming outgoing 25 port is being blocked by ISP? IF yes, then is there a work around.
I have tried NethServer (Linux Distribution), hMailServer windows setup. By using all these I can receive emails from internet but not able to send to internet.
Locally I am able to send and receive emails.
And Let me know If you need any further information.
Telnet gmail.com 25
220 mail.primeq.gq Microsoft ESMTP MAIL Service ready at Mon, 21 Sep 2020 22:19:19 -0700
451 4.7.0 Timeout waiting for client input
Connection to host lost.

Exchange Admin Center -> mail flow -> delivery reports -> Delivery Report
The last attempt to send the message was at 9/21/2020 9:06:41 PM (UTC-08:00) Pacific Time (US & Canada) and generated the error '[{LED=451 excellbroadband-smtp Cannot connect to server [18.104.22.168]: Cannot assign requested address};{MSG=};{FQDN=};{IP=};{LRT=}]'.

Comment: Your ISP has intercepted your outgoing port 25 connection and redirected it to its own server. You should upgrade to business class ISP service. We cannot support running servers on home network connections.
Comment: Yes, most probably your hoster blocks outgoing connections on that port. That's common practice. Talk to your hoster.
Comment: Thanks for the reply. I believe you are right.

How Can I mark an answer

Any why my question got -1. What needs to be added more and what is reason for down vote.
Answer: Make sure there're no rules blocking the port 25 in firewall, and ISP hasn't blocked your outgoing connection on port 25.
Please check if there were any NDR(undeliverable) messages sent to the senders' inbox folders. At the same time, you could also use the message tracking log to do a trace for these emails, maybe some events with source could help you find the reasons to cause the mailflow issue.

Microsoft Exchange


Weak derivatives of function defined over $\Bbb C$

Question:
Compute $D u$ in the sense of distributions, where
$u =(x+iy)^{-1}$ is a function defined in $\mathbb{C}$ and
$D=\frac{\partial }{\partial x}+i\frac{\partial }{\partial y}$.  (Hint:  use the integration by parts
formula)

The Solution to the question is $2\pi\delta$
I don't know how to solve it Please help me.
Comment: Welcome to MSE! Please read [how-to-ask-a-good-question](https://math.meta.stackexchange.com/q/9959/418542), and `edit` your post accordingly to increase your chances of success (add context, source, definitions, attempts). Lastly, please avoid [reposting](https://math.stackexchange.com/q/3946220/418542).
Answer: Show that $D\frac1{x+iy}$ is a radial distribution, with $\Phi(z)=\int_0^1 \phi(e^{2i\pi t}z)dt=\varphi(|z|^2)$ we get
$$\langle D\frac1{x+iy},\phi \rangle=
\langle D\frac1{x+iy},\Phi \rangle=-\langle \frac1{x+iy}, D\Phi\rangle$$ $$=-\int_0^\infty \frac1{re^{it}} \int_0^{2\pi}  D\Phi(re^{it}) dt rdr=-\int_0^\infty \frac1{re^{it}}  \int_0^{2\pi} \varphi'(r^2) 2re^{it} dt rdr$$ $$=-2\pi \int_0^\infty \varphi'(r^2)2rdr=2\pi \varphi(0)=2\pi \phi(0)$$


NullReferenceException after deserializing class from JSON

Question: I'm trying to get a Gesture Recognizer to work on unity 3D. The script let's me choose if I'm recording a gesture or comparing to existing ones if not recording.
The problem is
On the first run, it works perfectly: It lets me draw and record gestures and then, after disabling recording, it compares to existing ones to look for a match on a list (templates.templates).
But then after I close the game and re-open it, it debugs "loading successful" and I can see the list of the templates in the Inspector, but it returns an error of NullRefferenceException for the templates or current gesture. I'm losing my mind here. Can you help me notice what behaves differently from the first run and second (after loading the templates from json file) and figure this thing out?
The script is as follows (I serialized every private thing just because...):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;

//******************************************* Gesture Recognizer *********************************************//
//
//      Author:         Andres De La Fuente Duran
//
//      Use:            This script can simply be attached to a camera to function.
//                      It allows for recording of 2D 'gestures', in this case meaning a set of points
//                      representing a continuous motion of the mouse (or touch input).
//                      It also allows for testing 'gestures' against a collection of templates created
//                      with this very same script.
//
//                      Template gestures are saved in a JSON file and loaded into a list at start.
//
//                      The way the recognition works is that a list of points is recorded (relative to
//                      the location of the initial click as (0,0)), scaled to a square resolution of
//                      choice, reduced by interpolation to a set number of points, and then compared
//                      to gestures already processed by this script.
//
//                      This is built for maximum customizability, so you can change the number of points
//                      allowed when recording, the number of points once reduced, the rate of sampling,
//                      and the square ratio gestures are scaled to. Recording the gestures and testing
//                      can be done easily by swithching the 'recording' boolean variable.
//
//                      Some additional notes:      Because the origin of each gesture is the initial
//                                                  point, and comparison follows points in order of
//                                                  recording, directionality is captured by this
//                                                  solution. The gestures do not have to be wildly
//                                                  different for the recognition to be reliable.
//
//                                                  However, you can turn on 'anomaliesTesting' to
//                                                  weight more heavily sudden differences in gestures
//                                                  than constant differences to allow for similar
//                                                  gestures with small modifications or flares.

//****************************************** Recognizer Class ****************************************************//
//
//      Use:        Stores all information for the current gesture being recorded, the existing gestures,
//                  the conditions selected by an editor user, and variables needed to perform recognition.
//                  This is the central class with most of the functionality in the script.
//
//      Fields:
//                  Editor Controlled............................................................................
//
//                  recording:          boolean to control whether to save a gesture or try to recognize it
//
//                  anomaliesTesting:   boolean to control whether to weight sudden differences during
//                                      comparison more than other differences
//
//                  pointsPerGesture:   the size of the array of points stored for each gesture
//
//                  templateSaveName:   the string name of the gesture to be saved when recording
//
//                  samplingRate:       time interval between samples while recording
//
//                  maxPointsAllowed:   the maximum number of points that will be recorded
//
//                  standardRatio:      the size of one side of the square that points will be scaled to
//
//                  devTightness:       the number of deviations from the average difference between the points
//                                      of two gestures that are allowed before they are weighted more
//
//                  anomaliesFactor:    how much extra to weight the differences that surpass the devTightness
//
//                  Control Flow................................................................................
//
//                  gestureStarted:     boolean to execute code to start gesture and to avoid starting anew
//
//                  gestureComplete:    boolean to execute recording of gesture until complete
//
//                  inputReady:         boolean to prevent execution of anything until input is lifted
//                                      so as not to start gestures immediately after one is complete
//
//                  Recording and Recognizing...................................................................
//
//                  gestureFileName:    JSON file to load saved gestures from as templates for recognition
//
//                  startPoint:         the initial point from which to calculate every other point
//
//                  currentPoint:       the last point recorded
//
//                  currentGesture:     the object containing the recorded gesture for current execution
//
//                  currentPointList:   list of points as they are recorded
//
//                  reducedPoints:      array of points for after scaling and mapping of currentPointList
//
//                  templates:          object to store list of template gestures
//
//                  tempTime:           time since last sample
//
//      Methods:    Documentation is above each significant function

public class GestureRecognizer : MonoBehaviour {

    public bool recording = true;
    public bool anomaliesTesting = false;
    public string templateSaveName;
    public int pointsPerGesture = 30;
    public float samplingRate = 0.01f;
    public bool limitSamples = false;
    public int maxPointsAllowed = 100;
    public float standardRatio = 100f;
    public float devTightness = 1f;
    public float anomaliesFactor = 5f;

    [SerializeField]private bool gestureStarted;
    [SerializeField] private bool gestureComplete;
    [SerializeField] private bool inputReady;

    [SerializeField] private string gestureFileName = "gestures.json";
    [SerializeField] private TwoDPoint startPoint;
    [SerializeField] private TwoDPoint currentPoint;
    [SerializeField] private DrawnGesture currentGesture;
    [SerializeField] private List<TwoDPoint> currentPointList;
    [SerializeField] private TwoDPoint[] reducedPoints;
    [SerializeField] private GestureTemplates templates;
    [SerializeField] private float tempTime = 0f;

    private void Awake()
    {

    }

    void Start () {
        LoadTemplates();
        varInitialization();
    }

    #region variable initialization and reset
    private void varInitialization()
    {
        currentPoint = new TwoDPoint(0, 0);
        startPoint = new TwoDPoint(0, 0);
        currentPointList = new List<TwoDPoint>();
        currentPointList.Add(new TwoDPoint(0, 0));
        reducedPoints = new TwoDPoint[pointsPerGesture];
        for (int i = 0; i < pointsPerGesture; i++)
        {
            reducedPoints[i] = new TwoDPoint(0, 0);
        }
        gestureStarted = false;
        gestureComplete = false;
        inputReady = false;
        currentGesture = new DrawnGesture("currentGesture", pointsPerGesture);
    }

    private void varReset()
    {
        for (int i = 0; i < pointsPerGesture; i++)
        {
            reducedPoints[i].SetX(0);
            reducedPoints[i].SetY(0);
        }
        currentPointList.Clear();
        currentPointList.Add(new TwoDPoint(0,0));
        gestureStarted = false;
        gestureComplete = false;
    }

    #endregion

    void Update() {
        tempTime += Time.deltaTime;
        if (Input.GetMouseButton(0))
        {
            if (inputReady)
            {
                if (!gestureStarted)
                {
                    gestureStarted = true;
                    StartGesture();
                }
                if ((!gestureComplete) && (tempTime > samplingRate))
                {
                    tempTime = 0f;
                    ContinueGesture();
                }
                if (gestureComplete)
                {
                    EndGesture();

                }
            }
        } else
        {
            if (gestureStarted)
            {
                EndGesture();
            }
            inputReady = true;
        }
    }

    //******************************************
    //      Save and Load Gestures
    //
    //      SaveTemplates
    //      use:                writes templates to json file
    //      LoadTemplates
    //      use:                called on start to read json templates
    //                          object from file if it's there
    [SerializeField]
    private void SaveTemplates()
    {
        string filePath = Application.dataPath + "/StreamingAssets/" + gestureFileName;
        string saveData = JsonUtility.ToJson(templates);
        File.WriteAllText(filePath, saveData);
        Debug.Log("Template Saved!");
    }
    [SerializeField]
    private void LoadTemplates()
    {
        templates = new GestureTemplates();
        string filePath = Path.Combine(Application.streamingAssetsPath, gestureFileName);
        if (File.Exists(filePath))
        {
            string data = File.ReadAllText(filePath);
            templates = JsonUtility.FromJson<GestureTemplates>(data);

            Debug.Log("Templates Loaded!");

        }
    }

    //***************************************
    //      StartGesture
    //
    //      use:            Set up recording of gesture by
    //                      setting the start point and control bool.
    //                      Called when player first clicks.
    [SerializeField]
    private void StartGesture()
    {
        Debug.Log("gesture started");
        startPoint.SetX(Input.mousePosition.x);
        startPoint.SetY(Input.mousePosition.y);
        gestureComplete = false;
    }

    //***************************************
    //      ContinueGesture
    //
    //      use:            Update min and max x and y values for
    //                      the current gesture being recorded
    //                      and add the new point to the list.
    //                      Called while player holds input down.
    [SerializeField]
    private void ContinueGesture()
    {
        currentPoint.SetX(Input.mousePosition.x - startPoint.GetX());
        currentPoint.SetY(Input.mousePosition.y - startPoint.GetY());
        currentPointList.Add(new TwoDPoint(currentPoint.GetX(), currentPoint.GetY()));
        if (currentPoint.GetX() > currentGesture.GetMaxX())
        {
            currentGesture.SetMaxX(currentPoint.GetX());
        }
        if (currentPoint.GetX() < currentGesture.GetMinX())
        {
            currentGesture.SetMinX(currentPoint.GetX());
        }
        if (currentPoint.GetY() > currentGesture.GetMaxY())
        {
            currentGesture.SetMaxY(currentPoint.GetY());
        }
        if (currentPoint.GetY() < currentGesture.GetMinY())
        {
            currentGesture.SetMinY(currentPoint.GetY());
        }
        if (limitSamples && currentPointList.Count >= maxPointsAllowed)
        {
            gestureComplete = true;
            Debug.Log(message: "Gesture Complete!");

        }
    }

    //***************************************
    //      EndGesture
    //
    //      use:            Resets control bools and other variables
    //                      records gesture to the templates object
    //                      or calls recognition.
    //                      Called when max recording points reached.
    [SerializeField]
    private void EndGesture()
    {
        if (inputReady) inputReady = false;
        gestureStarted = false;
        gestureComplete = true;
        Rescale(currentGesture);
        MapPoints(currentGesture);
        if (recording)
        {
            currentGesture.SetName(templateSaveName);
            templates.templates.Add(new DrawnGesture(currentGesture.GetName(), pointsPerGesture, currentGesture.GetMaxX(), currentGesture.GetMaxY(),
                currentGesture.GetMinX(), currentGesture.GetMinY(), currentGesture.GetPoints()));

        } else
        {
            DrawnGesture m = FindMatch(currentGesture, templates);
            Debug.Log(m.GetName());
        }
        varReset();
    }
    [SerializeField]
    private void OnApplicationQuit()
    {
        SaveTemplates();
    }

    //***************************************
    //      Rescale
    //
    //      use:        scales recorded list of points to a square field
    //                  of a chosen size by multiplication of the factor
    //                  of the desired size it already is
    //                  Called on every gesture after recording
    [SerializeField]
    private void Rescale(DrawnGesture gesture)
    {
        float scale = 1f;
        float xrange = gesture.GetMaxX() - gesture.GetMinX();
        float yrange = gesture.GetMaxY() - gesture.GetMinY();
        if (xrange >= yrange)
        {
            scale = standardRatio / (gesture.GetMaxX() - gesture.GetMinX());
        } else
        {
            scale = standardRatio / (gesture.GetMaxY() - gesture.GetMinY());
        }
        if (scale != 1)
        {
            foreach (TwoDPoint point in currentPointList)
            {
                point.SetX(point.GetX() * scale);
                point.SetY(point.GetY() * scale);
            }
        }
    }

    //***************************************
    //      MapPoints
    //
    //      use:        maps the list of recorded points to a desired
    //                  number of points by calculating an even distance
    //                  between such a number of points and interpolating
    //                  when that distance is reached upon traversal of the
    //                  list
    //                  Called after scaling on every gesture
    //
    //      param:      gesture:    the object to store the new array
    [SerializeField]
    private void MapPoints(DrawnGesture gesture)
    {
        reducedPoints[0].SetX(currentPointList[0].GetX());
        reducedPoints[0].SetY(currentPointList[0].GetY());
        int newIndex = 1;
        float totalDistance = TotalDistance();
        float coveredDistance = 0;
        float thisDistance = 0;
        float idealInterval = totalDistance / pointsPerGesture;
        for (int i = 0; i < currentPointList.Count - 1; i++)
        {
            thisDistance = PointDistance(currentPointList[i], currentPointList[i + 1]);
            bool passedIdeal = (coveredDistance + thisDistance) >= idealInterval;
            if (passedIdeal)
            {
                TwoDPoint reference = currentPointList[i];
                while (passedIdeal && newIndex < reducedPoints.Length)
                {
                    float percentNeeded = (idealInterval - coveredDistance) / thisDistance;
                    if (percentNeeded > 1f) percentNeeded = 1f;
                    if (percentNeeded < 0f) percentNeeded = 0f;
                    float new_x = (((1f - percentNeeded) * reference.GetX()) + (percentNeeded * currentPointList[i + 1].GetX()));
                    float new_y = (((1f - percentNeeded) * reference.GetY()) + (percentNeeded * currentPointList[i + 1].GetY()));
                    reducedPoints[newIndex] = new TwoDPoint(new_x, new_y);
                    reference = reducedPoints[newIndex];
                    newIndex++;
                    thisDistance = (coveredDistance + thisDistance) - idealInterval;
                    coveredDistance = 0;
                    passedIdeal = (coveredDistance + thisDistance) >= idealInterval;
                }
                coveredDistance = thisDistance;
            } else
            {
                coveredDistance += thisDistance;
            }
            gesture.SetPoints(reducedPoints);
        }

    }

    //***************************************
    //      FindMatch
    //
    //      use:        determines template gesture with the minimum
    //                  average distance between points to the
    //                  currently recorded gesture
    //                  Called after finishing a gesture when not
    //                  recording
    //
    //      param:      playerGesture:  current gesture to be matched
    //                  templates:      object containting list of
    //                                  gestures to compare against
    //
    //      return:     returns gesture object of the minimum
    //                  difference template
    [SerializeField]
    private DrawnGesture FindMatch(DrawnGesture playerGesture, GestureTemplates templates)
    {
        float minAvgDifference = float.MaxValue;
        DrawnGesture match = new DrawnGesture("no match", pointsPerGesture);
        foreach(DrawnGesture template in templates.templates)
        {
            Debug.Log(template.GetName());
            float d = AverageDifference(playerGesture, template);
            Debug.Log(d.ToString());
            if (d < minAvgDifference)
            {
                minAvgDifference = d;
                match = template;
            }
        }
        return match;
    }

    //***************************************
    //      AverageDifference
    //
    //      use:        caluclates the average distance between
    //                  the points of two gestures
    //
    //      param:      playerGesture:  first to be compared
    //                  template:       gesture to be compared against
    //
    //      return:     returns float value of the average distance
    //                  between points of two parameter gestures
    [SerializeField]
    private float AverageDifference(DrawnGesture playerGesture, DrawnGesture template)
    {
        int numPoints = playerGesture.GetNumPoints();

        if (numPoints != template.GetNumPoints())
        {
            Debug.Log("Number of points differs from templates");
            return -1f;
        }

        float totalDifference = 0;

        for (int i = 0; i < numPoints; i++)
        {
            totalDifference += PointDistance(playerGesture.GetPoints()[i], template.GetPoints()[i]);
        }

        return (totalDifference / numPoints);
    }

    //***************************************
    //      AverageDistanceWithAnomalies
    //
    //      use:        calculates the average difference between
    //                  the points of two gestures but weighing
    //                  those which deviate significantly by
    //                  multiplying them
    //                  Both the tightness of this and the factor
    //                  of multiplication are customizable
    //                  above
    //
    //      param:      playerGesture:  first to be compared
    //                  template:       gesture to be compared against
    //
    //      return:     returns float value of the average distance
    //                  between points of two parameter gestures
    //                  with weights
    [SerializeField]
    private float AverageDifferenceWithAnomalies(DrawnGesture playerGesture, DrawnGesture template)
    {
        int numPoints = playerGesture.GetNumPoints();

        if (numPoints != template.GetNumPoints())
        {
            Debug.Log("Number of points differs from templates");
            return -1f;
        }

        float totalDifference = 0;
        float[] sampleDifferences = new float[numPoints];
        float[] sampleDeviations = new float[numPoints];
        float standardDev = 0;

        for (int i = 0; i < numPoints; i++)
        {
            float thisDistance = PointDistance(playerGesture.GetPoints()[i], template.GetPoints()[i]);
            sampleDifferences[i] = thisDistance;
            totalDifference += thisDistance;
        }

        float average = totalDifference / numPoints;

        for (int i = 0; i < numPoints; i++)
        {
            sampleDeviations[i] = Math.Abs(sampleDifferences[i] - average);
            standardDev += sampleDifferences[i];
        }

        standardDev = standardDev / numPoints;

        for (int i = 0; i < numPoints; i++)
        {
            if (Math.Abs(sampleDeviations[i]) > devTightness * standardDev)
            {
                totalDifference -= sampleDifferences[i];
                totalDifference += anomaliesFactor * sampleDifferences[i];
            }
        }

        average = totalDifference / numPoints;

        return (average);
    }

    //***************************************
    //      TotalDistance
    //
    //      use:        calculates the total distance covered
    //                  when traversing the current list of recorded
    //                  points in order of recording
    //                  Called when determining ideal intervals
    //                  for mapping onto desired number of points
    [SerializeField]
    private float TotalDistance()
    {
        float totalDistance = 0;
        for(int i = 0; i < currentPointList.Count - 1; i++)
        {
            totalDistance += PointDistance(currentPointList[i], currentPointList[i + 1]);
        }
        Debug.Log("total distance: " + totalDistance);
        return totalDistance;
    }

    //***************************************
    //      PointDistance
    //
    //      use:        calculates the absolute value of the distance
    //                  between two points using pythagorean theorem
    [SerializeField]
    private float PointDistance(TwoDPoint a, TwoDPoint b)
    {
        float xDif = a.GetX() - b.GetX();
        float yDif = a.GetY() - b.GetY();
        return Mathf.Sqrt((xDif * xDif) + (yDif * yDif));
    }
}

//******************************************************* Templates ******************************************************//
//
//      Use:    Groups gestures to be used for comparison to a player's attempts

[Serializable]
public class GestureTemplates
{

    public List<DrawnGesture> templates;

    public GestureTemplates()
    {
        templates = new List<DrawnGesture>();
    }

}

//******************************************************** Gestures ******************************************************//
//
//      Use:    Groups all information pertinent to a 'gesture'
//              which is essentially a single stroke drawing represented by points
//
//      Fields:     points:     list of points representing the gesture, only populated once a hand drawn gesture is
//                              reduced by the MapPoints method
//
//                  min/max:    these are the minimum and maximum x and y values of the points (starting point
//                              is used as the origin)
//
//                  numPoints:  the size of the points array (set to a variable of the GestureRecognizer class to
//                              keep control there)
//
//                  name:       string that will be returned when matched with a non-recorded gesture
//
//      Methods:    Initializer(2 parameters):  use when creating a new gesture for later use
//
//                  Initializer(7 parameters):  use when copying data from another gesture
//
//                  Reset:                      for use in clearing the gesture used for each player gesture attempt

[Serializable]
public class DrawnGesture
{
    [SerializeField]private TwoDPoint[] points;
    [SerializeField] private string name;
    [SerializeField] private float maxX;
    [SerializeField] private float minX;
    [SerializeField] private float maxY;
    [SerializeField] private float minY;
    [SerializeField] private int numPoints;

    public DrawnGesture(string newName, int pointsPerGesture)
    {
        numPoints = pointsPerGesture;
        points = new TwoDPoint[numPoints];
        name = newName;
        maxX = 0;
        maxY = 0;
    }
    public DrawnGesture(string newName, int pointsPerGesture, float max_x, float max_y, float min_x, float min_y, TwoDPoint[] newPoints)
    {
        numPoints = pointsPerGesture;
        points = new TwoDPoint[numPoints];
        SetPoints(newPoints);
        name = newName;
        maxX = max_x;
        minX = min_x;
        maxY = max_y;
        minY = min_y;
    }
    public void Reset()
    {
        maxX = 0;
        minX = 0;
        maxY = 0;
        minY = 0;
        name = "";
        Array.Clear(points, 0, numPoints);
    }

    public TwoDPoint[] GetPoints()
    {
        return points;
    }
    public void SetPoints(TwoDPoint[] new_points)
    {
        for(int i = 0; i < numPoints; i++)
        {
            points[i] = new TwoDPoint(new_points[i].GetX(), new_points[i].GetY());
        }
    }
    public string GetName()
    {
        return name;
    }
    public void SetName(string n)
    {
        name = n;
    }
    public float GetMaxX()
    {
        return maxX;
    }
    public void SetMaxX(float x)
    {
        maxX = x;
    }
    public float GetMaxY()
    {
        return maxY;
    }
    public void SetMaxY(float y)
    {
        maxY = y;
    }
    public float GetMinY()
    {
        return minY;
    }
    public void SetMinY(float y)
    {
        minY = y;
    }
    public float GetMinX()
    {
        return minX;
    }
    public void SetMinX(float x)
    {
        minX = x;
    }
    public int GetNumPoints()
    {
        return numPoints;
    }
    public void SetNumPoints(int n)
    {
        numPoints = n;
    }
}

//******************************************************** Points ********************************************************//
//
//      Use:    This is a class to maintain 2D coordinates
//
//      Fields:     x:  the x coordinate (relative to the first point when recorded)
//                  y:  the y coordinate (also relative to first point)

public class TwoDPoint
{
    private float x;
    private float y;

    public TwoDPoint(float startx, float starty)
    {
        x = startx;
        y = starty;
    }

    public float GetX()
    {
        return x;
    }
    public void SetX(float new_x)
    {
        x = new_x;
    }
    public float GetY()
    {
        return y;
    }
    public void SetY(float new_y)
    {
        y = new_y;
    }
}

The error is as follows:

NullReferenceException: Object reference not set to an instance of an object
  GestureRecognizer.AverageDifference (DrawnGesture playerGesture, DrawnGesture template) (at Assets/Scripts/GestureRecognizer.cs:475)
  GestureRecognizer.FindMatch (DrawnGesture playerGesture, GestureTemplates templates) (at Assets/Scripts/GestureRecognizer.cs:437)
  GestureRecognizer.EndGesture () (at Assets/Scripts/GestureRecognizer.cs:319)
  GestureRecognizer.Update () (at Assets/Scripts/GestureRecognizer.cs:200)

Important:
I did not develop the script, I'm just trying to make it work.
Thanks in advance!
Comment: [tag:visual-studio] is not an appropriate tag for this question.
Comment: @PeterDuniho in many cases I would also close this as a duplicate but especially for Unity beginners this is often very frustrating. It explains **what** a `NullReferenceException` is and **how** to debug and find it. However, in this specific case it doesn't explain the OP **at all** the **why** this happens and how it can be solved which is not quite trivial for a beginner (see [answer](https://stackoverflow.com/a/60769712/7111561)). Actually I just reopened this in order to post a helpful answer right before you closed it again ;)
Comment: @derHugo: you are welcome to your opinion. I don't share it. As far as I am concerned, no question that has nothing more to the problem statement than "I got this `NullReferenceException`" can be anything but a dupe of the canonical. And that goes double when it's just a wall of code, rather than a proper [mcve]. This question isn't going to help anyone in the future, as there's not enough in it for anyone to find it, should they have the same problem but have done their due diligence. As such, there's no reason to keep it around at all, never mind reopen it.
Answer: In general: Start Debugging your code, go through it line by line so you see exactly what is null.

I just did that and the Problem is as follows:
The class TwoDPoint is not serializable! Thus the field DrawnGesture.points which is of type TwoDPoint[] is also not serializable.
So when you generate the JSON this field is skipped. There are two places where you could already have noted that:

you could have simply confirmed this in the saved file
{"templates":[{"name":"","maxX":245.0,"minX":-4.0,"maxY":263.0,"minY":0.0,"numPoints":30}]}

→ No field named points
you can see that this field points is actually not appearing in the Unity Inspector!

Since the Inspector uses the same Serialization Rules as JsonUtility this should be a hint that something is wrong.

So later for loading the file in LoadTemplates you simply do
templates = JsonUtility.FromJson<GestureTemplates>(data);

but since the field points does not exists in your file and the field is not serializable anyway it is skipped again it keeps the value null for all the loaded templates!

Solution:

Tag your class as [System.Serializable]
[System.Serializable]
public class TwoDPoint
{
   ...
}

this would almost fix it.
The next problem is that this class contains no serializable fields either! You can change this by again tagging them [SerializeField]:
[System.Serializable]
public class TwoDPoint
{
    [SerializeField] private float x;
    [SerializeField] private float y;

    ...
}

Actually the whole getter setter make not much sense in this case ... you could simply make your field public as well
[System.Serializable]
public class TwoDPoint
{
    public float X;
    public float Y;

    public TwoDPoint(float x, float y)
    {
        X = x;
        Y = y;
    }
}

and adjust the rest of the code to directly read and write X and Y instead of using get and set methods. public fields of serializable types are automatically serialized.

The change you can already see in the Unity Inspector! As said: If a field doesn't appear here it won't be serialized via JsonUtility neither - and the other way round.

As you can see there now is a field called points in a template!
It is now also present in the JSON
{"templates":[{"points":[{"x":0.0,"y":0.0},{"x":-1.2672364711761475,"y":-4.435328006744385},{"x":-2.534141778945923,"y":-8.870744705200196},{"x":-3.6529128551483156,"y":-13.34582805633545},{"x":-4.771683692932129,"y":-17.820911407470704},{"x":-5.8904547691345219,"y":-22.295995712280275},{"x":-7.009225845336914,"y":-26.771080017089845},{"x":-8.127996444702149,"y":-31.246164321899415},{"x":-9.246767044067383,"y":-35.721248626708987},{"x":-10.365538597106934,"y":-40.19633102416992},{"x":-11.484309196472168,"y":-44.67141342163086},{"x":-12.603079795837403,"y":-49.1464958190918},{"x":-13.577103614807129,"y":-53.655174255371097},{"x":-14.543621063232422,"y":-58.165592193603519},{"x":-15.510139465332032,"y":-62.67601013183594},{"x":-16.438554763793947,"y":-67.18716430664063},{"x":-15.64819049835205,"y":-71.73175811767578},{"x":-14.857826232910157,"y":-76.27635192871094},{"x":-14.067461967468262,"y":-80.8209457397461},{"x":-13.277097702026368,"y":-85.36553955078125},{"x":-12.486733436584473,"y":-89.91014099121094},{"x":-11.696369171142579,"y":-94.4547348022461},{"x":-8.638381004333496,"y":-96.89103698730469},{"x":-4.163297653198242,"y":-98.00981140136719},{"x":0.31178566813468935,"y":-99.12857818603516},{"x":4.815909385681152,"y":-99.94639587402344},{"x":9.422344207763672,"y":-99.70394897460938},{"x":14.028779029846192,"y":-99.46150970458985},{"x":18.63521385192871,"y":-99.21906280517578},{"x":23.241649627685548,"y":-98.97662353515625}],"name":"","maxX":35.0,"minX":-13.0,"maxY":0.0,"minY":-79.0,"numPoints":30}]}

And it is of course also after loading filled with valid values
Comment: Thank you very much, @derHugo! I was about to lose my mind over this.
As I said, I tried to serialize everything, and didn't notice those last x and y floats were not serialized yet. Dumb me didn't even notice the points missing. Thank you for taking the time, really appreciate it!


Reference Error in javascript and try catch

Question: A try-catch is used on a call to a backend service because there is a chance that it may return an empty response.
When the response is empty, the error is marked:
"ReferenceError: modelInfo is not defined".
The fact that the API might be down and a ReferenceError happens is to be expected.
In order to handle this error, the code is wrapped in a try-catch.
The behavior I expected with the try-catch was that it would error requesting the service info, and jump to 'catch', running that code.
The catch code doesn't run?

        var activeMessage = view.querySelector('#activeMessage');
        var html = '';

        try {

            //This call to the backend could throw a ReferenceError
            ApiClient.getJSON(ApiClient.getUrl("VeraModelInfo")).then(function (modelInfo) {

                html += modelInfo.Name;
                html += '
';
                html += modelInfo.InternalIp;
                html += '
';
                html += '';
                html += '';
                html += 'check_circle_outline';
                html += '';
                html += '  Connected';
                html += ' ';

                activeMessage.style.opacity = 0;
                activeMessage.innerHTML = html;
                activeMessage.style.color = '#303030';

        }
        catch (error) { //This catch doesn't run after ReferenceError

            html += '';
            html += '';
            html += 'circle_remove';
            html += '';
            html += '';
            html += ' No Vera Home Automation Device Detected!';

            activeMessage.innerHTML = html;
            activeMessage.style.color = 'red';
            activeMessage.style.opacity = 1;
            activeMessage.style.display = 'block';

            view.querySelector('#deviceModel').style.display = "none";
        }

Realizing that an Error is not always an Exception...
how to throw an exception to run the catch code when there is a ReferenceError in a request.
Or recognize the ReferenceError to handle the client layout code in another function?
Comment: An error in the `.then()` callback cannot be caught by the `catch` clause; that's what the Promise mechanism is for.
Answer: I ended up (thanks to @Pointy's suggestion) writing this and grasped the idea of Promises, which worked.
 var activeMessage = view.querySelector('#activeMessage');
        var html = '';

        return new Promise(() => {

            ApiClient.getJSON(ApiClient.getUrl("VeraModelInfo")).then(function (modelInfo) {

                html += modelInfo.Name;
                html += '
';
                html += modelInfo.InternalIp;
                html += '
';
                html += '';
                html += '';
                html += 'check_circle_outline';
                html += '';
                html += '  Connected';
                html += ' ';

                activeMessage.style.opacity = 0;
                activeMessage.innerHTML     = html;
                activeMessage.style.color   = '#303030';
                activeMessage.animate({
                    transform   : ['translateX(-200px)', 'translateX(0)'],
                    opacity     : [0, 1]
                },
                    {
                        duration: 300,
                        fill    : 'forwards',
                        easing  : 'cubic-bezier(0.42, 0, 0.58, 1)',
                        delay   : 525
                    });

                var icnConnectedContainer = view.querySelector('#icnConnectedContainer');
                icnConnectedContainer.animate({
                        opacity : [0, 1]
                    },
                    {
                        duration: 320,
                        fill    : 'forwards',
                        easing  : 'cubic-bezier(0.42, 0, 0.58, 1)',
                        delay   : 880
                    });

                // Place the image for the users MiCasaVerde Device in an image.
                var deviceImg           = view.querySelector('#deviceModel');
                deviceImg.src           = modelInfo.ImageUrl;
                deviceImg.style.opacity = 0;
                deviceImg.style.display = 'block';
                deviceImg.animate({
                    transform   : ['scale(0.89)', 'scale(1)'],
                    opacity     : [0, 1]
                },
                    {
                        duration: 220,
                        fill    : 'forwards',
                        easing  : 'cubic-bezier(0.42, 0, 0.58, 1)',
                        delay   : 120
                    });

                if (config.SavedDeviceProfiles) {
                    config.SavedDeviceProfiles.forEach(function (device) {
                        view.querySelector('#clientProfiles').innerHTML += (getClientHtml(device));
                    });
                }

            }, () => {

                html += '';
                html += '';
                html += 'error';
                html += '';
                html += '';
                html += ' No Vera Home Automation Device Detected!';

                activeMessage.innerHTML     = html;
                activeMessage.style.color   = 'red';
                activeMessage.style.opacity = 1;
                activeMessage.style.display = 'block';

                view.querySelector('#deviceModel').style.display = "none";
            });


Using angularJs to modify css.height causes Internet Explorer to not scroll to the bottom of the page

Question: When i try to dynamically set the height of a ngGrid component (using ngFlexibleHeightPlugin) I can't use the mousewheel to scroll to the bottom of the page in Internet Explorer 11 (and lower).
The issue only appears on heights larger than the screen size and only when using the mousewheel to scroll.
The critical line of code is:
self.grid.$viewport.css('height', newViewportHeight + 'px');

Answer: The mousewheel() function in the ng-grid.js is causing the issue for the Internet Explorer.
If you are comment the following block if (elm.focus) { elm.focus(); } from the ng-grid.js, it will solve the issue.
function mousewheel() {
    isMouseWheelActive = true;
    //if (elm.focus) { elm.focus(); }
    return true;
}

Help from: https://stackoverflow.com/a/25171252/2451726


Can two weak stationary time series $X_t, Y_t$ have covariance $\mathrm{Cov}(X_t,Y_t)$ that changes over time?

Question: Can two weak stationary time series $X_t, Y_t$  have covariance $Cov(X_t,Y_t)$ that changes over time? No solution is needed, please give me some hints. I think it can but I find it is difficult to support my idea.
Comment: If you cannot prove your idea, just sharing your idea is also good. I think Cov(Xt, Yt) may change over time. But I can not find the way to support my idea.
Comment: Is that a homework exercise? If so, please add the [tag:self-study] tag and read its [Wiki](https://stats.stackexchange.com/tags/self-study/info).
Comment: It a question that teacher left us, not a necessary homework. Thanks your comment !
Comment: Hint: let each series consist of *iid* variables.  Does this imply the variables in one series must be independent of those in the other?
Comment: Thanks your hint. Yes! It must be independent. But because of independence, the covariance must be 0 which will not change with t.
Answer: Let $(X_t),$ with "times" $t=0,1,2,\ldots,$ be variables with independent and identical distributions having finite variance $\sigma^2$ -- which implies they form a stationary (whence weakly stationary) stochastic process.  Suppose further that this common distribution is symmetric about $0$: this means the $-X_t$ all have the same distribution as the $X_t.$  For instance, the standard Normal distribution is symmetric about $0.$
Define
$$Y_t = (-1)^t X_t$$
and notice that
$$\operatorname{Cov}(X_t,Y_t) = \operatorname{Cov}(X_t,(-1)^tX_t) = (-1)^t \operatorname{Cov}(X_t,X_t) = (-1)^t\sigma^2$$
alternates between $\sigma^2$ and $-\sigma^2:$ that is, it changes over time.  Nevertheless, the symmetry of the distribution implies the $(Y_t)$ are identically distributed and, since the $(X_t)$ are independent, the $(Y_t)$ are independent too.  Thus $(Y_t)$ is a (weakly) stationary process, too.  In this example the covariance changes over time.
Comment: Thanks!!! This is really ingenious!


Programação em pares remotamente

Question: Eu e meu parceiro gostamos bastante de programar em pares de vez em quando, geralmente quando se tem alguma função complexa. Mas nós moramos em cidades diferentes e as vezes fica difícil se reunir para programar.
Atualmente estamos desenvolvendo uma aplicação Android com a IDE oficial (Android Studio) configurado com o controle de versões Github.
Ultimamente estamos usando a transmissão de tela pelo Skype para fazer a programação em pares. Está bacana, mas queríamos algo parecido com o que o Google docs faz, ou seja, edições simultâneas.
Há alguma ferramenta ou funcionalidade do Android Studio ou Git que faz isso?
Answer: Recentemente a Microsoft anunciou uma ferramenta de colaboração em tempo real: Visual Studio Live Share.
O que é interessante nela:

Pode ser usada no Visual Studio ou no Code
Usa o tooling da máquina que faz o compartilhamento da sessão, ou seja, você vai ver o conteúdo das variáveis da máquina chamadora!
Você vê e pode editar em tempo real o código para ajudar alguém!

Isso é pair programming de uma maneira nunca vista!
Até o momento desta resposta a ferramenta está em preview limitado. Você pode pedir para participar neste link: https://code.visualstudio.com/visual-studio-live-share, clica no botão "Sign up for early access"
Se você conhece alguém que tenha acesso, pode instalar a ferramenta nesse link https://github.com/MicrosoftDocs/live-share e pedir para essa pessoa te chamar para uma sessão.
Answer: Conheço dois:

Screenhero, que é uma solução de compartilhamento de tela, porém via peer-to-peer
inserir a descrição do link aqui, essa sim uma solução mais parecida com a citada, porém, ela funciona na nuvem.

Programação em pares remotamente


Forwarding Application Logs using nxlog

Question: I want to parse the Request URL field in message of application Event Logs by nxlog to kibana but i am not able to parse it as a seperate field.
Please suggest what to do in it.
Answer: There is an example in the manual: Example 6.9. Parsing URL request parameters in Apache access logs

Forwarding Application Logs using nxlog


Min and Max TypeError

Question: For some reason i can not understand,a TypeError occures when using min and max functions..
Here is the code:
import random
from typing import List, Any, Union
list1 = []

for i in range(0,200):
    x = random.randint(1,50)
    list1.append(x)

list2 = [ j for j in range(0,51)]

list1.append(list2)
print(list1)

del list1[99:130]

print(len(list1))

print(min(list1))

And this is the error:TypeError: '<' not supported between instances of 'list' and 'int'
Thank you :)
Comment: Please follow the code of conduct.  Restructure your code snippet, it is very difficult to understand it.
Comment: Try `list1.extend(list2)` instead of `list1.append(list2)` - search the docs for explanation (is simple)
Answer: it's because you have a nested list (list1)
see on the example
f = [12,3,4,5,[1,2,3]]
In [25]: min(f)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-d9448f4534d8> in <module>
----> 1 min(f)

TypeError: '<' not supported between instances of 'list' and 'int'

Comment: Thank you but i am a newbie..Explaining it would be helpful (Just a few words :P)
Comment: Thank you all very much ! I appreciate your time and effort :)
Answer: list1.append(list2) adds list2 (which is indeed a list) as an additional element to the end of list1. Your error arises because Python can't find the minimum of a list which consists of several numbers and one list.
I think you wanted to add all the individual numbers in list2 to list1, to end with a list of just numbers. This can be done using extend, rather than append.

Min and Max TypeError


Prove $\text{rank}(A) \geq \frac{(\text{tr}(A))^2}{\text{tr}(A^2)}$ when $A$ is Hermitian

Question: If $A \in \mathbb{C}^{n \times n}$ is a non-zero Hermitian matrix, I need to show that
$$\text{rank}(A) \geq \frac{(\text{tr}(A))^2}{\text{tr}(A^2)}$$ and reason out when the equality is attained?
Can anyone help me in showing this result?
Answer: Your matrix is diagonalizable to a diagonal matriz with real entries, when you diagonalize it, $\mathrm{rank}A$, $\mathrm{tr} A$ and $\mathrm{tr} A^2$ do not change. This means that you can suppose that $A$ is real and diagonal to begin with.
So suppose $A=\operatorname{diag}(\lambda_1,\dots,\lambda_n)$ with the $\lambda_i\in\mathbb R$. Then $\operatorname{rank}A$ is the number of non-zero $\lambda_i$s, $\operatorname{tr}A=\sum_i\lambda_i$ and  $\operatorname{tr}A^2=\sum_i\lambda_i^2$. It follows that we are reduced to showing that

if $\lambda_1$, $\dots$, $\lambda_n$ are real numbers, then $\big(\sum_{i=1}^n\lambda_i\big)^2\leq n\sum_{i=1}^n\lambda_i^2$.

One way to do prove this is to fix $r\geq0$, compute the maximum $M$ of the function $f(\lambda_1,\dots,\lambda_n)=(\lambda_1+\cdots+\lambda_n)^2$ in the sphere $\lambda_1^2+\cdots+\lambda_n^2=r$, and finally check that $M$ is equal to $nr$.
This can be done easily using the method of Lagrange multipliers---it will, moreover, tell you where the maximum is achieved, and show when your inequality becomes an equality.
Comment: Seems to me like a typical case of cracking nuts with a sledgehammer since, for example, no differential structure is involved, but as they say, *gustibus non est disputandum*...
Comment: Rank of a matrix is linked to number of independent rows/ columns in the matrix, whereas trace is linked with sum of eigen values of the matrix. How do we link them? Also number of non-zero eigen value not necessary equals rank of a matrix!
Comment: @Learner But number of zero eigs equal to the rank drop no?
Comment: Mariano: (1) The blockquoted inequality is a case of Cauchy-Schwarz inequality. (2) Both the inequality itself and the equality case are direct once you note that RHS$-$LHS is $\sum_{i,j}(x_i-x_j)^2$.
Comment: @Didier: my favourite proof of C-S uses Lagrange multipliers, so there is no loss :)
Comment: Heh. Well, I can prove pretty much *all* classical inequalities (C-S, the arithmetic-geometric inequality, Young's, Minkowski's, and many many others) using the *exact* same idea. I very much prefer to have at hand a general method to avoid thinking!
Comment: IOW: there are lots and lots of nuts!


Understanding Time2Vec embedding for implementing this as a keras layer

Question: The paper time2vector link (the relevant theory is in section 4) shows an approach to include a time embedding for features to improve model performance. I would like to give this a try. I found a implementation as keras layer which I changed a little bit. Basically it creates two matrices for one feature:
(1) linear = w * x + b
(2) periodic = sin(w * x + b)
Currently I choose this feature manually. Concerning the paper there are a few things i don't understand. The first thing is the term k as the number of sinusoids. The authors use up to 64 sinusoids. What does this mean? I have just 1 sinusoid at the moment, right? Secondly I'm about to put every feature I have through the sinus transformation for me dataset that would make 6 (sinusoids) periodic features. The authors use only one linear term. How should I choose the feature for the linear term? Unfortunately the code from the paper is not available anymore. Has anyone worked with time embeddings or even with this particularly approach?
Comment: They're transforming a single value of 'the moment in time that something happened' into multiple features. As humans we already do this, 'now' can be split into time of the day, day of the week, day of the month, day of the year, year, etc.. It looks like they do this in a clever automated way that uses 64 different cycle lengths (1/day, 1/week, 1/month etc. are probably in there)
Comment: It looks like what they're doing with sines is similar to a [fourier series](https://en.wikipedia.org/wiki/Fourier_series#Definition), 3Blue1Brown has a good [video explanation](https://www.youtube.com/watch?v=r6sGWTCMz2k). From a glance at the paper (so I might be mistaken) it also looks like they run _only_ the time through the transformation so they get a bunch of extra features to encode for the time.
Comment: Yes, it seems mostly like a Fourier series, I already watched this video but it wasn't quite helpful in understanding what to do here. So, if they just use the time which would make totally sense how do they gain 64 sinusoids from this single feature? Are they transforming the same feature multiple times? Thanks for your reply
Answer: For my limited understanding, the linear transformation of time is a fixed element of the produced embedding and the parameter K allows you to select how many different learned time representations you want to use in your model. So, the resulting embedding has a size of K+1 elements.


If $0\rightarrow A\rightarrow B\rightarrow C\rightarrow 0$ is exact and $B\simeq A\oplus C$ as a $R$-module, does this sequence split?

Question: Suppose $0\rightarrow A\rightarrow B\rightarrow C\rightarrow 0$ is a short exact sequence that $B\simeq A\oplus C$ as a $R$-module. Does this short exact sequence split?
I think the answer is no, but I must have a counterexample. I could not find any. Can you help me?
Comment: I tried to make a short exact sequence that doesnt split but $B\simeq A\oplus C$ !I used $\mathbb{Q}$ and $\mathbb{Z}$ because the only homomorphism between them is zero but I couldnt make the hypothesis .
Comment: Please explain what you thought about, and generally try to follow this guide: http://meta.math.stackexchange.com/a/1804/26369
Answer: Although this isn't quite a duplicate, the case $R=\mathbb{Z}$ is thoroughly discussed in A nonsplit short exact sequence of abelian groups with $B \cong A \oplus C$.


LilyPond - Can I change the scoreTitleMarkup style/content depending on the page number?

Question: Question:
Is there a way to change how the score title appears based on whether it's on an odd or even page?
Given:
% --- paper.ily
\paper {
  scoreTitleMarkup = \markup \column {
    \fill-line {
      \box \fromproperty #'header:order
      \bold \fromproperty #'header:title
      \null
    }
    \fill-line {
      \null
      \italic \fromproperty #'header:author
    }
  }
}

% --- score.ily
\score {
  <<
    \new Staff \music
  >>
  \header {
    title = \title
    order = \order
    author = \author
  }
}

% --- compile.ly
title = "Good Afternoon"
order = "1"
author = "Santa"
music = {
  % ...
}
\include "./score.ily"

title = "Good Evening"
order = "2"
author = "Elves"
music = {
  % ...
}
\include "./score.ily"

title = "Good Night"
order = "3"
author = "Truman"
music = {
  % ...
}
\include "./score.ily"

Result:

Contrived Example:
(Notice the order and author are on reversed sides on the right-hand page.)
Answer: It is possible by adapting the implementation of \page-ref.
This is a bit awkward to use since you have to put a uniquely named \label before each markup block that uses \odd-even-markup, and the page number of the label, not the markup, is used for the decision. There may be a way to get the page number without a label, but I didn't find one.
Since the size of the markup is calculated before the page number is known, the odd and even markup have to be the same size (or they're padded to the same size). That probably won't be a problem in this particular use case.

\version "2.24.3"

#(define-markup-command (delayed-markup layout props factory) (procedure?)

   "Use the dimensions of the markup returned by (factory #t) for layout,
    and the markup returned by (factory #f), called later, for rendering."

   (let* ((gauge-stencil (interpret-markup layout props (factory #t)))
          (x-ext (ly:stencil-extent gauge-stencil X))
          (y-ext (ly:stencil-extent gauge-stencil Y)))
     (ly:stencil-outline
      (ly:make-stencil
       `(delay-stencil-evaluation
         ,(delay (ly:stencil-expr
                   (interpret-markup layout props
                     (make-with-dimensions-markup x-ext y-ext (factory #f))))))
       x-ext y-ext)
      (make-filled-box-stencil x-ext y-ext))))

#(define (layout-lookup-label layout label)

   "The weird label-lookup logic from page-ref."

   (define (assoc-name-get name ls)
     (do ((ls ls (cdr ls)) (result '() result))
         ((null? ls) result)
       (if (and (car ls) (eq? name (assoc-get 'name (cdar ls))))
           (set! result (cons (car ls) result)))))

   (let* ((table (ly:output-def-lookup layout 'label-page-table))
          (alist-table (ly:output-def-lookup layout 'label-alist-table))
          (retrieve-id (and (list? alist-table)
                            (let ((entry (assoc-name-get label alist-table)))
                              (and (pair? entry) (caar entry))))))
     (and (list? table)
          (assoc-get (or retrieve-id label) table))))

#(define-markup-command (page-ref-generic layout props label factory) (symbol? procedure?)

   "Use the dimensions of the markup returned by (factory #t) for layout, and
    the markup returned by (factory pagenum) for rendering, where pagenum is
    the page number of the given label or #f if the label wasn't found."

   (interpret-markup layout props
     (make-delayed-markup-markup
       (lambda (dry-run)
         (factory (or dry-run (layout-lookup-label layout label)))))))

%#(define-markup-command (page-ref layout props label gauge default) (symbol? markup? markup?)
%
%   "A reimplementation of page-ref in terms of page-ref-generic."
%
%   (interpret-markup layout props
%     (make-page-ref-generic-markup label
%       (lambda (page-number)
%         (if (boolean? page-number)
%             (if page-number gauge default)
%             (number-format (ly:output-def-lookup layout 'page-number-type) page-number))))))

#(define-markup-command (odd-even-markup layout props label ifodd ifeven) (symbol? markup? markup?)

   "Select ifodd or ifeven markup depending on the page number of the label.
    If label lookup fails, display ifodd and ifeven superimposed."

   (interpret-markup layout props
     (make-page-ref-generic-markup
       label
       (lambda (page)
         (if (boolean? page)
             (make-combine-markup ifodd ifeven)
             (if (odd? page) ifodd ifeven))))))

\label #'a  \markup \odd-even-markup #'a "odd" "even"  \pageBreak
\label #'b  \markup \odd-even-markup #'b "odd" "even"  \pageBreak
\label #'c  \markup \odd-even-markup #'c "odd" "even"  \pageBreak

To use common title markup for all scores, you could do something like this. (Edit: see Lazy's answer for a way to avoid the \remember-page-number and score-label = #last-remembered-page-label boilerplate.)
last-remembered-page-label = ##f

remember-page-number =
  #(define-music-function () ()
     (set! last-remembered-page-label (gensym))
     #{ \label #last-remembered-page-label #} )

#(define-markup-command (title-odd-even-markup layout props ifodd ifeven) (markup? markup?)

   "like \\odd-even-markup, but gets the label from the 'score-label' header property."

   (interpret-markup layout props
     (make-odd-even-markup-markup (chain-assoc-get 'header:score-label props) ifodd ifeven)))

\paper {
  scoreTitleMarkup = \markup \title-odd-even-markup "odd" "even"
}

\remember-page-number

\score {
  \header { score-label = #last-remembered-page-label }
  { c'1 }
}

\pageBreak

\remember-page-number

\score {
  \header { score-label = #last-remembered-page-label }
  { d'1 }
}

Comment: It is a clever hack, but you need to understand that this is not exactly the behavior we'd expect. The thing is that this is not "markup depending on page number", but "a stencil depending on page number", which is probably fine for something like page number (not much going on), but if you use e.g. something like `"a" \column { "b" "b" "b" }` for this you'll see why this is still an (albeit quite clever) hack. For the means of the OP probably a usable solution.
Comment: I've posted a way to get rid of the boilerplate in a separate answer (cannot put this as comment).
Comment: @Lazy I added a link to your answer and a mention of the sizing problem.
Answer: The problem here is the order things are done. At the time this markup is created Lilypond does not know on what page it is. Rather it places all of these things on a single page and then breaks this page depending on the content.
So with the current state of affairs this is not possible. Some of the developers dream of turning these markups into grobs, which would potentially allow for a later callback changing that stuff.
Note that the header markups are not affected by this, as they need to be spaced out, but else the content cannot depend on the page, as the page would depend on the content.
But how do things like TeX do this (e.g. for references, tocs, ...)? These employ a two step approach, writing the page numbers into a separate file which then provides the number on the next run. This could be implemented around Lilypond.
For example use code like this
#(use-modules (ice-9 textual-ports))
pageref =
#(define-scheme-function (ref) (string?)
   (let ((refs (format #f "~a.pagerefs" input-file-name))
         (filler (markup #:box #:bold (format #f "%.~a.%" ref))))
     (if (file-exists? refs)
         (let* ((content (call-with-input-file refs get-string-all))
                (content (string-split content #\newline))
                (content (map (lambda (x) (string-split x #\:)) content))
                (content (filter (lambda (x) (not (or (null? x) (equal? (car x) "")))) content))
                (content (map (lambda (x) (cons (car x) (cadr x))) content))
                (page-nr (assoc-get ref content filler)))
           page-nr)
         filler)))

\markup\pageref "A"
\pageBreak
\markup\pageref "B"

and create a wrapper in whatever language you like that

Runs Lilypond with svg option into a tempdir
Searches the pages for %\.(\w+)\.%
Enters the found pairs into a file [inputfile].pagerefs in the format label:page
Reruns Lilypond with the intended format

For the above case that file would contain
A:1
B:2

Comment: I'm accepting the answer not necessarily because I comprehend it all, but because the pretty clear answer is, "No, you can't. At least not yet." As far as your example is concerned, do you have handy either more documentation on that, other examples, or discussions in the mailing list? It's fine if you don't; I at least have a direction to search.
Comment: [`\page-ref`](https://lilypond.org/doc/v2.24/Documentation/notation/reference-to-page-numbers) manages to do something very similar, so I think it's possible.
Comment: Please critique my answer.
Comment: @Neal While this answer still stands, checkout benrg's idea, which could just work out for you. Do not forget to mark his reply as accepted if it works out for you.
Answer: Adding to @benrq's interesting approach:
You do not need to manually label everything and set score-labels. Instead you can change the score-handler to something that does these things for you:
#(define (collect-scores-for-book-with-label score)
  (let* ((label (gensym))
         (header (ly:score-header score))
         (header (if (null? header) #{\header {}#} header)))
    (module-define! header 'score-label label)
    (ly:score-set-header! score header)
    (collect-music-for-book #{ \label #label #})
    (collect-scores-for-book score)))

#(set! toplevel-score-handler collect-scores-for-book-with-label)

\paper {
  scoreTitleMarkup = \markup \title-odd-even-markup "a" "b"
  ragged-bottom = ##t
}

\score {
  { c'1 }
}

\pageBreak

\score {
  { d'1 }
}

Probably one would also like to adapt the other toplevel handlers, but you get the idea.


Return setState in reduce

Question: I have a state that returns an array of objects :
const [coins, setCoins] = useState([])
const [newCoins, setNewCoins] = useState([])

console.log(coins)

[
  {
    "note": "",
    "quantity ": 2,
    "name": "Bitcoin",
    "price": 37000.98,
  },
  {
    "note": "",
    "name": "Bitcoin",
    "quantity": 1,
    "price": 37000.98,
  },
  {
    "note": "",
    "name": "Ethereum",
    "price": 2690.32,
    "quantity": 1,
  }
]

I would like, starting from this list of objects, to create a new table in order to display a concise summary of the previous table. So you have to merge the objects with the same "name", cumul the "quantity", and finally add a new "key" which will be used to add the current price (retrieved via an API).
Using reduce works fine and returns me a new array
const coinsArrCopy = coins.map(item => ({...item}))
  const coinsCopy = coinsArrCopy.reduce((acc, obj) => {
    let existItem = acc.find(item => item.name === obj.name);
    if (existItem) {
      existItem.quantity += obj.quantity
      delete existItem.price
      delete existItem.note
      return acc;
    }
    acc.push({...obj, currentPrice: 0})
    // return setNewCoins(acc) <== ERROR
    return acc;
 }, [])

The new table looks like this:
console.log(coinsCopy)

[
  {
    "quantity": 3,
    "name": "Bitcoin",
    "currentPrice": 0
  },
  {
    "name": "Ethereum",
    "quantity": 1,
    "currentPrice": 0
  }
]

How to transfer this coinsCopy array to newCoins state? return setNewCoins(acc) gives me an error setNewCoins is not a function?
Comment: Where are you performing this transformation? And declare separate state for the transformed array: `const [newCoins, setNewCoins] = useState([])`
Comment: This state is declared in the same place as my other states. I edited my comment to add it
Answer: You can call your setNewCoins function to update the state right after you've created the coinsCopy variable, as long as you're performing such calculation on the same component or on a child component (in this case you'll have to pass the setNewCoins function through props). You'll end up with something like:
const coinsArrCopy = coins.map(item => ({...item}))
const coinsCopy = coinsArrCopy.reduce((acc, obj) => {
    let existItem = acc.find(item => item.name === obj.name);
    if (existItem) {
      existItem.quantity += obj.quantity
      delete existItem.price
      delete existItem.note
      return acc;
    }
    acc.push({...obj, currentPrice: 0})
    return acc;
 }, [])

//This will update the state with the current value of the coinsCopy array.
setNewCoins(coinsCopy)

Comment: Of course I tried. This doesn't work and returns the error: TypeError: setNewCoins is not a function
Comment: Please, provide more context. Share more code if possible, that would let us know if you're calling the function on the same component, on a child component or something along those lines.
Answer: The solution was actually quite simple.
You have to add the change of state in a useEffect, and listen to the "coins" state to restart the effect again when it detects a change.
useEffect(() => {
  setNewCoins(coinsCopy)
}, [coins])

Return setState in reduce


How to get unlabeled data by BeautifulSoup Python

Question:

  Contents

   Google what time is it

  It's 4:38.

  2018. 2. 5. 5:38:41 PM

]

In the code above, I want to extract the answer ("It's 4:38") and the timestamp. For the question, I used

for link in soup.find_all('a'): Questions.append(link.text);

but I couldn't do the same with the answers and timestamp. How do I resolve this issue?
Answer: You can see that the text you want is a descendant of the div element. You can also see that it immediately follows the first br element that is such a descendant. Then one way to find it is simply to iterate through the descendants of the div looking for that br. When you see that take the next item.
Here's how it will play out.
>>> import bs4
>>> soup = bs4.BeautifulSoup(open('sumin.htm').read(), 'lxml')
>>> div = soup.find('div')
>>> for element in div.descendants:
...     element.name, element
...
(None, '\n  Contents\n  ')
('a',
   Google what time is it
  )
(None, '\n   Google what time is it\n  ')
(None, '\n')
('br',
)
(None, "\n  It's 4:38.\n  ")
('br',
)
(None, '\n  2018. 2. 5. 5:38:41 PM\n ')

Notice that elements such as br have the name property but navigable strings do not (this property is None).
Answer:
How to get unlabeled data

Actually, it is not unlabeled. The text you want is located inside the
 tag. To get that text you can check if the text is NavigableString.
If you check the type of each content,
Contents  #<class 'bs4.element.NavigableString'>

   Google what time is it
           #<class 'bs4.element.Tag'>

#<class 'bs4.element.NavigableString'>

   #<class 'bs4.element.Tag'>

  It's 4:38.    #<class 'bs4.element.NavigableString'>

  #<class 'bs4.element.Tag'>

  2018. 2. 5. 5:38:41 PM      #<class 'bs4.element.NavigableString'>

Code:
>>> from bs4 import BeautifulSoup, NavigableString
>>> html = '''

...   Contents
...
...    Google what time is it
...
...

...   It's 4:38.
...

...   2018. 2. 5. 5:38:41 PM
...
'''
>>> soup = BeautifulSoup(html, 'lxml')
>>> div = soup.find('div', class_='content-cell mdl-cell mdl-cell--6-col mdl-typography--body-1')
>>> contents = [x.strip() for x in div.contents if isinstance(x, NavigableString)]
>>> contents
['Contents', '', "It's 4:38.", '2018. 2. 5. 5:38:41 PM']

From this, you can understand what NavigableString is. Now, to get the date and time you can simply join the last 2 elements of the list.
>>> ' '.join(contents[-2:])
"It's 4:38. 2018. 2. 5. 5:38:41 PM"

Answer: text = '
\n  Contents\n  \n   Google what time is it\n  \n
\n  It\'s 4:38.\n
\n  2018. 2. 5. 5:38:41 PM\n
'

s = BeautifulSoup(text,"lxml")

>>> s.find("br").findNext("br").next
'\n  2018. 2. 5. 5:38:41 PM\n '
>>> s.find("br").next
"\n  It's 4:38.\n  "

Answer: Use select_one() in combo with SelectorGadget Chrome extension to grab CSS selectors by clicking on the desired element in your browser:
soup.select_one('.YwPhnf').text
# 09:06

Or you can use stripped_strings, but it's not as pretty as using CSS selectors:
html = '''

Contents

  Google what time is it

It's 4:38.

2018. 2. 5. 5:38:41 PM

'''
soup = BeautifulSoup(html, 'lxml')

# returns a generator object
current_time = list(soup.select_one('.content-cell').stripped_strings)[2]
print(current_time)

# It's 4:38.

Code:
from bs4 import BeautifulSoup
import requests, lxml

headers = {
    'User-agent':
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}

params = {
  "q": "what time it is",  # query
  "gl": "us",              # country to search from
  "hl": "en"               # language
}

html = requests.get("https://www.google.com/search", headers=headers, params=params)
soup = BeautifulSoup(html.text, 'lxml')

current_time = soup.select_one('.YwPhnf').text
current_date = soup.select_one('.KfQeJ:nth-child(1)').text
print(f'{current_time}\n{current_date}')

# 2:11 AM
# September 11, 2021

Alternatively, you can achieve the same thing by using Google Direct Answer Box API from SerpApi. It's a paid API with a free plan.
The difference in your case is that you only need to get the data you want from the structured JSON, rather than figuring out to extract things and maintain the parser over time if something won't work correctly because of some changes in the HTML.
Code to integrate:
from serpapi import GoogleSearch

params = {
  "api_key": "YOUR_API_KEY",
  "engine": "google",
  "q": "what time it is",
  "gl": "us",
  "hl": "en"
}

search = GoogleSearch(params)
results = search.get_dict()

print(results['answer_box']['result'])

# 2:07 AM

Disclaimer, I work for SerpApi.


Context menu icon not appearing in Google Chrome

Question: I am making a test extension but the item is not appearing in context menu. What is wrong here?
My manifest file
{
 "name": "Colour",
 "version": "1.0.1",
 "description": "Colour the background on right clicking image.",
 "offline_enabled": true,
 "permissions" : [
 "contextMenus",
   "tabs",
   "http://*/*",
   "https://*/*"
 ],
 "background_page":"background.html"
}

My background.html contains this script
function getColour(info, tab){
  document.body.style.background="#456";
}

chrome.contextMenus.create({
  "type":"normal",
  "title":"Colour page",
  "contexts":["image"],
  "onclick":getColour()
});

Answer: A reference to the getColour function has to be passed. It should not be invoked:
function getColour(info, tab){
    document.body.style.background="#456";
}

chrome.contextMenus.create({
    "type": "normal",
    "title": "Colour page",
    "contexts": ["image"],
    "onclick": getColour // <--- Removed ()
});

Previously, your code would work in this way:

getColour() -  Calls getColour.
There is no return statement in the function, so it returns undefined.
chrome.contextMenu.create({ ... "onclick": undefined }); - No event handler!
Comment: @Shikhar Sharma  If you have still have problems understanding the difference between invoking/calling/executing a function and referencing one (like for a callback) then just say so and Ill try and write an answer explaining it.  I myself had quite a bit of a problem getting it in the beginning (if your out there somewhere Waha, thank you ;))
Comment: @PAEz It's not difficult: When a function name is postfixed by two parentheses, eg `name()`, the function is **invoked**. When these are left out, a **reference to the function is passed,** eg `name`
Comment: I get that now, but it took me making the mistake 3 times and having Waha explain it to me before I really got it.... especially when it came to the idea of callbacks.
Comment: @RobW - Thanks. I removed the () and i now understand the difference between invoking and referencing. The item now appears in the context menu. But on clicking on it nothing happens - background color of the tab containing the image i right-clicked still remains the same.
Comment: @ShikharSharma `document` refers to the background page. You have to populate the body of `getColour` with [`chrome.tabs.executeScript(null, {code:'document.body.style.background="#456";'});`](http://code.google.com/chrome/extensions/tabs.html#method-executeScript)


What is the best practice for writing a link to the screen through t()?

Question: In Drupal 7, one could do the following one line::
t('Visit !mylink', ['!mylink' => l('my website', 'http://example.com')]);

But that no longer works in Drupal 8 or 9 .  So far, I've tried this:
First I create a link, Drupal 8 style:
$mylink = Link::fromTextAndUrl('my website', Url::fromUri('http://example.com'));

Then try to create a string that can be printed.  I've tried toString():
t('Visit @mylink', ['@mylink' => $mylink->toString()]);

However, we're not supposed to do this. The API docs says:

Do not use this method to render a link in an HTML context. In an HTML context, self::toRenderable() should be used so that render cache information is maintained.

So I try to use toRenderable():
t('Visit @mylink', ['@mylink' => render($mylink->toRenderable()]);

But PHP 7.2 doesn't like it.  The call to t() produces the following Notice:

Notice: Only variables should be passed by reference ...

Fair enough - but how is this done?
I could not find how to do this described in any of the obvious docs, such as:

https://www.drupal.org/docs/security-in-drupal/sanitizing-output
https://www.drupal.org/docs/security-in-drupal/writing-secure-code-for-drupal

So my question is:
What is the best practice for writing a link to the screen in Drupal 8?
(Environment: Ubuntu 20.04 LTS, Drupal 8.8.6 (core + devel), procedural code - e.g. hook_help()).
Answer: For a link enclosed in translatable text, Drupal core suggests to use t() and embed the HTML anchor tag directly in the translated string. In LinkGeneratorInterface::generate(), the example code for this case is the following.
$text = t('Visit the content types page', array(
  ':url' => Url::fromRoute('entity.node_type.collection')->toString(),
));

Searching for :url in the Drupal core code finds code like the following.
BlockContentController::add()
if (count($types) === 0) {
  return [
    '#markup' => $this
      ->t('You have not created any block types yet. Go to the block type creation page to add a new block type.', [
      ':url' => Url::fromRoute('block_content.type_add')->toString(),
    ]),
  ];
}

ListingEmpty::render()
  $element = [
    '#markup' => $this->t('Add a custom block.', [
      ':url' => Url::fromRoute('block_content.add_page')->toString(),
    ]),
    '#access' => $access_result->isAllowed(),
    '#cache' => [
      'contexts' => $access_result->getCacheContexts(),
      'tags' => $access_result->getCacheTags(),
      'max-age' => $access_result->getCacheMaxAge(),
    ],
  ];

Alternatively, Drupal core uses the following code.
block_help()
$themes = \Drupal::service('theme_handler')->listInfo();
$output = '
' . t('Block placement is specific to each theme on your site. Changes will not be saved until you click Save blocks at the bottom of the page.') . '
';
$output .= '
' . Link::fromTextAndUrl(t('Demonstrate block regions (@theme)', [
  '@theme' => $themes[$demo_theme]->info['name'],
]), Url::fromRoute('block.admin_demo', ['theme' => $demo_theme]))->toString() . '
';

template_preprocess_forums()
    if ($variables['tid'] != $topic->forum_tid) {
      $variables['topics'][$id]->moved = TRUE;
      $variables['topics'][$id]->title = $topic->getTitle();
      $variables['topics'][$id]->message = Link::fromTextAndUrl(t('This topic has been moved'), Url::fromRoute('forum.page', ['taxonomy_term' => $topic->forum_tid]))->toString();
    }

Comment: As a note, the quote from the API about cache data still applies. If you have a URL that is dynamically generated and that has additional cache requirements to the rest of the page, you should be injecting them into the render array because they will be lost otherwise. Most of the time this won't apply, though.
Comment: Very enlightening.  A big thanks to both MrD and you!
Answer: It will easy if you convert link to url and use translate like this.
$url = Url::fromUri('http://example.com')->toString();
t('Visit link', array(':href' => $url));

Example drupal core use translation with link.
$requirements['online'] = array(
      'title' => t('Internet'),
      'value' => t('The translation server is offline.'),
      'severity' => REQUIREMENT_ERROR,
      'description' => t('The installer requires to contact the translation server to download a translation file. Check your internet connection and verify that your website can reach the translation server at @server_url.', array(
        ':server_url' => $server_url,
        '@server_url' => $server_url,
      )),
    );


Can't visit site after switching on Language Detection 'Session' in combination with Ip to locale

Question: My site is in a kind of a loop? I can't login anymore and visit the site? http://landberg.at/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/en/user
What do i have to do. Its a combination with IP to local and Language Detection 'Session'

How do i disable Language Detection 'Session' from mySql database manually?
i already disabled IP to local module from database...

I really need my site back as soon as possible.
Thanks!
Update:
I solved it by entering ?language=en behind my URL. After this i was able to login again.
Comment: Do you use drush? Have you tried disabling the module via drush?
Comment: no i disabled it directly in mySQL with `UPDATE system SET status='0' WHERE name='module_name';`
Comment: It is possible that the module is still cached. Have you tried
`DELETE FROM cache_bootstrap WHERE cid='system_list';` ?
Comment: yes i did that too! But still i can't visit the site. I want manually disable Language Detection 'Session' in database but i don't know where it is?
Comment: once you are able, be sure to include your solution as an answer and 'accept' it so this question does not remain unanswered
Answer: I solved it by entering ?language=en behind my URL. After this i was able to login and visit my site again.


If two members of a RAID 1 volume have inconsistent bits, how do most RAID controller handle this?

Question: I am using VROC for CPU RAID with some NVMe drives. I have a RAID 1 array that seems to be having problems. Instead of boring you with the details, I have a more general question.
How does VROC (or RAID 1 controller in general) handle a situation in which the drives have inconsistent bits? There is no way it can know which is correct, because there is no parity bit.
How do most RAID controller handle this?
Answer: RAID controllers never read from both mirrored drives to compare the data. So the answers is - you'll get inconsistent read you must detect and handle at the file system level. Modern file systems like ZFS, BtrFS and even dead-born ReFS have options to hash both meta and actual data.
Answer: Classical RAID1 implementations do not check both mirrors for comparison purpose,  neither during normal activity nor scrub. For example, Linux MDRAID almost always read from the first mirror leg, while some hardware controllers use a round-robin approach.
This means that a classical RAID1 can return inconsistent data even if a good version exists on one of the mirror leg. After all, not using data checksum, how can a RAID1 array distinguish the bad copy from the good one?
BTRFS and ZFS mirrors are an entirely different matter: by using data checksum, they can immediately identify (and correct) the bad/corrupted data.


Como notificar usuário Web Api com SignalR?

Question: Ao receber um post em uma aplicação Web Api preciso notificar um determinado cliente que foi inserido um novo registro. Esse usuário vai ver essa notificação em uma aplicação cliente(javascript) separada do projeto Web Api e vai estar logado utilizando Identity.
Como enviar uma notificação com SignalR para esse determinado cliente(com base no login Identity)?
Comment: Você já montou um Hub pra comunicar o usuário?
Comment: Man, conheçe o Pusher? é um serviço que, digamos assim, terceriza isso pra ti, eu tenho um post sobre ele. O legal é que vc faz a conta no serviço do pusher, cria um canal e um evento, baixa a api deles, e de um lado dispara o evento e do outro, a pagina, registra via javascript o evento, bem bacana.
http://wp.me/p2AWkc-7y
Answer: Acho que esta procurando algo como "AJAX Reverso", não encontrei uma definição em português mas vai aqui um link para entender melhor como ele funciona prokata.com/reverseajax.html.
Na época utilizei o DWR mas é uma implementação para java, no caso do ASP.NET vi que existe o Pokein mas parece que não é gratuito, tem um opção de "Free community edition" mas não encontrei para donwload.
Mas acredito que exista alguma implementação gratuita por ai, acho que não somos os únicos que já precisou utilizar este recurso antes.
Espero ter ajudado.
Comment: O DWR e bom mas precisa ter aceso no servidor para instalar. Então precisa saber se Carlos pode fazer isso?
Answer: Carlos, considerando que seu Hub esteja implementado no mesmo projeto que o WebApi:
Quando o um usuário (via javascript) conectar no seu Hub, você grava o ConnectionId e UserId do Identity dele em um banco de dados (por exemplo).
Quando acontecer o POST, você pode pegar uma instância do seu Hub e enviar a mensagem para o cliente que quiser.
Para obter uma instância do Hub, faça:
var meuHub =  GlobalHost.ConnectionManager.GetHubContext<TIPO_DO_MEU_HUB>();

e para enviar uma mensagem, você faz como se estivesse dentro do Hub, exemplo:
meuHub.Clients.Client(ConnectionId_DO_CLIENTE).enviaMensagemParaOCliente("woot");

Na hora do POST você verifica qual ConnectionId do cliente destinatário via o UserId dele e manda a mensagem, lembrando que um mesmo UserId pode ter mais de um ConnectionId (multiplos navegadores/dispositivos) -então você provavelmente vai querer notificar todos.
Answer: Um servidor nao pode chamar um cliente porque Internet e baseado sobre um sistema de pequenos mesangem: ligaçao, transmiçao, corta ligaçao etc... Entao e o cliente que vai dever chamar o servidor.
O que vc pode fazer e colocar um pedaço de JS no site, com um timer.
Por exemplo cada minutos, a pagina vai chamar o servidor para saber se tem um novo mesagem (veja setTimeout() )
2 opçoes:
1) a pagina chama o servido entao tem um "refresh" da pagina. Muito facil mais no bem "estetico" porque com o sem mensagem no servidor vai ter um "refresh"
2) usar XMLHttpRequest() o que permite um codigo JS de chamar uma outra pagina e receber as informaçoes, sem fazer um "refresh".
Comment: Peter, você está certo ao dizer que apenas um cliente pode iniciar uma conexão mas isso não tem nada a ver com a pergunta. É perfeitamente possível e comum enviar dados em tempo real a partir do servidor para o cliente, sem uma requisição específica (veja socket.io ou signalr, por exemplo)
Comment: E verdade Leo, mas SOMENTE depois da chamada do cliente. Porque para conversar com um cliente o servidor deve ter o IP de cliente. Um servidor tem um IP "fixa" mas não o cliente. Pior, NADA pode demonstrar que se o servidor envia dados durante 10 minutos, o cliente vai continuar a ter o mesmo IP durante os 10 minutos. Hoje, por exemplo, meu rede internet caiu três vezes, cada vez por 2 ou 3 minutos. E a cada vez, o endereço IP atribuído foi diferente.
Comment: Peter, como eu falei: isso não tem nada a ver com a pergunta feita. Problemas de desconexão devem se tratados pelo programador, se ele quer enviar notificaçoes do servidor para o cliente e são bem fáceis de tratar, seja usando uma abstração como o SignalR ou websockets puro. A suas sugestões para a necessidade dele são _extremamente_ ineficientes e ficaria muito preocupado em ver um site profissional as utilizando hoje em dia.
Comment: Isso tem MUITO a ver com a pergunta. Porque se Carlos e sozinho no seu escritório, e que durante todo a seu tempo de programação, ele tem a mesma IP, ele vai ser feliz porque vai funcionar. Mas quando ele vai conectar um segundo computador o que a sua ligação internet vai cair, mesmo 5 segundos e que ele vai receber um novo IP, ele não vai entender porque não funciona mas.
Comment: Peter, dá uma lida de novo na pergunta, ele não está perguntando nada sobre como funciona o protocolo HTTP, provavelmente ele já sabe (já que programa web), bem como o fato comum de ocasional mudança de IP. Ele está só perguntando como enviar uma notificação ao cliente, a partir do servidor, prática simples e bem conhecida atualmente. Sua resposta é ruim para quem cair aqui porque dá a entender que o que ele quer fazer só é possível via poolling ou refresh, o que não só não é verdade como - repito - extremamente ineficiente e deve ser desencorajado.
Answer: Parece que vc vai ter um cliente (A) que vai se conectar por exemplo a 14H00. Um outro cliente (B) vai enviar um mensagem no servidor por exemplo a 15H00. O que vc quer fazer e enviar uma informação no cliente A, para informar que tem um novo mensagem.
E impossível ter certeza que isso vai funcionar. Por que?
1) entre a connection do cliente A a 14H00 e o momento o vc vai enviar um mensagem 15H00, o cliente A pode mudar de IP
2) Se o cliente tem 2 computadores, um roteador e um modem, quando o servidor vai salvar o IP, ele não vai salvar o IP do cliente, mas o IP do roteador. Vc pode fazer o test seguinte: coloca no seu site uma pagina que mostra o IP, conecta-se com um computador de seu rede e depois com um outro do mesmo rede e vc vai ver que do ponto de vista do servidor os dois tem o mesmo IP.
Quando criamos um CHAT por exemplo, tem o mesmo problema: mostrar para o  cliente A, os mensagens do cliente B, C etc...
O SignalR pode ser usado, mas não como vc acha. Vc diz "Como enviar uma notificação com SignalR para esse determinado cliente(com base no login Identity)?" o que significa que vc acha que e o servidor que vai chamar o cliente A.
Não e possível (infelizmente)
De verdade com o SignalR, vc vai determinar o tempo da chamada. E o cliente A que vai dever (por exemplo cada 5 segundos) chamar o servidor. Então, o servidor vai saber quem "chama" e vai dar a resposta certa.
Vc pode dar uma olhada aqui:
http://www.asp.net/signalr/overview/getting-started/tutorial-high-frequency-realtime-with-signalr
Vc pode tambem dar uma olhada aqui:
https://github.com/JabbR/JabbR
Na pasta Scripts tem jquery.signalR-2.2.0-pre-140709-b104.js (linhas 694 e seguinte para entender o principio).
Comment: Peter você está errado. No momento em que há a mudança de IP você perde a conexão com o servidor. Se você está usando o SignalR, ele tenta a reconexão e basta você tratar esta reconexão no seu Hub. Não precisa se preocupar com IP, é tudo abstraído pra você - você só precisa gerenciar o ConnectionId que é o "endereço" do cliente p/ quem você quer enviar uma mensagem. O "teste" que você sugere é irrelevante, a internet funciona perfeitamente, mesmo com NAT. O que Carlos está perguntando é perfeitamente possível. E também está errado em dizer que é preciso fazer pooling no signalR.


Where to update database in Android in-app billing?

Question: I downloaded android in-app billing sample "Dungeons" application and i tested it.But i don't want to use its database.I want to update my own database but i can't find that where can i update my database with purchased response?
Answer: <code>    private class DungeonsPurchaseObserver extends PurchaseObserver {
    public DungeonsPurchaseObserver(Handler handler) {
        super(BusinessPunkBase.this, handler);
    }

    @Override
    public void onBillingSupported(boolean supported) {
            //Here you can update your DB

    }

    @Override
    public void onPurchaseStateChange(PurchaseState purchaseState,
            String itemId, int quantity, long purchaseTime,
            String developerPayload) {
        //Here you can update your DB

    }

    @Override
    public void onRequestPurchaseResponse(RequestPurchase request,
            ResponseCode responseCode) {

    }

    @Override
    public void onRestoreTransactionsResponse(RestoreTransactions request,
            ResponseCode responseCode) {
        //Here you can update
    }
}
</code>
Comment: It didn't worked.I tried in onPurchaseStateChange but there aren't any change.


Roots of Unity - Complex Numbers

Question: The sets $A = \{z : z^{18} = 1\} $and $ B = \{w : w^{48} = 1\}$ are both sets of complex roots of unity. The set $C = \{zw : z \in A \ \text{and} \ w \in B\}$ is also a set of complex roots of unity. How many distinct elements are in $C$?
Erm I'm wondering where to start this? Does the stuff in the set equal the ratio of $z$ to $z^{18}$ which is equal to 1 so $z^{18}= z$? and $w = w^{48}$? Help is appreciated, thank you.
Comment: The gcd or lcm of exponents say something to you?
Comment: You might like to think about this problem geometrically. Remember, multiplying complex numbers adds the angles.
Answer: HINT:
As gcd$(18,48)=6,$lcm $(18,48)=144$
The minimum positive integer of $n$ such that $(zw)^n=1$ is $144$ for all possible combinations of $z,w$
Now utilize Complex numbers and Roots of unity
Answer: A hint that is a bit too long for a comment, but should get you going along one possible path:
The elements of the set $A$ are of the form $e^{2s\pi i/18}$, and the elements of $B$ are of the form $e^{2t\pi i/48}$, so that when you multiply an element from $A$ by an element from $B$, what you get is a number of the form:
$$e^{(s/18+t/48).2\pi i}$$
so now you need to look at the possible values of $s/18+t/48 = (8s+3t)/144$.
Comment: I was wondering how you got that the elements of set A and B are of that form?
Comment: @LoyalKnight It follows from De Moivre's theorem, as [on this Wikipedia page](http://en.wikipedia.org/wiki/Root_of_unity#Examples), and it is one of the things that once you have used it a couple of times, it becomes a really useful fact to recall and use when needed.

Roots of Unity - Complex Numbers