1 Publisher Class Event, Multiple Subscribers, Different Parameters

Question: I am using delegates and events to pass data around in my application, but want the triggering of 1 event to pass different sets of data to different places.
Problem
I have a main class which performs some work.  Once the work is complete, I want it to notify a number of other classes (including the UI) so that other actions can be carried out.  The information that the other classes needs is different.
Example
Main.cs - Performs an action and wants to update the UI, send a text message and write to a log file.
UI updates a DataGrid so needs the individual fields.
The log file writer needs all the whole line as an array / List.
The text message code needs the Line, LineNumber and FileName, but as a tab delimited string.
The below all works correctly when I am only trying to update the UI, but when I try to send different information to different places then I run into errors.
I have tried creating different extensions of EventArgs, but if I try to declare 2 delegates with different signatures then I get an error message.
Any help would be much appreciated.
FrmMain.cs
Main main = new Main();
main.PatternFound += OnPatternFound;

main.DoSomeWork();

private void OnPatternFound(object source, LineEventArgs e)
    {
        UpdateDataGrid(e.Line, e.FileName, e.LineNumber);
    }

private void UpdateDataGrid(string line, string file, int lineNumber)
    {
        if (InvokeRequired)
        {
            Invoke(new Action<string, string, int>(UpdateDataGrid), line, file, lineNumber);
        }
        else
        {
            dgResults.Rows.Add(line, file, lineNumber);
        }
    }

Main.cs
public delegate void PatternFoundEventHandler(object sender, LineEventArgs e);
public event PatternFoundEventHandler PatternFound;

protected virtual void OnPatternFound(string line, string fileName, int lineNumber)
    {
        PatternFound?.Invoke(this, new LineEventArgs { Line = line, FileName = fileName, LineNumber = lineNumber });
    }

public void DoSomeWork()
{
    //Finished my work
    OnPatternFound(line, file, lineNumber);
}

LineEventArgs.cs
public class LineEventArgs : EventArgs
{
    public string Line { get; set; }
    public string FileName { get; set; }
    public int LineNumber { get; set; }
}

Comment: *"information that the other classes needs is different"* - you will have to decide what to put in `EventArgs` to satisfy majority of the needs. Or just add **multiple events**. I personally like another approach, where `sender` is used as a way to access all as instance members (`EventArgs` is not used). Be careful with multithreading though.
Comment: Thanks Sinatr.  So with the way that you do it, in the subscribers you would take the source and know that the caller was Main.  From there you would access Main.Line, Main.LineNumber, Main.FileName directly as they are public properties?
Comment: Yes. Though as I said, be careful. `InvokeRequired` tells you might have multithreading. Access to public members may require some kind of acquisition pattern. E.g. something bad may happen if you read public property with value of *previous* event. That's where `EventArgs` are safe, once instance is created it will persist (typically immutable) for all event handlers for a given event. Next event - new `EventArgs`.
Answer: What you are trying to achieve is possibly not a good approach for several reasons. Your decided to stick to events which means you decided to do what is called "inversion of control".
You implemented your main class in a way that says: "I am doing some sort of pattern matching and I will tell whoever is interested what I found and I am doing it in the way my event-args implementation defines." As a result it's now up to the subscribers to take this information as is or leave it.
Strictly spoken, what you said...

Performs an action and wants to update the UI, send a text message and write to a log file.

...is not what you implemented, because the main class does nothing of this. Anyway, in my opinion it is a viable solution to keep it event-driven, but then you would need to change your upstream code.
You could for example attach three different event handlers to this single event. Every handler would then have to transform the data in a format it needs: The logging handler would have to transform it to an array, the UI handler would have to concatenate it and so on.
The other alternative would be that you have one handler and dispatch to three different methods, like the OnPatternFound method would call a UpdateUI method and a Log method and so on.
Lastly you could also get rid of inversion of control and move your logic to the main class, but I would not recommend it! Your approach is good, but you should just not try to invoke the same event in three different ways. That's up to the subscribers.
Comment: Thanks Peit.  So if I try to keep the code as clean as possible, if I were to implement your suggestion of, "The other alternative would be that you have one handler and dispatch to three different methods", to avoid breaking DIP I would have to create some sort of Interface and pass an instance of the LogWriter, TextMessageSender, etc to the constructor of the Main class?  If not is there another way to achieve this without tightly coupling my code?
Comment: No, you misunderstood me. Of course you have many different opportunities. What I had on my mind was just what you wrote, except that your method ``OnPatternFound`` dispatches to three meaningful other methods: ``private void OnPatternFound(object source, LineEventArgs e) { UpdateDataGrid(e.Line, e.FileName, e.LineNumber); WriteLogMessage(...); SendTextMessage(...); }``.
Comment: Got it.  I see what you mean now.  Thanks.


canonical "simplest" cobordism for fixed boundary

Question: For a given orientable $n$-manifold, is there a canonical choice of $n+1$-manifold that has this manifold as its boundary?
For $n< 3$, every orientable manifold can be embedded into Euclidean $n+1$-space, and one can take the interior of the embedding as a "simplest, canonical" choice of such a cobordant manifold. E.g. the canonical choice of manifold that has the 2-torus as boundary would be the "solid torus". Moreover, it seems to me (correct me if I'm wrong) that every other cobordant manifold can be written as the connected sum of this "canonical" cobordant manifold and a closed $n+1$-manifold.
Is there still a "canonical" choice like that for $n\geq 3$? (I'm aware that in general orientable $n$-manifolds cannot be embedded in $n+1$-space, but maybe there's some other way to "add a filling" to a $n$-manifold.)
Comment: You should assume the $n$-manifold you start with is null-cobordant, otherwise no such $(n+1)$-manifold exists.
Answer: Uh...your comment about $n < 3$ is misleading, in the sense that every orientable surface admits many embeddings in 3-space; the torus, for instance, is the boundary of a cube-with-knotted-hole, or, if you prefer, a tubular neighborhood of a trefoil knot is a solid torus whose boundary torus is also the boundary of the complement of that tubular neighborhood; after an inversion swapping some point of the tubular neighborhood with infinity, we see the torus bounding a rather different compact 3-manifold-with-boundary.
So it's a tough sell to argue that every surface bounds a "natural" solid. The cube-with-knotted-hole example is a counterexample (I believe) to the last sentence of your second paragraph.
As to whether there is some way to pick a particular cobordism, either for surfaces or for higher-dimensional null-cobordant manifolds, one that has nice properties --- I have no idea. But the surface example leaves me doubtful.
Comment: Good point, maybe I should have just put it that way: any orientable surface is the boundary of a a collection of solid spheres with arbitrary many handles, which we can regard as the "canonical choice" of null-cobordism.
Comment: So the guess with the connected sum is wrong for $n=2$?
Comment: Sure looks that way to me.


Print queue content in order mutlithreaded

Question: I would like to be able to read from a queue and print element that was in the queue in the same order that they pushed, for example:
(order is from left to right)
Queue -> [{1, "Single"},{2,"Single"}, {1,"Married"},{1,"Divorced"},{2,"Married"},{2,"Divorced"},{1,"Widow"},{2,"Widow"}]
My goal is to synchronized thread so in any case there are 2 threads running at PrintInOrder with argument {1, "Single"} at one thread and {1,"Married"} at second thread, it will print the {1,"Single"} before {1,"Married"} because it first in the queue.
I try to solve it by the following code:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class PrintUsersQueueInOrderMutlithreaded
    {
        public static void Main()
        {
            var printUsersQueueInOrderMutlithreaded =
                new PrintUsersQueueInOrderMutlithreaded();
            printUsersQueueInOrderMutlithreaded.PopulateQueue();
            printUsersQueueInOrderMutlithreaded.ReadFromQueue();

            Console.ReadLine();
        }

        private Dictionary<int, SemaphoreSlim> userLocks;
        private Queue<User> usersQueue;

        private string[] maritalStatus = { "Married", "Divorced", "Widow" };

        public PrintUsersQueueInOrderMutlithreaded()
        {
            usersQueue = new Queue<User>();
            userLocks = new Dictionary<int, SemaphoreSlim>();
        }

        internal void PopulateQueue()
        {
            usersQueue.Enqueue(new User() { Id = 1, MaritalStatus = "Single" });
            usersQueue.Enqueue(new User() { Id = 2, MaritalStatus = "Single" });
            usersQueue.Enqueue(new User() { Id = 1, MaritalStatus = "Married" });
            usersQueue.Enqueue(new User() { Id = 1, MaritalStatus = "Divorced" });
            usersQueue.Enqueue(new User() { Id = 2, MaritalStatus = "Married" });
            usersQueue.Enqueue(new User() { Id = 2, MaritalStatus = "Divorced" });
            usersQueue.Enqueue(new User() { Id = 1, MaritalStatus = "Widow" });
            usersQueue.Enqueue(new User() { Id = 2, MaritalStatus = "Widow" });
        }

        internal void ReadFromQueue()
        {
            List<Task> tasks = new List<Task>();
            while (usersQueue.Count > 0)
            {
                var user = usersQueue.Dequeue();
                tasks.Add(Task.Run(() => PrintInOrder(user)));
            }

            Task.WaitAll(tasks.ToArray());
        }

        private void PrintInOrder(User user)
        {
            SemaphoreSlim userLock;
            lock (userLocks)
            {
                if (!userLocks.ContainsKey(user.Id))
                {
                    userLocks[user.Id] = new SemaphoreSlim(1, 1);
                }
                userLock = userLocks[user.Id];
            }

            userLock.Wait();
            try
            {
                Console.WriteLine(user);
            }
            finally
            {
                userLock.Release();
            }
        }
    }

    internal class User
    {
        public int Id { get; set; }
        public string MaritalStatus { get; set; }

        public override string ToString()
        {
            return $"Thread id {Thread.CurrentThread.ManagedThreadId,2}" +
                $" User id {Id,2} Marital status {MaritalStatus,2}";
        }
    }
}

It make we wonder if it possible to control the order of PrintInOrder execution :\
Thanks!
Comment: It makes me wonder what question you're asking? It also makes me wonder what's wrong with your current code.
Comment: The question is if it possible to keep the order of the queue in each thread per user, for example, thread 1 will print user 1 in the order Single , Married, Divorced and Widow.
Comment: Could you edit the question and clarify what part is given and unchangeable, and what is subject to potential modifications?
Answer: The moment you do Task.Run, you're making the order indeterminate by creating multiple parallel flows - you cannot recover from that; if you want to preserve order, you need to retain order. Actually, though, your code is already broken re thread-safety: you have concurrent access to usersQueue which is not a thread-safe object. If this was me, I would switch to something like a Channel<User>, and have one reader that simply dequeues from that (asynchronously, or even via await foreach on the .AsAsyncEnumerable() from it), and have that single reader to all the writes.
Comment: @LiorDadon the only way to do that is to have a single worker doing the printing; otherwise they are all just racing, and anyone can win
Comment: Thank you for your answer!
In other words, if the queue is given and I couldn't have access to it  and I do have access only to PrintInOrder method, is it impossible to print all users in the same order they was in the queue?
Answer: I would assume the goal here is that users with the same id should maintain order, but order is not necessary maintained for users with different Ids.
The by far simplest solution would just be to just print all users synchronously. The console is inherently synchronous anyway, so the whole thing with creating tasks is pointless if all you are doing is printing items. I.e. just do:
while (usersQueue.Count > 0)
{
    Console.WriteLine(usersQueue.Dequeue());
}

But lets assume you want to do some significant processing of users instead of just printing. So you would actually get some benefit from some amount of parallel processing.
The general approach is to queues, to ensure some items are processed in order, while allowing others to be processed concurrently. There are several possible ways to do this:

Create ConcurrentQueues yourself, and tasks looping thru each queue.
Use dataflow to create a pipeline. You could use filters and concurrency limits to configure the pipeline however you want.
Use a LimitedConcurrencyTaskScheduler per user Id, with a limit of one, when starting tasks.


Codigo em python usando biblioteca HMAC

Question: Estou fazendo um trabalho sobre criptografia para a faculdade usando HMAC junto com SHA256, e gostaria de entender o que este código faz em cada linha, estou um pouco confuso.
#!/usr/bin/env python3
import hashlib
import hmac
from math import ceil

hash_len = 32
def hmac_sha256(key, data):
    return hmac.new(key, data, hashlib.sha256).digest()

def hkdf(length, ikm, salt=b"", info=b""):
    prk = hmac_sha256(salt, ikm)
    t = b""
    okm = b""
    for i in range(ceil(length / hash_len)):
        t = hmac_sha256(prk, t + info + bytes([1+i]))
        okm += t
    return okm[:length]

Answer: Se eu estiver correto, é assim que funciona:
# Comentários na linha de cima à linha comentada.

import hashlib
import hmac
from math import ceil

# As palavras vão ter 32 bytes.
hash_len = 32

# Define um método que aplica SHA256 com a key e os data informados.
def hmac_sha256(key, data):
    return hmac.new(key, data, hashlib.sha256).digest()

# Cria um HMAC do tamanho length, com a chave ikm, o sal salt e uma informação, também usada para a criação do HMAC, info.
def hkdf(length, ikm, salt=b"", info=b""):

    # Gera uma chave preliminar com o salt e o ikm informados.
    prk = hmac_sha256(salt, ikm)

    # Declara um espaçador t.
    t = b""

    # Declara o HMAC final okm.
    okm = b""

    # Laço para gerar o HMAC; itera-se sobre um vetor [0..ceil(length / 32)]
    for i in range(ceil(length / hash_len)):
        # O espaçador guarda o resultado do algoritmo de hashing
        # a cada iteração, usando como base para tal a si próprio,
        # a info e um vetor de zeros de tamanho variável, apenas
        # como preenchedor (para que t não fique viciado).
        t = hmac_sha256(prk, t + info + bytes([1+i]))

        # Concatena t em okm
        okm += t

    # Recorta okm do tamanho length informado.
    return okm[:length]

Como o HMAC acompanha a mensagem assinada em todo o tempo da troca da mensagem, o fato de HMAC ser truncado não é significante, pois pode ser conferido a qualquer momento caso o receptor da mensagem tenha a mesma length, ikm, salt e info passadas como parâmetro de hkdf(), que também deve ser conhecido pelo lado receptor.
Comment: Muito obrigado! Agora consegui entender!
Answer: Embora a resposta do @Marcelo Uchimura responda a questão, acho que não responde o para que serve o código, inclusive menciona que isto seria para mensagens, onde não é ponto.

O HKDF é um KDF usando HMAC, há uma definição dele aqui. Bem, um KDF tem como entrada um dado "não tão aleatória" e uma outro dado, este que é uniformemente aleatório. Um bom exemplo de uso é quando uma chave é acordada via ECDH, já que a chave é "resposta matemática", portanto não é indistinguível de um dado completamente aleatório, dessa forma o uso de KDF é necessário. Da mesma forma, você pode querer ter várias chaves usando apenas uma única, assim o HKDF também pode ser usado, *mesmo que a chave necessite de mais bytes do que o valor original.*

O HKDF é dividido em duas parte, uma o extrator e outra o expansor. Este é o extrator:
prk = hmac_sha256(salt, ikm)

A ideia aqui é incluir o salt e o ikm. Presume que o salt é distinguível de um dado uniformemente aleatório, já o ikm talvez seja, mas não precisa ser.
Seu resultado, o prk, é um dado uniformemente aleatório, assumindo que o hmac_sha256 seja um PRF seguro, ou que ao menos a compressão do SHA256 seja um PRF.
Depois disso temos o expansor, que consume o prk, ele está em:
for i in range(ceil(length / hash_len)):

    t = hmac_sha256(prk, t + info + bytes([1+i]))

Observe que o prk é usado como chave nesta etapa. Isso é, a chave gerada pelo extrator é usada no expansor. O expansor irá criar n bytes necessários, por isso existe o range para repetir o processo até que atinja a quantidade de bytes exigida.
Formalmente este processo é descrito como:
K(1) = HMAC(PRK, CTXinfo || 0),
K(i + 1) = HMAC(PRK, K(i) || CTXinfo || i), 1 ≤ i < t,

O CTXinfo é uma informação adicional, pode ser omitido. Então basicamente a entrada do HMAC é: o resultado anterior (se i > 1) concatenado com a informação adicionado e concatenado com o i, sendo i um único byte, sequencial.
No caso desta implementação, como está definido o t = b"", não haverá diferença entre a primeira ou última execução.
Por fim o okm[:length] irá apenas cortar a saída, já que a hash tem tamanho fixo (no caso do SHA-256), então se quiser valores não múltiplos de 256, por exemplo, não conseguirá sem truncar.

Codigo em python usando biblioteca HMAC


How to override supersized.shutter.css

Question: I'm not the best in php manipulation that's why I'm asking.
function supersized_libraries_info() {
  $libraries['supersized'] = array(
    'title' => 'Supersized',
    'website' => 'http://www.buildinternet.com/project/supersized/',
    'download url' => 'https://github.com/f3ndot/supersized/tree/3718ae83f0945e327cc09530b959c5a8b049871f',
    'version arguments' => array(
      'file' => 'slideshow/js/supersized.3.2.8.min.js',
      'pattern' => '/Version : (\d+)/',
      'lines' => 4,
    ),
    'files' => array(
      'js' => array(
        'slideshow/js/jquery.easing.min.js',
        'slideshow/js/supersized.3.2.8.min.js',
        'slideshow/theme/supersized.shutter.min.js',
      ),
      'css' => array(
        'slideshow/theme/supersized.shutter.css',
        'slideshow/css/supersized.css',
      ),
    ),
  );
  return $libraries;
}

That's the all code of supersized_libraries_info() function. I wan't to hook that using hook system so for my theme it suppost to be
mytheme_supersized_libraries_info() right?
Then I wan't to just edit css location so that supersized.shutter.css will be in placed in my theme location.
(My code!)
function koko_supersized_libraries_info($variables) {
  $libraries['supersized'] = array(
    'files' => array(
        'css' => array(
        path_to_theme() + '/css/supersized.shutter.css',
        'slideshow/css/supersized.css',
      ),
    ),
  );

I just want to edit the css property of that object. I don't know how to get to there.
Mine edit just doesn't work at all (nothing happends).
I want to clear css array and then set mine values.
Answer: To alter the value returned from an implementation of hook_libraries_info(), a module or a theme needs to implement hook_libraries_info_alter(). As with other alter hooks, there isn't a way to override the value returned from a specific module, so the hook name is the usual one: modulename_library_info_alter() or themename_library_info_alter().
As side note, you code contains also an error: The parameter is $variables, but the code is using $libraries.
Answer: Like @kiamlaluno said, you need to implement hook_libraries_info_alter(); however, you should change your code too into something like this:
function koko_libraries_info_alter(&$libraries)
{
   if( isset( $libraries['supersized']))
      $libraries['supersized']['files']['css'][] =
    path_to_theme().'css/something.css';
}

This way you only insert an additional CSS at the bottom of the library CSS files, and if the library changes its filenames, or (more likely) add more files, you wont need to change your hook as well. Note that $libraries is passed by reference.
You only ensure that your custom CSS is always the last to be valued.

How to override supersized.shutter.css


Passing Arguments to another WPF Application doesn't work

Question: i got a problem when passing two arguments from one WPF App to another WPF App.
I publish the second WPF App to my Desktop and i want to start it with my first WPF App.
First-Program:
public MainWindow()
{
    InitializeComponent();
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.FileName = @"C:\Users\User\Desktop\Work.application";
    startInfo.Arguments = "test 1234";
    Process.Start(startInfo);
}

To get the arguments in the second program i tried the following code
1.Get Arguments in Mainwindow with Environment.GetCommandLineArgs() => doesn't        work
public MainWindowSecondProgram()
{
    InitializeComponent();
    string[] args = Environment.GetCommandLineArgs();
    foreach (String element in args)
    {
        MessageBox.Show(element);
    }
}

2.Get Arguments in App by using startup function => doesn't work
public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        foreach (string element in e.Args)
        {
            MessageBox.Show(element);
        }
    }
}

Now if i copy the Work.exe (not Work.application) from my Visual Studio Project folder to my Desktop and change the path from
@"C:\Users\User\Desktop\Work.application" to
@"C:\Users\User\Desktop\Work.exe"

and run my first program again, it works perfect with
the first function  and the second function.
So why is it working with the EXE but not with the published application?
Edit:
I tested both functions by passing two arguments threw the debugger and it works, but not by passing it to the published application, only EXE works.
Comment: Possible duplicate of [C# ProcessStartInfo arguments](http://stackoverflow.com/questions/15454456/c-sharp-processstartinfo-arguments)
Comment: @MethodMan i did the same, but no results. think its a different problem. he is talking about passing to EXE and im talking about the passing to.application. (different?!) EXE works for me, but not for the application.
Comment: why do you think `application` file can be treated as normal application? To me it's just a ***setup*** file. It's for convenience only and yes it's totally unprofessional (even publishing via web nowadays usually requires users to download a full-fledged setup file as `exe` or `msi` - it looks much more professional and users nowadays are smart enough to know how to use those setup files). Because it's just a quickly setup file, running it will run the setup first (prepare the exe file) before actually running the exe file. What you want is impossible and ***nonsense***.
Comment: @Hopeless why should it be nonsense? its an offline click-once application, which is published/changed around 2 times a week because of new features or changes. every time the agent start the application, it checks if there is a newer version and you dont need admin permissions to execute the app. Best regards
Comment: I mean `application` file is out of your control, it's like a compiled package or setup file and cannot be understood as what you put in your application. I guess you may also want to pass some arguments to a `msi` file? It's a package rather than a program (of yours). When running setup file like `application` file, the logic in your code is not even run. In fact the actual exe will be called in sequence but the info about args will be omitted (I believe this is by design).
Comment: @Hopeless ok, now i got it. Thanks. There are several articles about that problem like https://robindotnet.wordpress.com/2010/03/21/how-to-pass-arguments-to-an-offline-clickonce-application/
Answer: For a Windows Store App, you need to use Application.OnLaunched. Try this code:
public partial class App : Application
{
    protected override void OnLaunched(LaunchActivatedEventArgs args)
    {

            MessageBox.Show(args.Arguments);
    }
}

Note that you'll have to turn that string into an array yourself.
Comment: Filed: First thanks for your answer. The application is a desktop wpf application not a windows store app. Best regards
Comment: Either way I believe if you're inheriting from `Application`, this is the way to get arguments.
Answer: To read arguments in a ClickOnce application, use:
AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData

You can read more here.
Also, not sure, but you may need to run the ClickOnce app via the .appref-ms shortcut as opposed to the .application file itself.


Is it true that $E[Y|W]=E[Y|E(X|W)]$, given that $W$ is $X$ measured with error

Question: In Carroll's 2006 book "Measurement Error in Nonlinear Models", and on p38 it is stated without proof that:

[One can] estimate the regression of $Y$ on $(Z, X)$ and then to substitute into this model $\{Z,E(X|W)\}$ [ ... ] [which is equivalent to] to substituting (Z, W) into the fitted model for the regression of $Y$ on $(Z,W)$.

$W$ is a measurement of the predictor $X$, but measured with error. $Z$ is a covariate measured without error.
Which is the following equivalence.
$$ E[Y|W] = E[Y|E(X|W)]$$
(I have remove $Z$ from the subsequent calculations, as they are not needed in my problem).
Is there a proof for this? I have found the following paper that mentions this, but it is vague.

Babanezhad, Yaghmaei (2010) "Bias Terms of Measurement Error in Treatment by expected Estimating Equations"
Comment: It is clearly the case when $E[X|W]=\alpha W$.
Comment: Excuse me, but what does $\alpha$ mean in this context?
Comment: Re.: This is a coefficient. Any coefficient.
Comment: Re-reading the paragraph in the book, I wonder if the end of it could
not be ``substituting $(Z,W)$ into the fitted model for the regression of $Y$ on $(Z,X)$''. Then the
question would concern the possible quality $E(Y|W) = E[Y|X=E(X|W)]$,
which seems sensible. In this case, I would still answer: no
with a counter-example.
Comment: @Xi'an, do you have a paper (or other reference) that shows that this is clearly the case when $E[X|W]=αW$. I would like to understand this for myself (this maybe something elementary in stats, that I don't know yet).
Answer: The relation $E[Y | W] = E[Y | E(X | W)]$
does not hold in a general context, e.g. when if $Y$ is assumed
to be independent of $W$ conditional on $X$.
Assume that $X$ is standard normal and that $W := X^2$, so that $E(X |
W) = 0$. If we take $Y = X^2 + \varepsilon$ where $\varepsilon$ is a
noise independent of $X$, then $E[Y | W] = W = X^2$, while $E[Y | E(X
| W)]$ is simply $E(Y) = 1$.
Now, I confess that in this example $W$ can not be regarded as $X$
with a measurement error, so further assumptions should be imposed.
As suggested by @X'ian, the relation would hold if we could be sure
that $E[X|W]$ is a linear function of $W$, say $\alpha W$ for some
$\alpha$. This linearity is granted for example by assuming that the
vector $[X,\,W]^\top$ has an elliptically symmetric distribution. In
the present context, only $\alpha =1$ would make sense.
Comment: Ok, so say for example $W$ is normally distributed with mean $X$ (aka $W \sim N(X,\sigma)$), so that $E[W]=X$, this would mean that as $W$ is symmetrically distributed around $X$, the relation would hold? Also, I am not sure why $E(X|W)=0$?
Comment: In your question the assumptions about $X$ and $W$ are not explicit
and I thought that it was about the identity in a fairly general
context, so I allowed $W := X^2$, which is *not* $X$ with error. You
might  have in mind the extra assumption that $X =W +$ error or $W
=X +$ error. See also my comment to the question: I suspect that your
interest is on the value of the regression function of $Y$ on $X$ when
$X$ is taken equal to $E(X|W)$. This is a different identity.
Comment: I understand that your first paragraph was about $W$ and $X$ in a general (non error) case. Are you saying that the identity I stated in the question $E[Y|W]=E[Y|E(X|W)]$ is incorrect, and that I should be trying to proove $E(Y|W)=E[Y|X=E(X|W)]$ instead?
Comment: No, I would not say that is is incorrect but that it could
not really express what you want to do: susbtitute $E(X|W)$ in place of
$X$ in the regression $E(Y|X)$ of $Y$ on $X$. If $g(X):=E(Y|X)$ (say)
and $h(W):=E(X|W)$, the question would be about the relation
$E(Y|W)=g[h(W)]$. I can hardly figure out that $E[Y | E(X | W)]$ could
be known in practice, since this mixes the regression and error
models in a quite subtle way.
Comment: Ok, so to make it a bit simpler, as I want to substitute $E(X|W)$ in place of $X$, then I need to prove that $E[X|W]=\alpha W$ (where as yourself and X'ian stated, $\alpha=1$)? Then this leaves the regression on Y out of the evaluation.
Answer: The equation
$$E[Y\mid W] = E[Y\mid E(X\mid W)]\;\;\;  \text {does not hold in general}$$
but let's see a very "well-behaved" example where it does hold. Assume that $\{Y, W\}$ follow a bivariate normal distribution, and that $\{X,W\}$ also follow a bivariate normal. For simplicity assume all three variables have zero unconditional expected values. I will use for compactness $E(X \mid W) \equiv Z$ (which is not the "Z" in the question). Then
$$E(Y \mid W) = \frac {{\rm Cov}(Y,W)}{\sigma^2_W} W =  \frac {E(YW)}{\sigma^2_W}W  \tag{1}$$
$$E(X \mid W) \equiv Z  = \frac {{\rm Cov}(X,W)}{\sigma^2_W} W = \frac {E(XW)}{\sigma^2_W} W\tag{2}$$
where "$\sigma$" denotes here the standard deviation. $Z$ follows a normal distribution, and being just a scaled version of $W$, it too has a joint bivariate normal distribution with $Y$. So
$$E(Y \mid Z) = \frac {{\rm Cov}(Y,Z)}{\sigma^2_Z} Z = \frac {E(YZ)}{\sigma^2_Z} Z \tag{3}$$
We are wondering "Is $(1) = (3)\;?$". For it to hold we must have
$$\text{If}\;\;\; (1) = (3) \implies \frac {E(YW)}{\sigma^2_W} W = \frac {E(YZ)}{\sigma^2_Z} Z \tag{4}$$
From $(2)$ we have
$$\sigma^2_Z = \left(\frac {E(XW)}{\sigma^2_W}\right)^2 \sigma^2_W = \frac {[E(XW)]^2}{\sigma^2_W}  \tag {5}$$
Inserting $(5)$ into $(4)$, and inserting the expression for $Z$ from $(2)$ we obtain the requirement
$$\text{If}\;\;\; (1) = (3) \implies \frac {E(YW)}{\sigma^2_W} W = \frac {E(YZ)\cdot \sigma^2_W}{[E(XW)]^2} \frac {E(XW)}{\sigma^2_W} W$$
and simplifying we arrive at
$$\text{If}\;\;\; (1) = (3) \implies \frac {E(YW)}{\sigma^2_W}  = \frac {E(YZ)}{E(XW)}   \tag{6}$$
Now, assume that $W = X+U$ where $U$ is zero-mean  normal independent of $X$ and $Y$ (this is consistent with the assumptions of pairwise bivariate normality). Then
$$ E(XW) = E(X^2) = \sigma^2_X$$
Inserting  into $(6)$, while also substituting for $Z$ (from $(2)$) we obtain
$$\text{If}\;\;\; (1) = (3) \implies \frac {E(YW)}{\sigma^2_W}  = \frac {E\left(Y\frac {E(XW)}{\sigma^2_W} W\right)}{\sigma^2_X}  $$
$$\implies  \frac {E(YW)}{\sigma^2_W}  = \frac {E(XW)}{\sigma^2_W}\frac {E\left(Y W\right)}{\sigma^2_X}$$
$$\implies 1 = \frac {E(XW)}{\sigma^2_X}$$
which holds so here indeed
$$E[Y\mid W] = E[Y\mid E(X\mid W)]$$
does hold.


FLutter dart error expected value of Type 'List' but got one of type 'List'

Question: I have a class C like :
class C {
  int? first;
  int? second;
  C({
    this.first,
    this.second,
  });
}

and I have two classes that one of them extend from the other:
class A {
  int? id;
  List<C>? list;
  A({
    this.id,
    this.list,
  });
}

class B extends A{
  String? title;
  B({
    this.title,
    list,
  ):super(
    list: list,
  );
}

in my cubit I made instance of B class like below and I got this error :
B b = B(title: '', list: []);

expected value of Type List<C> but got one of type List<dynamic>

where is my problem?
Answer: In your B class you need to define the type for list when you extends A:
class B extends A {
  String? title;
  B({
    this.title,
    List<C>? list,// change to this
  }) : super(
          list: list,
        );
}


Woocommerce change product image via php

Question: I'm trying to change product image via php. But I can't get it to work.
    require_once(ABSPATH . 'wp-admin/includes/media.php');
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $yesterday = date("Y-m-d",  time() - 60 * 60 * 24);
    $jsondata = file_get_contents("730.json");

    ini_set('memory_limit', '-1');
    $json = json_decode($jsondata, true);
    $price = $json["AWP | Asiimov (Well-Worn)"][$yesterday]["price"]/100;

    $post_information = array(
        'post_author' => $user_id,
        'post_content' => '',
        'post_status' => "publish",
        'post_title' => 'test',
        'post_parent' => '',
        'post_type' => "product",
    );

    $image = media_sideload_image("http://www.technologijos.lt/upload/image/n/technologijos/it/S-49657/samsung-ssd-840-evo.jpg", 0, "The WordPress Logo");

    $post_id = wp_insert_post($post_information);

    $attachment = wp_get_attachment_image( 18, 'thumbnail' );

    update_post_meta( $post_id, '_visibility', 'visible' );
    update_post_meta( $post_id, '_stock_status', 'instock');
    update_post_meta( $post_id, 'total_sales', '0');
    update_post_meta( $post_id, '_downloadable', 'no');
    update_post_meta( $post_id, '_virtual', 'yes');
    update_post_meta( $post_id, '_regular_price', $price );
    update_post_meta( $post_id, '_sale_price', "1" );
    update_post_meta( $post_id, '_purchase_note', "" );
    update_post_meta( $post_id, '_featured', "no" );
    update_post_meta($post_id, '_sku', "145");
    update_post_meta( $post_id, '_product_attributes', array());
    update_post_meta( $post_id, '_sale_price_dates_from', "" );
    update_post_meta( $post_id, '_sale_price_dates_to', "" );
    update_post_meta( $post_id, '_price', $price );
    update_post_meta( $post_id, '_sold_individually', "" );
    update_post_meta( $post_id, '_manage_stock', "no" );
    update_post_meta( $post_id, '_backorders', "no" );
    update_post_meta( $post_id, '_stock', "" );
    update_post_meta( $post_id,  '_product_image_gallery', $attachment  );

The last line doesnt work. And i dont know how to get it working. I tried changing different things, (I am new to PHP/ WordPress).
Answer: Are you trying to set the featured image?
If so, you may want to use the function given in the answer here.
The Function:
function Generate_Featured_Image( $image_url, $post_id  ){
    $upload_dir = wp_upload_dir();
    $image_data = file_get_contents($image_url);
    $filename = basename($image_url);
    if(wp_mkdir_p($upload_dir['path']))     $file = $upload_dir['path'] . '/' . $filename;
    else                                    $file = $upload_dir['basedir'] . '/' . $filename;
    file_put_contents($file, $image_data);

    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => sanitize_file_name($filename),
        'post_content' => '',
        'post_status' => 'inherit'
    );
    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    $res1= wp_update_attachment_metadata( $attach_id, $attach_data );
    $res2= set_post_thumbnail( $post_id, $attach_id );
}

Usage:
Generate_Featured_Image( '../wp-content/my_image.jpg',   $post_id );
                                                      // $post_id is Numeric ID... You can also get the ID with:          wp_insert_post()

Answer: I would like to add to bryceadams answer.
Seems like that, for example, eBay's Finding API returns images whose URL has a structure that will not allow the command
$filename = basename($image_url);

to operate as expected because, what happens is, all URLs of the images have the same ending basename and the files get conflicted. I found out that the command
$filename = basename($image_url, '.jpg') . (string) rand(0, 5000) . '.jpg';

works better for many APIs. Hope it adds up and helps.


Can Dell SonicWall NetExtender record urls visited

Question: My company is in geographical different area and I am in a different area. They have asked me to install VPN client Dell SonicWall NetExtender
I want to know if I am connected to it can they track which websites I am visitingr or is this not possible?
I did a tracert and my packets are going to appropriate locations without being sent to them. However, I want to know if this is really possible.
Answer: If you don't believe tracert, why would you believe the word of psuedonymous strangers? Maybe we work for your employer and are conspiring to mislead you. It's possible they could be routing some internet addresses through them and not others. It's possible they could change the routing policy every time you connect.
If it's a company computer, it's possible they could be setting policies like browser proxy use to make web requests go through them, but which won't affect traceroute. That might be a feature included in the SonicWall VPN client if it has pre-connection setup scripts, even if it's not a company computer.
Or, most likely, they route the office internal network over the VPN and leave everything else alone.
Comment: Are you high? Or is this simply your way of talking? Thanks anyways for the information.
Answer: It's certainly possible to set it up they way you're asking about, but the tracert shows they're not doing this.  With almost any VPN, there is a choice between sending all traffic through the VPN, or sending only necessary traffic through the VPN.  Bandwidth costs money, and none of the companies I've serviced care what websites employees visit when out of the office.
If they have an IT guy/gal/team, you could just ask one of them.  Unless they're socially inept or you're a jerk, they'll be straight with you.


Adding standard deviations

Question: An AP Statistics problem reads:
Mr. Lopez teaches one statistics class. The girls have a semester average of 83 with standard deviation 9 and the boys have a semester average of 78 with standard deviation 6. Assuming that the students are all independent of one another, what is the standard deviation of the entire class?
The answer according to the book is 10.8 because the book treats boys and girls as random variables. Thus the answer simply took the square root of the sum of the variances, which gave an answer of 10.8.
However, boys and girls are not really random variables in this case. Theoretically there could be 2 boys and 100 girls in the class. Wouldn't that change the answer?
Answer: Why do you say the boys and girls are not random variables?  Yes there could be the numbers you quote, but why does that say they are not random.  The book is using the fact that variances add as long as the variables are uncorrelated, which is where the root mean square addition for standard deviations comes from.
Comment: I didn't think we can assume such a thing given the problem. For example, means also add - assuming that these are random variables. However, if there are 50 girls and 2 boys, then the means would not add.

I think it would only be appropriate to view them as random variables if the question asked what would be the average score after choosing one random boy and one random girl. No?
Comment: Yes, the means add.  We are given the means, so the mean number of total students is $151$
Comment: But if there are 2 boys with a mean of 78 and 8 girls with a mean of 83, then we can't just add 78 + 83 = 161. Rather, we would need to do: $\frac{(78*2 + 83*8)}{10}= 82 $
Comment: I just realized I was reading the semester average and standard deviation as applying to the number of students of each sex attending each day, not as test scores.  In that reading it is fine to add the variances.  As test scores the book is badly wrong.  Even if there are an equal number of boys and girls you need to consider the difference in averages of the two sexes.  Imagine you had three boys with mean 10 and standard deviation 0 and three girls with mean 90 and standard deviation 0.  The class average would be 50 and the standard deviation would be 40.

Adding standard deviations


If Else Statements in Cypress

Question: I have problem with if-else in cypress. I have 3 questions. And the questions is not consistent, always change. So I wanted to set an answer for specific question. The error is, whenever the question B appear, cypress cant skip the question A and it stops. Cypress didn't read my if and else, and I can't understand, why it happens.
Here is my code:
let disabled = null;

cy.contains("What is your dream car brand?").then(() => {
  disabled = true;

  cy.get("input[name=securityQues]").type("Ferrari");

  cy.end();
});

if (disabled == false) {
  cy.contains("What is your favorite movie?").then(() => {
    cy.get("input[name=securityQues]").type("Forrest Gump");
  });
} else {
  cy.contains("Where is your favourite place to vacation?").then(() => {
    cy.get("input[name=securityQues]").type("Japan");
  });
}

Comment: Could you please describe the problem? Do you have any errors?
Comment: Here I have 3 questions. And the questions is not consistent, always change. So I wanted  to set an answer for specific question. The error is, whenever the question B appear, cypress cant skip the question A and it stop. Cypress didnt read my if and else. Why cypress cant read my if else part?
Comment: I think you want to use jquery to test for the various texts, e.g `let carQuestion = Cypress.$('div:contains("What is your dream car brand"); if (carQuestion)...`.
Comment: `cy.contains(..)` has a built-in test which fails when the text is not present.
Comment: A better way is to break it down into separate tests for each question, and control which question shows via fixture.
Comment: Ok,I got the solution already. Thanks for helping!
Answer: Try to use another way to find your main element with a question. .contains in this case will not work. Try to use .get('css-selector') and then you can appropriate access that element. See an example here: https://github.com/valor-software/ngx-bootstrap/blob/development/cypress/support/timepicker.po.ts#L117
Answer: Doing conditional testing on user interfaces is completely discouraged as your tests will never be deterministic. I'd tell you to try to find a workaround to your way of testing what you want to test.
Here there is a nice read on that https://docs.cypress.io/guides/core-concepts/conditional-testing.html#The-problem

If Else Statements in Cypress


Positioning UIImageViews in UITableView cells

Question: I'm creating a grid of thumbnail images, using a UITableView where each cell display 3. At this stage, I'm simply trying to place 3 static images to get placement/size right. But I'm unable to control the position and size of the thumbnail image. Here's my code for one thumbnail image:
<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// after getting cell..

UIImage *image = [UIImage imageNamed:@"placeholder.png"];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50.0, 0.0, 85.0, 85.0)];
imageView = [[UIImageView alloc] initWithImage:image];
[cell addSubview:imageView];

return cell;

}
</code>
Is my understanding correct that I control the position and size of the image by setting it in the UIImageView?
I appreciate the help.
Answer: You need to scale the image in the view:
<code>UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[imageView setFrame:CGRectMake(50.0, 0.0, 85.0, 85.0)];
[imageView setContentMode:UIViewContentModeScaleAspectFill];
[cell addSubview:imageView];
</code>
Comment: Thanks.I tried adding your line (setContentMode) and it had no effect. Is there anything I should check in the storyboard?
Comment: You are initializing two different imageView, see edit in a minute.
Comment: Holy.. it must be time for a break. Thanks so much, it worked!


cant able to test file extension on test class?

Question: visuaforce page:
<apex:page sidebar="false" controller="UploadOpportunityScheduleLineItem123">
    <apex:form >
        <apex:sectionHeader title="Upload data from CSV file"/>
          <apex:pagemessages />

                <apex:inputFile value="{!contentFile}" filename="{!nameFile}" />
                <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>

   </apex:form>
</apex:page>

apex:
public with sharing class UploadOpportunityScheduleLineItem123{

    // Global variables
    public string nameFile{get;set;}

    Public Id parentId{get;set;}

    public Blob contentFile{get;set;}

    List<account> lstScheduleToUpdate = new List<account>();

    public account objSchedule{get;set;}
    //String array for taking csv data by line.
    String[] filelines = new String[]{};

    //set for storing all id's from csv.
    set<String> opptoupload{get;set;}

       //Main constructor
    public UploadOpportunityScheduleLineItem123()
    {
        //Initalizing required objects.
        objSchedule = new account();
        opptoupload = new set<String>();

    }
    //Method to read file content and check extension and file format.
    public Pagereference ReadFile()
    {

        parentId=Apexpages.currentPage().getParameters().get('ParentId');
        //If without selecting csv file you clicked on upload it will give error message.
      if(nameFile == null)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'You should select csv file to upload');
            ApexPages.addMessage(errormsg);
            return null;
        }
        //Taking file extension.
        String extension = nameFile.substring(nameFile.lastIndexOf('.')+1);
        //Checking if file extension is .csv.
        if(extension == 'csv' ||extension == 'CSV')
        {
            nameFile =blobToString( contentFile,'ISO-8859-1');
            //Spliting by new line

            filelines = nameFile.split('\n');
            //Spliting values by (,) for checking coloumn size

                for (Integer i=1;i<filelines.size();i++){
                String[] inputconvalues = new String[]{};
                inputconvalues = filelines[i].split(',');
                account b = new account();
                b.name= inputconvalues[0];
                b.billingcountry = inputconvalues[1];
                b.billingcity = inputconvalues[2];
                lstScheduleToUpdate.add(b);
                }
                //Checking if list is not empty then updating.
                if(lstScheduleToUpdate.Size()>0)
                {
                    insert lstScheduleToUpdate;
                }
                ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.info,'Batches File uploaded successfully');
                ApexPages.addMessage(errormsg);
            return null;
        }
        //If file is not csv type then it will give error message.
        else
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'File type should be csv type');
            ApexPages.addMessage(errormsg);
            return null;
        }
    }
    public static String blobToString(Blob input, String inCharset){
        String hex = EncodingUtil.convertToHex(input);
        System.assertEquals(0, hex.length() & 1);
        final Integer bytesCount = hex.length() >> 1;
        String[] bytes = new String[bytesCount];
        for(Integer i = 0; i < bytesCount; ++i)
        bytes[i] =  hex.mid(i << 1, 2);
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
    }
}

test class :
@IsTest(SeeAllData=true)

    private class testexceltoaccount
    {
          static testmethod void testLoadData() {
                   StaticResource testdoc = [Select Id,Body from StaticResource where name ='testMethodCSVUpload1'];
             UploadOpportunityScheduleLineItem123 testUpload = new UploadOpportunityScheduleLineItem123();
             testUpload.contentFile= testdoc.Body;
             testUpload.ReadFile();
              }

    }

Cant able to cross this section of code in code coverage :
String extension = nameFile.substring(nameFile.lastIndexOf('.')+1);
        //Checking if file extension is .csv.
        if(extension == 'csv' ||extension == 'CSV')
        {

I tried many possible to cross code coverage but still it is at that point .Please help me in this regard.
Thanks in advance
Answer: When we use apex:inputFile on VF page and upload any file, then name of file is automatically update field into the field specified in  filename attribute, but when you are writing test class you only specifying content of file
testUpload.contentFile= testdoc.Body;
You should add name in nameFile global variable manually
testUpload.nameFile= 'test.csv';
@IsTest(SeeAllData=true)
private class testexceltoaccount
{
      static testmethod void testLoadData() {
               StaticResource testdoc = [Select Id,Body,Name from StaticResource where name ='testMethodCSVUpload1'];
         UploadOpportunityScheduleLineItem123 testUpload = new UploadOpportunityScheduleLineItem123();
         testUpload.contentFile= testdoc.Body;
         testUpload.nameFile= 'test.csv';
         testUpload.ReadFile();
          }

}


Feeling eighth note quintuplets

Question: Many of my favorite really complicated songs have these quintuplets in them (5 equally-spaced notes in the space of a quarter note), yet I can't seem to "feel" these 5-note subdivisions. I have no trouble listening to, say, Take 5 by Dave Brubeck and feeling that, but how on earth can I feel the 5-note divisions in the context of a 4/4 time signature? How do the really advanced players of these songs conceptualise this rhythm?
If the answer is just to practice it, that's okay, but ideally if anyone knows any helpful tips, that would be great.
Comment: https://www.youtube.com/watch?v=jsLFlLU6xjM especially part 2
Comment: Yep,  practice practice practice.
Comment: For specific guidance... what's the song??
Answer: I'd start easy. See if you can feel triplets. See if you can switch easily between feeling triplets and feeling duplets or quadruplets. Once you've got that down, see if you can feel quintuplets (or at least have a strong enough pulse that you can try stuffing 5 notes in each beat instead of 3 or 4).
Comment: Exactly this.   I might add "try playing quintuplets as   2-sixteenths + sixteenth-triplet, then reverse that, then finally as evenly spaced quint"  .  Once you can do that, you've got it all locked down.
Comment: Agreed here. I personally use Carnatic syllables and quintuplets really clicked for me when I used "ta-ka-gi-na-ton" for learning to squeeze 5 into a beat. For spreading it out over 2 beats, I simply feel the halfnote and adjust accordingly.
Answer: Maybe you're trying to be too mathematical about this.  Quintuplets (and similar divisions) are often used expressively, over a flexible pulse.  Sequence this literally into a DAW and you'll see what I mean.  It will sound horrible!
Comment: "sound horrible" is a personal opinion not shared by many others
Comment: Go on, do it then!

Feeling eighth note quintuplets


Configuring favicon with expires header in htaccess

Question: I have implemented Expires headers via mod_expires on my Apache server and have successfully created expires headers for most file types, however I am having trouble with the favicon.
I initially tried adding a set of instructions for the .ico files but when checking via YSlow it has no expiry set.
When this didn't work I amended it to be a GIF, however this seems to have the same issue.
Other gif's on the website have correctly set expires headers (accoridng to YSlow at least).
Can anyone shed any light on this situation?
Answer: If you're using Apache, just add a MIME-Type for the favicon in your website's .htaccess file or to Apache's mime.types file:
<code># Add Proper MIME-Type for Favicon
AddType image/x-icon .ico
</code>
Then, set the Expires header a few month(s) in the future:
<code># Enable Apache's mod_expires Module
ExpiresActive On
ExpiresByType image/x-icon "access plus 1 month"
</code>
After clearing your browser's cache and reloading the page, you should see the favicon.ico file being served with the Cache-Control header being set to a date (specified in seconds) in the future:
<code>Content-Type image/x-icon
Cache-Control: max-age=2592000
</code>
For related information, see the YSlow documentation on Making Your favicon.ico Small and Cacheable at: http://developer.yahoo.com/performance/rules.html#favicon
Comment: +1 This absolutely works.  Make sure to _clear your cache_ though people, I thought this didn't work until I manually cleared my cache.  Not sure why a hard refresh didn't do it but whatever.
Answer: This here works for me:
<code># Cache the following content for 1 month (4 Weeks)
<FilesMatch "\.(jpg|jpeg|png|gif|ico)$">
Header set Cache-Control "max-age=2419200, public"
</FilesMatch>
</code>


2 sample Z test for non normally distributed data

Question: I'm trying to analyse the impact of a marketing campaign and I'm looking to identify the most appropriate statistical test. I have one group of customers who received the campaign (approx 100,000 people) and a random control (approx 50,000 customers) who received nothing. I want to measure whether there is any difference in the average spend from both groups in the period following the campaign launch.
The vast majority of customers in both groups will spend nothing after the campaign. Only approximately 2% of the customers in the groups will spend anything. So the average spend variable in both groups is not normally distributed - it will have a huge tail at 0, corresponding to the large number of people who will spend nothing.
As the population sizes are very large (100,000 and 50,000) can I just use a 2 sample z test as normal due to the central limit theorem? Or will the fact that the variable being tested is highly skewed mean that a 2 sample z test is invalid?
Comment: That's not what the CLT says. Z-test requires distributions to be normal.
Comment: @user2974951 - with 50,000 observations, the distribution of the sample mean may very well be so close to Gaussian (thanks to the CLT) that a z-test will work fine, even with 98% of the observations being 0.
Answer: As noted in a comment, z-test is not appropriate in this case, since it requires a normal distribution and your data is obviously not normally distributed.
EDIT: When can you use z-test? It is true that many test statistics may approach normality with large number of samples. Now the question is whether your mean amount spent will approach a normal distribution given the large number of your samples. The way you have described (with majority, 98% of individuals spending nothing), it might be contested. I am at heart an experimentalist, so here is what I'd do: draw samples of 10,000 from your data and see whether the means are normally distributed on a q-q plot. If your data is good enough at 10K samples, it will be even better at 50K.
One possibility is, of course, a non-parametric alternative such as a U-test. With these numbers, you could also safely use a randomization approach.
However, it might be that whatever the obtained p-value, your results will not be very meaningful – precisely because of the large sample size, which will allow to detect even very small effects. If the amount spent is, say, in \$10-20 range, would an average difference of \$0.05 make any difference?
In other words, your statistical test may be overpowered.
Rather than focusing on the test, you could focus on the effect size – or actual difference (and estimate its confidence intervals).
Another problem with your approach is that very often the amount spent is not a continuous variable; for example, we are talking about a price list which contains a finite number of prices (e.g., \$9.99, \$19.99 and \$29.99, and no-one ever spends \$12.75). If that is the case, maybe comparing the frequencies of individuals who choose a particular option (or none at all) using a χ² test or something similar might be a better choice.
Comment: Well, yeah, that's the question. Normally, I would say that you are right, but I wonder whether with such a large fraction of 0's you will approach normality at your sample size. I have included an edit to my answer.
Comment: They are samples, because you want to infer about future clients (the full population) and not merely about the people you have in your experiment. If I take 3 mice and give them a novel drug, and compare it to the 3 mice that did not get the drug, I could in theory treat these 6 mice as full populations (after all, no other mice in the world received my drug), but the whole purpose of my statistics is to make inference about what happens when I give that drug to any other mice.
Comment: Thanks - there appears to be conflicting advice on this online. I've read other advice saying when sample sizes are high a z-test or t-test approach is fine. For the U test, how would I handle all the 0 values when the records are ranked? As they make up say 98% of the records would they all get give n the same rank?
Comment: Thanks for the advice. The bit I'm struggling with is that these groups aren't really "samples" from populations. They are populations - the test group is everyone who got the campaign. The control group is  "everyone else" who could have received the campaign but didn't due to a random selection (pre-campaign the groups are identical). From the answers so far, after checking sample means for normality as suggested, I'm unsure if I should do a) a z test on the 100k vs the 50k or b) take large samples (e.g. 40k) from both groups and do a z test / t test on those. Which is the better approach?


TP-Link TG-3468 on an IBM x3850 M2

Question: I got a networks card from TP-Link. It is the TG-3468. I wanna place it into my IBM server x3850 M2. It has PCIe x8 slots. The slot is a little bit longer than the lenght of the card, but it fits.
Also the BIOS shows, that there is an ethernet card there. But when I start, after initialising everything, the server shows a blinking _ sign.
Whats wrong and what can i do?
Answer: First Check Boot Order in Bios..
You can disable the Ethernet-Bios launch for the PCI Slot of your card (guess you wont boot from this card) You can check this in IBM Bios.
If you reach the Bootloader and you try to Boot Linux then apply iommu=soft to Kernel boot flags

TP-Link TG-3468 on an IBM x3850 M2


Logging Request/Response size in access_log of Nginx

Question: I need to log request/response size(body+headers) in the access_log. Any idea how to do it in nginx?
In apache we can do it using %I..%O...
Answer: Taken from ngx_http_log_module:

$bytes_sent: the number of bytes sent to a client
$connection: connection serial number
$connection_requests: the current number of requests made through a connection (1.1.18)
$msec: time in seconds with a milliseconds resolution at the time of the log write
$pipe: "p" if request was pipelined, "." otherwise
$request_length: request length (including request line, header, and request body)
$request_time: request processing time in seconds with a milliseconds resolution; time elapsed between the first bytes were read from the client and the log write after the last bytes were sent to the client
$status: response status
$time_iso8601: local time in the ISO 8601 standard format
$time_local: local time in the Common Log Format
Answer: I would use these 2 parameters in nginx.conf:

log_format  perf            '$remote_addr $status - $request_length $bytes_sent'

According to documentation ( http://wiki.nginx.org/HttpLogModule) the $request_length is only the body of the request, but I have confirmed that it includes all headers (I have some GET requests with lots of cookies which have more than 1400 bytes in total). $bytes_sent is total number of bytes sent to the client (as opposed to $body_bytes_sent which is compatible with apache %B).
Comment: @user1559834 seems it is `$body_bytes_sent` now. Not sure if they changed it since my post in year 2012 or it was a typo.
Comment: $body_sent is not a variable in nginx logging module
Answer: $request_length:
request length (including request line, header, and request body)
$bytes_sent:
response length (including header, and body)
$body_bytes_sent:
response length only include body.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


OLS is BLUE. But what if I don't care about unbiasedness and linearity?

Question: The Gauss-Markov theorem tells us that the OLS estimator is the best linear unbiased estimator for the linear regression model.
But suppose I don't care about linearity and unbiasedness. Then is there some other (possible nonlinear/biased) estimator for the linear regression model which is the most efficient under the Gauss-Markov assumptions or some other general set of assumptions?
There is of course one standard result: OLS itself is the best unbiased estimator if in addition to the Gauss-Markov assumptions we also assume that the errors are normally distributed. For some other particular distribution of errors I could compute the corresponding maximum-likelihood estimator.
But I was wondering if there is some estimator which is better-than-OLS in some relatively general set of circumstances?
Answer: Unbiased estimates are typical in introductory statistics courses because they are: 1) classic, 2) easy to analyze mathematically.  The Cramer-Rao lower bound is one of the main tools for 2).  Away from unbiased estimates there is possible improvement.  The bias-variance trade off is an important concept in statistics for understanding how biased estimates can be better than unbiased estimates.
Unfortunately, biased estimators are typically harder to analyze.  In regression, much of the  research in the past 40 years has been about biased estimation.  This began with ridge regression (Hoerl and Kennard, 1970).  See Frank and Friedman (1996) and Burr and Fry (2005) for some review and insights.
The bias-variance tradeoff becomes more important in high-dimensions, where the number of variables is large.  Charles Stein surprised everyone when he proved that in the Normal means problem the sample mean is no longer admissible if $p \geq 3$ (see Stein, 1956).  The James-Stein estimator (James and Stein 1961) was the first example of an estimator that dominates the sample mean.  However, it is also  inadmissible.
An important part of the bias-variance problem is determining how bias should be traded off.  There is no single "best" estimator.  Sparsity has been an important part of research in the past decade.  See Hesterberg et al. (2008) for a partial review.
Most of the estimators referenced above are non-linear in $Y$.  Even ridge regression is non-linear once the data is used to determine the ridge parameter.
Comment: One of my favourite admissible estimators: a single arbitrarily chosen point of the parameter space which is not an impossible value :)
Comment: @chl seconded. Great overview.
Comment: @probabilityislogic Those often are admissible, but what you wrote is [not 100% true if we (somewhat) artificially restrict the parameter space](https://stats.stackexchange.com/q/529917/247274) (e.g. we only allow for heads-heads or tails-tails coins). That a possible constant is not always admissible surprised me.
Answer: I don't know if you are OK with the Bayes Estimate? If yes, then depending on the Loss function you can obtain different Bayes Estimates. A theorem by Blackwell states that Bayes Estimates are never unbiased. A decision theoretic argument states that every admissible rule ((i.e. or every other rule against which it is compared, there is a value of the parameter for which the the risk of the present rule is (strictly) less than that of rule against which it's being compared)) is a (generalized) Bayes rule.
James-Stein Estimators are another class of estimators (which can be derived by Bayesian methods asymptotically) which are better than OLS in many cases.
OLS can be inadmissible in many situations and James-Stein Estimator is an example. (also called Stein's paradox).
Comment: @suncoolsu, that's not the typical definition of admissibility. The one you've given is (much) stronger. An admissible estimator is one that is *not* uniformly dominated, i.e., for every other rule against which it is compared, there is a value of the parameter for which the the risk of the present rule is (strictly) less than that of rule against which it's being compared. Conversely, an *inadmissible* estimator is one that is (weakly) dominated by *some* other estimator for *every* value of the parameter and is strictly dominated for *at least* one value by that same estimator.
Comment: @suncoolsu asymptotic unbiasedness is very different from the usual sense of "unbiased". Any reasonable estimate should be asymptotically unbiased.  One more note: shouldn't the statement about admissible estimators be the other way around? ie every admissible estimator is generalized Bayes.
Comment: Thanks for the pointers. Will need to hit the library to make sense of it all.
Comment: @cardinal Yup. You are right. I will correct it.
Comment: @cardinal. Using math is much easier than simplifying it in plain English. But that is just me. Thanks for the correction @cardinal
Comment: @suncoolsu what do you mean by "never unbiased"?  Do you mean with respect to the prior?
Comment: @vqv There is a theorem by Blackwell which says that "Bayes estimates are almost never unbiased". Please notice I am talking about asymptotic unbiasedness here.
Comment: @suncoolsu, this is definitely one of those instances where a few symbols say something much more clearly than "plain English". I fear my description is too clumsy, but it's hard to get it precise in few words. Another attempt would be: "An admissible estimator dominates every other estimator at at least one point in the parameter space. The point of domination will typically vary according to the estimator being compared against."
Comment: @vqv In re: "Any reasonable estimate should be asymptotically unbiased." I don't necessarily disagree, but this is a strong statement, no? I haven't got an example offhand but it seems plausible that there exist estimators with nice finite sample properties that happen to be inconsistent. But perhaps not. And I think you're correct that every admissible estimator corresponds to a Bayes rule.
Comment: @vqv - You are correct as well. Sorry for misinterpreting your question.
Comment: @JMS. I think @vqv is correct, this is another way of thinking about consistency.
Comment: @suncoolsu I wasn't so clear; I should have stuck with asymptotically biased (consistent under L1). Still, I'm not so sure that there do not exist reasonable estimators that are asymptotically biased but have good finite sample properties. But like I said, I can't think of an example offhand.
Comment: @suncoolsu, consistency and asymptotic unbiasedness are different things. To get some notion of equivalence requires more structure on the problem, like uniform integrability. There are some estimators that are consistent yet asymptotically biased and, of course, estimators that are asymptotically unbiased but inconsistent.
Comment: @JMS Asymptotic unbiasedness does not imply consistency.  Asymptotic unbiasedness: $|E \hat{\theta} - \theta| \to 0$; L1 consistency: $E|\hat{\theta} - \theta| \to 0$.  L1 consistency is much stronger.  Anyway, this is probably far off the topic of the original question.
Comment: Of course, where is my head. Good catch.
Comment: @everyone. Sorry. I meant - "a step towards consistency". Because consistency is a sum of squared bias and variance in $L_2$ specifically.
Comment: @suncoolsu, you must be using a definition of consistency that is different. The usual definition is a statement about *convergence in probability*, not in any $L^p$ space. Of course, if you have the latter, you get the former for free.
Comment: @cardinal. I can't resist my temptation to use math anymore. $E[\hat \theta - \theta]^2 = E[\hat \theta - E[\hat \theta] + E[\hat \theta] - \theta]^2 = E[\hat \theta - E[\hat \theta]]^2 + ( E[\hat \theta] - \theta)^2 = Var[\hat \theta] + Bias^2$. So basically @cardinal and me are talking about the same thing but from a different perspective. If Variance **and** Bias go to 0 in **probability**, consistency holds, otherwise not. Or am I still incorrect? Thats what I have learnt in my courses here.
Comment: @suncoolsu, Let $\hat{\beta}_n$ be an estimator for a parameter, $\beta$, derived from a sample of size $n$. Then $\hat{\beta}_n$ is *consistent* for $\beta$ if $\hat{\beta}_n \to \beta$ ***in probability***. This is a weaker requirement than requiring that $\mathbb{E} |\hat{\beta}_n - \beta|^p \to 0$ for some $p > 0$.
Comment: @suncoolsu, I see you edited your comment while I was writing mine. Convergence in *any* $L^p$ space guarantees convergence in probability. This can be seen by a straightforward application of Markov's inequality. But, convergence in probability is weaker than this requirement. Hence, consistency of a parameter is (substantially) weaker than requiring the parameter to converge to its true value in, say, $L_2$, the latter being more or less what it looks like you're stating.
Comment: @cardinal. Yeah I was talking about MSE and not the convergence.
Comment: @suncoolsu, Some people refer to convergence of a parameter in $L_2$ as *mean-square consistency*. But, in general, a consistent estimator need not have asymptotically negligible bias *nor* variance. In fact, it need not even have finite variance. If you're really sadistic, you can undoubtedly cook up an example where the variance *isn't even defined*.
Comment: @cardinal. Thanks for the inputs :-) Helps improve my understanding!
Comment: @suncoolsu, mine, too. That's one of the reasons I enjoy this site. Cheers.
Answer: There is a nice review paper by Kay and Eldar on biased estimation for the purpose of finding estimators with minimum mean square error.
Answer: "Best" in BLUE means the minimum variance.
Variance is a non-negative quantity, so its lowest value is zero.
If you estimate the coefficients by picking a constant every time, then your estimator has zero variance.
In other words, just estimating the coefficients as zero every time, regardless of the data, is a zero-variance estimator.
Further, this estimator is a linear combination of elements of $y$, so this is a linear estimator.
Somewhat related, it came to my great surprise that this approach need not result in an estimator that is "admissible" under square loss.
While this is technically a way of doing estimation, it is a silly approach by human standards. For this reason, I believe that it is important to put some conditions of what you want out of an estimator if you don't just want the minimum-variance estimator. For instance, perhaps you're willing to drop linearity and incur some bias, but then you demand that the estimator at least be consistent. Perhaps you do not demand consistency, but you want the minimum MSE. Perhaps you want the estimator that gives the lowest maximum risk across all possible parameter values (a so-called "minimax" estimator).


Passing variable in a URL(php)

Question: Is there a way that I can possibly pass my variable from an offline page to my online page?
I have the following code on a page on Website A that contains the email of my receiver:
$emailOutput = $dataQuery_email->contact_email;
This is my code so far but it's not working.
file_get_contents("http://my_domain.com/sendEmail.php?email_id=".$emailOutput);
On my sendEmail.php I did this:
$to = $_GET[$emailOutput];
Is there any other way?
Comment: Possible duplicate of [How to send a GET request from PHP?](https://stackoverflow.com/questions/959063/how-to-send-a-get-request-from-php)
Answer: Change $to = $_GET[$emailOutput]; to $to = $_GET['email_id']; as that is the name of the get parameter you have passed in your URL.
Take a look at this article for a basic overview of HTTP GET
Answer: Your url parameter was email_id, and $emailOutput was a variable/ value that youve passed to the url,
replace $_GET[$emailOutput] with $_GET["email_id"];

Passing variable in a URL(php)


Linear Regression Analysis

Question: I am very new to linear regression analysis and I am trying to solve my first examples, most of the examples I have come across contained some tables and data where I could easily use the formulas I know and solve them. However, I have just come across an example that does not have much data and I have no idea where I should start and which formulas I should use to initiate.
we assume that the number of schoolchildren's close relationship has a linear association with the likelihood (0-100%) that a child becomes bullied in the classroom. We build a regression model where we predict the likelihood of becoming bullied with the number of friends. We found out that if a child has no friends, the likelihood of being bullied is 70%. We also know that the regression coefficient (beta) for the variable 'number of friends' is -10.
This question is asking me to write the regression equation and also predict the likelihood of being bullied if the child has 14 friends.
Shouldn't I simply use the following formula? But isn't something missing in the question?
ŷ = β0 + β1x
Comment: What you should be looking at is *logistic* regression, not *linear* regression. Linear regression doen't give you probabilities.
Comment: Am I missing something, or do you just plug the numbers into the equation? $\beta_0$ is clearly 70, and $\beta_1$ is -10. So $\hat{y}_{14} = 70 + (-10) \cdot 14 = -70 = 0$. If you assume this is the only variable influencing the likelihood of being bullied, then this is logical. I think perhaps the wording "likelihood" and "probability" may be confusing in this instance because those are typically not the domain of linear regression, but in this instance it just seems to be the response variable. Perhaps someone can show me why I'm wrong.
Answer: Simple illustration to know why the linear regression in this case does not work , and what is the logistic regression .
First of all , you have to know that your dependent variable $y$ (child becomes bullied ) is a binary variable , that means it takes two outcomes either Yes (becomes bullied ) or No (does not become bullied ).Let us create a dummy variable to indicate if an observation yes or no :
$y=1$ if yes
$y=0$ if no
In the example we want to know what determines that a child becomes bullied , our independent variable  in this case is the number of friends $x$
Suppose that we run the regression model:
$Yes(y=1) =\alpha +\beta{x_i} + error$
Now suppose we got the following outputs
$yes=-1+0.5{x_i}$
Since our dependent variable is binary , that means we  want to know what makes it  change from 0 to 1 , in other words , we want to know what increase the likelihood of being bullied $Pr(y=1)$
So our model could be
$Pr(y=1)=-1+0.5{x_i}$
Now can you calculate the likelihood that a child being bullied who  has 25 friends ?.I suppose ,you know that the probability is bounded wherby   $0\leq p \leq 1$.
If you get a strange result you have to find out a function which satisfies  this condition $0\leq p \leq 1$ (squared function or exponential function..etc)
Answer: If it doesn't have much data you may have a problem.
If your data on bullying consists of a yes/no variable (bullied vs. not) for each child, then @JimBoy is right and you should use logistic regression. If you haven't studied that yet, then you should either do so or look for a different problem.  Linear regression (which is what people usually mean when they just say "regression") is for dependent variables that are continuous - that is, they can take on any value.
If you tell us what data the example you are using does supply, we may be able to give a more comprehensive answer
Comment: Thank you for your reply. All that is provided by the question is exactly what I have written. There is absolutely nothing else found in the task. I am having problem even writing the equation of the line. Is it even possible to write the equation based on the information given by the question?
Comment: Yes, but the task seems kind of silly.  Is this homework? If so, you should add the `self study` tag.
Comment: How can I do that? How can I write the equation based on the information provided? No, this is not homework, but basically just an exercise from a series of tasks I asked my lecturer to provide me to practice the topic.
Comment: You have the probability when the IV = 0 and you have the intercept and you have the parameter estimate (10). So it should be some simple algebra from the logistic regression formulas which are hard to type in a comment but see e.g. https://en.wikipedia.org/wiki/Logistic_regression
Answer: Using the linear probability model (*), you can solve your problem using the given equation. When you've used the values to make a prediction, you'll probably get an unexpected likelihood (hint: what are the range of possible likelihoods? can they be negative?), which is one of the reasons why you'll learn logistic regression. Sometimes though this model can be usefull as well.
(*) https://en.wikipedia.org/wiki/Linear_probability_model

Linear Regression Analysis


If $s^n\in S$ and $S$ is a multiplicative subset of a comutative ring, then $s\in S$

Question: I'm trying to solve this question:

Let $S$ be a multiplicative subset of a commutative ring $R$ with identity. If $I$ is an ideal in $R$, then $S^{-1}\left(\operatorname{Rad}I\right) = \operatorname{Rad}\left(S^{-1}I\right)$.

the $\subset$ part is easy. In order to prove the converse, I need to prove first that if $s^n\in S$ and $S$ is a multiplicative subset, then $s\in S$, I think is true, because if $s^2\in S$, then $s^{-1}\cdot s^2=s$, and then by induction we will have $s\in S$, when $s^n \in S$ am I right?
Remark
$\operatorname{Rad} I=\{r\in R;r^n\in I$ for some $n\}$
Edit
Following the comments below, my approach is wrong, I need a suggestion to solve the converse, I proved also that Rad I is an ideal, maybe I can use this?
Edit 2
Take $s'\in S$, note that if $a/s \in$ Rad$(S^{-1}I)$, then $a/s=as'/ss'$ $\in S^{-1}$(Rad$I$), because $a\in$ Rad $I$ and $S$ is multiplicative.
Now, am I right?
Thanks in advance
Comment: This is true for *saturated* multiplicative sets, that is, satisfying "if $xy\in S$ then $x\in S$ and $y\in S$"; for instance complements of prime ideals are saturated.
Comment: How do you know that $s^{-1} \in S$? The statement you are trying to prove is just false; for example, the multiplicative subset of $\mathbb{Z}$ generated by $4$ doesn't contain $2$.
Answer: Let $x\in \operatorname{Rad}\left(S^{-1}I\right)$, i.e. $x^n=s^{-1}i \ (s\in S, i \in I)$. Denote $y=sx$. Then $y^n=s^{n-1}i\in I$ since $I$ is an ideal. Hence $x=s^{-1}y\in S^{-1}\left(\operatorname{Rad}I\right)$.


ClassName Snippet for vscode and react

Question: Is there a way to make VScode to autocomplete/make a snippet of className so when i choose is it it will complete to className={``} (instead of current situation when it just complete to "className" ) ?
Thanks
Comment: Please show more code to show what you are selecting in what context and the desired result.  It needs to be more obvious.
Answer: You can try TabNine or VSCode IntelliSense and see if that helps, but it is hard for an IDE to assume 100% what you want to do, I am just giving examples of extensions that might help more.
Answer: You can create a snippet and you can set className by reading your fileName.
you can refer Documentation.
https://code.visualstudio.com/docs/editor/userdefinedsnippets#_create-your-own-snippets
Answer: In VSCode, click CTRL + SHIFT + P to open the command window. Type 'Configure user snippets' and select the first file. It will open a file containing your user defined snippets. Inside the topmost curly brackets, right before the closing bracket, insert a comma then the following snippet:
    "ClassName with formated string": {
    "prefix": "cla",
    "body": [
        "className = {`",
        "   ${1:}",
        "`}"
    ],
    "description": "ClassName with formated string"
}

So, the file will look like this:
enter image description here
To use the snippet, type cla, which should bring it as an option in your autocomplete menu

ClassName Snippet for vscode and react


HTTP Range Header Openshift Scalable App

Question: I have a Scalable Node.JS application on OpenShift that relies on the range header being present. I'm not sure what is removing the header (maybe haproxy?), but I'm wondering if anyone has experience with this and how I can get the range header to come through to my application.
I know for sure that the range header is being sent from the client as it's present on my development server so it's definitely something in OpenShift's stack that's removing the header before it reaches my app.
Answer: I noticed you reported this as a bug, worth linking here: https://bugzilla.redhat.com/show_bug.cgi?id=1127925
Comment: Good call! I actually switched the application to run on AWS Elastic Beanstalk for now as this was a deal breaker for me, but I should have added the link to the bug.


Como funciona o sistema de cache do React-Native?

Question: É o seguinte, criei um sistema que usa alguns componentes Image e carregam as imagens da internet.
Só que eu quero que as imagens apareçam mesmo quando o sistema está offline.
Percebi que existe um cache das imagens quando eu as acesso, e quando abro o app offline, muitas delas estão carregadas.
Quero saber como devo fazer para que todas as imagens fiquem no cache e também se existe um limite de tempo em que elas ficam armazenadas lá.
Aguardo.
Answer: Salve, Ítalo.
utilize essa módulo https://github.com/DylanVann/react-native-fast-image, ele vai te ajudar com o cache.
Emiliano


Is it appropriate to ask about experiences with specific extensions and help customizing?

Question: After looking at every multi-warehouse,  inventory and shipping extension, I can find, I have settled on one closest to my needs. The cost is reasonable to my customer.
I looked at taking the time to develop the needed functionality and it is beyond my current abilities.
I am not sure many in the  Magento Community need multi-warehouse functionality, my other customers don't need to manage several locations.
The developers have dropped customizing and conflict resolution and are focusing on developing the extensions, just this month Oct 18. It is guaranteed to work on standard Magento install, so that's where I'd have to start.
So My Question:
Is it OK to ask about this extension, about the experiences developers have had or about getting help customizing?
Also helpful would be extensions that are know to work with this one.
If it helps the discussion I will give the name of the Company and extension.
Moderator edit: the question in question: https://magento.stackexchange.com/questions/9945/what-is-your-experiences-with-using-and-or-modifying-multi-warehouse-by-innoexts
Comment: I really wrestled with this, knowing that I would ruffle some feathers. I would like to know who makes good extensions and who to avoid. Not everyone knows this, especially the new folks who are new to everything even asking questions. I can see why that is avoided, who would want to moderate that? But it would be handy. I saw an extension list and several of the extensions I checked out and the were only adverts for a custom shop. I even tried to contact the developer googled and found them and they never returned the call or emails.
Answer: I'd say yes. It's clear from your post here that the intent is genuine.
Comment: The answer I was wanting, just wanted to check the protocol.
Comment: My question was deleted.  Cannot find it now.
Comment: Undeleted. Need to have a pow-wow with fellow moderators as we seem to have a healthy difference of opinion :-)
Comment: Clarity is good. Thanks to all the moderators for taking time to provide guidelines and insight to others.
Answer: How to make sure that you are not affiliated with the extension vendor and not just promoting it? Unless you are a known member of a community there is no way. This is not a discrimination. I'm just trying to protect this (website) act of good will from the exploits who are trying to use it to push their stuff.
It's not an answer but in fact it is.
Comment: I agree that un-disclosed affiliation need to be avoided. I am not affiliated with this company. I actually am not sure I made the correct call buying the software. They changed the support policy and dropped any customizing and conflict resolution. So not very shining recommendations. But I do not have the experience to build the things I found in the software.  So This is why I asked first on meta. I changed my question a little but the fact is that I have this extension and want to customize it. I'd build it from scratch but I don't have the expectancy. I'm looking for the big pieces first.
Comment: I would build it from scratch but I don't have the experience or time.


How to track recently viewed nodes using JavaScript on a completely cached website?

Question: I want to make a block of recently viewed nodes on a website which is completely cached using Boost module (it saves a static HTML page for every request on the website). I don't want to disable Boost and recache a page every time this block updated, instead, I wondering if it possible to use JavaScript here. Is there any way I can do this?
Comment: Short answer, sure? You'd have to wire up a menu route and JS with ajax that triggers the node statistics API (I assume this is what you are talking about).
Comment: @Kevin I was thinking of a client-only approach using some tracking of visited pages that are filtered by page address (if JS have such mechanic). But I'll be happy with any method available, since it's barely worth writing it from scratch.
Comment: That data still has to be stored somewhere though - right? Or are you saying just using cookie or HTML5 LocalStorage? That would all be JS at that point basically, not much Drupal. The only Drupal part might be getting that output on the page, which you could maybe do with JS dom writing anyway.
Answer: Not a module, but still better than nothing. Note that some parts of the script are theme-aware.
This goes to the bottom of node--[type].tpl.php:
<?php if ($page): ?>

<?php endif; ?>

This to the new block (block's text format shouldn't change tags):

And the script.js to attach in theme.info
var currentlyStored = JSON.parse(localStorage.getItem('recentlyVisited'));

function updateRecentlyVisited() {
    var maxLinks = 20;
    var currentPage = new Array (document.URL, document.getElementsByClassName('node-title').item(0).textContent);

    if (currentlyStored)
        for (var i = 0; i < currentlyStored.length; i++) {
            if (currentlyStored[i][0] == currentPage[0]) {
                currentlyStored.splice([i],1);
                break;
            }
        }
    else
        currentlyStored = new Array();
    currentlyStored.unshift(currentPage);
    if (currentlyStored.length > maxLinks)
        currentlyStored.pop();

    localStorage.setItem('recentlyVisited', JSON.stringify(currentlyStored));
}


How to run multiple testing files with one config file in flutter without making long terminal command?

Question: I want to run multiple integration tests with one config file. By doing something like adding those files to a single file.
I found this answer "https://stackoverflow.com/questions/56236606/can-i-run-multiple-integration-tests-with-one-single-config-file-in-flutter".Here the terminal command length is getting bigger as the test files are increasing.
This is the folder structure of testing in my project
I want to run both tests by running app.dart without using lengthy commands as below.
flutter drive --target=test_driver/test_first/app.dart --driver=test_driver/test_first/app_test.dart flutter drive --target=test_driver/test_first/app.dart --driver=test_driver/test_first/login_test.dart

by doing something as below
import 'package:flutter_driver/driver_extension.dart';
import 'package:digiemo_flutter/main.dart' as app;

void main() {
  enableFlutterDriverExtension();

  //need to do something as below
  run app_test //some code to run first test
  run login_test //some code to run second test

  app.main();
 }

so the command should be:
flutter driver --target=test_driver/test_first/app.dart

something like that
Comment: Does this answer your question? [Can I run multiple integration tests with one single config file in Flutter?](https://stackoverflow.com/questions/56236606/can-i-run-multiple-integration-tests-with-one-single-config-file-in-flutter)
Answer: Simply give it the path of the folder
flutter drive --target=test_driver/test_first/


PHP - Checar se existem parâmetros GET em uma URL

Question: Boa noite!
Essa dúvida fica mais para curiosidade.
Tenho uma página em php que exibe certos tópicos de um fórum phpbb. Entre os dados armazenados está o caminho (url) do tópico, que vem no formato http://meusite.com.br/forum/viewtopic.php?f=yy&t=xx. Pelo pouco que eu sei o f e o t são requisições GET.
Pretendo concatenar nessa string os parâmetros do Google Analytics (o que eu poderia fazer sem verificar integridade simplesmente adicionando &utm_blablabal...), mas aí fiquei pensando: e se eu mudar a estrutura dos links (tipo via url_rewrite)? Ou se por algum motivo ambos os formatos (com/sem GET) passarem a ser armazenados pelo PHPBB? Alguns links obviamente viriam quebrados (por "abrir" a parte da requisição usando um & em vez de um ?), e assim necessitaria de uma verificação.
O que eu quero fazer é simplesmente checar nessa string se existem variáveis GET como essas (pro caso de um dia eu alterar o esquema das URLs e assim os links não quebrarem) e, dependendo da existência ou não, adicionar um & ou um ? antes dos parâmetros do Analytics. Basicamente uma "verificação de integridade".
Grato pela ajuda, e desculpem se não fui claro.
Answer: Simples. Você pode contar o que está no $_GET
empty($_GET)

Ou
(count($_GET) > 0)

Se for de uma url especifica, faça assim
strlen(parse_url($url, PHP_URL_QUERY)) > 0

Comment: Espera... o $_GET não é reservado à requisições? Porque essa URL não está "vindo" de uma requisição HTTP. É uma string que está armazenada em um banco (do PHPBB) e eu preciso apenas checar se existe parametros do estilo GET nela, para poder inserir os adicionais do adsense sem repetir o ?.
Answer: Para quebrar sua string que representa uma URL você pode utilizar os métodos parse_url() e parse_str().
parse_url() recebe uma string que representa uma URL e quebra a string em componentes. Dada sua URL de exemplo http://meusite.com.br/forum/viewtopic.php?f=yy&t=xx parse_url() retorna:
array(4) {
  'scheme' =>
  string(4) "http"
  'host' =>
  string(14) "meusite.com.br"
  'path' =>
  string(20) "/forum/viewtopic.php"
  'query' =>
  string(9) "f=yy&t=xx"
}

parse_str() recebe uma query string, string com parâmetros GET, e quebra em um array com chaves e valores. Dada a query string da URL acima f=yy&t=xx, o método retorna:
array(2) {
  'f' =>
  string(2) "yy"
  't' =>
  string(2) "xx"
}

E para reconstruir sua URL após adicionar um novo parâmetro GET (ou modificar um já existente) você pode utilizar:

o método http_build_query(), que recebe um array associativo (array com chaves e valores), para reconstruir a query string;
+ uma simples concatenação de strings para reconstruir a URL a partir dos componentes da mesma que você pegou com parse_url() e a query string que você refez no passo acima.

Abaixo, o código completo para quebrar uma URL, adicionar parâmetros GET e reconstruir a URL novamente:
<?php

$url_string = 'http://meusite.com.br/forum/viewtopic.php?f=yy&t=xx';

// quebrando a URL em partes
$url_partes = parse_url($url_string);

// quebrando os parâmetros GET da URL
parse_str($url_partes['query'], $parametros_get);

// adicionando novo parâmetro GET
$parametros_get['novoParametro'] = 'VALOR';

// reconstruindo a query string (os parâmetros GET juntos)
$url_partes['query'] = http_build_query($parametros_get);

// reconstruindo a URL
$url_string = $url_partes['scheme'] . '://' . $url_partes['host'] . $url_partes['path'] . '?' . $url_partes['query'];

echo $url_string . "\n";

vai printar:
http://meusite.com.br/forum/viewtopic.php?f=yy&t=xx&novoParametro=VALOR


Method orWhere does not exist. Laravel 5.3

Question: BadMethodCallException in Macroable.php line 74:
Method orWhere does not exist.
    $category = $categories->where('Node_ID', (explode('.', $cat{$title_id})[0]))
        ->orWhere('Node_Path', $cat->{$category_name})
        ->first();

If I try without "orWhere" works, if I use it, throws an Error. Someone knows where is the mistake?
Answer: You are trying to use orWhere on collections, thats why its showing you the error. You should use this on model like this (taking Category as a Model):
$category = Category::where('Node_ID', (explode('.', $cat{$title_id})[0]))
                     ->orWhere('Node_Path', $cat->{$category_name})
                     ->first();

See Laravel Docs for orWhere()

Hope this helps!


Por que posso atribuir uma instância de uma classe a uma variável cujo tipo é a interface?

Question: Exatamente a que se refere quando eu crio um objeto na memória, porém associo ele a varável a1 do tipo interface (AreaCalculavel)? Estou um pouco confuso, veja abaixo o exemplo.
package exercicio0101;

public class Aplicacao {

    public static void main(String[] args) {

        double area;

        AreaCalculavel a1 = new Quadrado(10);
        area = a1.calculaArea();
        System.out.println("Area do Quadrado: " + area);

        AreaCalculavel a2 = new Circunferencia(5);
        area = a2.calculaArea();
        System.out.println("Area da Circunferencia: " + area);

        AreaCalculavel a3 = new Retangulo(10, 2.5);
        area = a3.calculaArea();
        System.out.println("Area do Retangulo: " + area);
    }
}

Answer: Interfaces são contratos, então elas só existem para controlar acesso aos membros de um objeto, elas não determinam o que realmente é o objeto, só o que eles são capazes de fazer (mesmo quando tem uma implementação default de métodos nela). Só classes concretas podem criar objetos e elas que definem como o objeto será estruturado na memória. Então a interface não tem nenhum papel na definição do layout da memória, só as 3 classes usadas criam objetos.
Outro ponto importante a notar é que objetos que possuem interfaces são sempre por referência e por isso na variável só terá um ponteiro que indica onde o objeto está de fato, desta forma a variável tem um tamanho fixo (sempre 4 ou 8 bytes dependendo da arquitetura que está rodando). Não poderia ser diferente porque você só pode ter objetos de tamanhos potencialmente diferentes através de indireção, mantendo assim o mesmo tamanho na variável. O objeto mesmo fica em outra área (heap).
Inclusive tudo isso poderia ser feito com apenas uma variável, ou até mesmo sem nenhuma, mas o que quero dizer é que as 3 variáveis que guardam o objeto são compatíveis e como o valor não é usado mais poderia reaproveitar a variável, ou nem ter a variável.
Só atente que a variável poderá acessar só o que a interface deixa, mesmo que objeto nela tenha vários outros membros disponíveis, lembrando que ela é um contrato do que pode acessar, e eu entendo que ela tenha o método calcularArea() e mais nada, então é só isso que poderá chamar nela (até poderá acessar outras coisas do objeto se fizer um cast, mas quase sempre que faz um cast algo está errado).
Talvez precise estudar sobre hierarquia de tipos para entender melhor esses conceitos. Não é simples entender quando falta vários outros fundamentos, porque para cada explicação exige um conhecimento. A construção do conhecimento flui melhor quando se aprende primeiro os conceitos fundamentais para aplicá-los depois.
Para entender melhor sobre interface:

Uma interface é uma variável?
Como e quando usar Interface? (cheio de links sobre o assunto)
Programar voltado para interface e não para a implementação, por quê?
Classes que implementam interfaces são consideradas subclasses?
Em orientação a objetos, por que interfaces são úteis?

Coloquei no GitHub para referência futura.