Changing a form value when submitting

Question: I'm using Javascript to change an input value before submitting and saving it into a MySQL table, but after changing the value I get a blank row in the database.
I'm using it like this
document.getElementsByName('wifestatus').value  = "nothing";

I tried getElementsById but it gives me the same result.
     <input type="radio" name="gotmarried" id="gotmarried1" value="لا" style="margin-right:5px"
onClick="disablewifestatus()"/>
  ****
 <input type="radio" name="gotmarried" id="gotmarried2" value="****" style="margin-right:5px"
onClick="enablewifestatus()"/>
  *****
 ( 	  <input type="radio" name="wifestatus" id="wifestatus1" value="******" style="margin-right:5px"/>
   ****
 <input type="radio" name="wifestatus" id="wifestatus2" value="*****" style="margin-right:5px"/>
  *****
 <input type="radio" name="wifestatus" id="wifestatus3" value="****" style="margin-right:5px"/>
  *****   	   )

I'm using Joomla so sending process will be like this
$row->gotmarried = $_POST['gotmarried'];
 $row->wifestatus = $_POST['wifestatus'];

How can I change the value of a form input and save it into the database?
Comment: You need to provide us with more relevant code, specifically: code that adds a row to the database and part of the HTML showing "wifestatus"
Comment: @Alex I edited my answer
Comment: are you trying to change the status of a radio button to selected?
Comment: what do you mean "if yes"? I am trying to understand what you are asking.
Answer: You should use getElementById, not getElement(s)ById
Furthermore, when you getElements by some selector, it doesn't just return that element(s) it returns an array like object that you would need to loop through to change values on.
http://jsfiddle.net/vhuumox0/17/
Comment: Sir, it's work only with input field but when I send it to the database it will send blank value.

Changing a form value when submitting


Make just one slide different size in Powerpoint

Question: Making a powerpoint that's supposed to show a before and after of a website.  Since it's currently a long website I'd rather make a single long slide to put it on (20" instead of 7.5").  But all the other slides in the presentation should be normal-sized.
I found Slide Size (Design ribbon, Customize section) but that resizes ALL slides.
Answer: You can't.  You can only have one slide size and one orientation per presentation.
Are you projecting the presentation or delivering it on a laptop?
If so, the size is sort of irrelevant.
Regardless of the slide size, the projected/displayed image will never be longer or wider than the projector/display accepts.
Answer: Although you cannot use different sized slides in one PowerPoint file, for the actual presentation you can link several different files together to create a presentation that has different slide sizes.
The process to do so is as follows:

Create the two Powerpoints (with your desired slide dimensions)

They need to be properly filled in to have linkable objects and selectable slides

Select an object in the main PowerPoint to act as the hyperlink
Go to "Insert -> Links -> Action"
Select either the "Mouse Click" or the "Mouse Over" tab
Select "Hyperlink to:" and in the drop down menu choose "other PowerPoint Presentation"
Select the slide that you want to link to.

Any slide that isn't empty should appear in the "Hyperlink to Slide" dialog box

Repeat the Process in the second Presentation to link back to your main presentation

Reference to Office Support Page where this solution was first posted.
https://support.office.com/en-us/article/can-i-use-portrait-and-landscape-slide-orientation-in-the-same-presentation-d8c21781-1fb6-4406-bcd6-25cfac37b5d6?ocmsassetID=HA010099556&CorrelationId=1ac4e97f-bfe6-47b1-bab6-5783e78d126d&ui=en-US&rs=en-US&ad=US
Answer: True you can't have different sized slides.  NOT true the size of you slide doesn't matter.  It will size it to your resolution, but you can click on the magnifying icon(at least on PP 2013) and you can then scroll in all directions of your slide in original resolution.
Comment: I wonder if 2016 behaves differently; I set up two slides, one the standard 16:9 (13.333 x 7.5) the other double that size.  Zoom during slide show gives me the same results in each.
Comment: I can't see that 2016 does anything differently; in the resize dialog box I saw a "Number slides from" option and I hoped that was a poorly implemented and named option to begin slide resizing from a particular slide number... that's not the case - resizing then occurred to all slides in the Presentation.
Answer: if you want to shrink one slide for instance, add shapes to hide the unwanted background margins. you can set the shape color filling as the background (gray or black).
It's "ugly" but it works
Answer: true, this option is not available in any version of MS ppt.Now the solution is that You put your different sized slide in other file and put a hyperlink in first file.


How to edit lightdm.conf file

Question: I tried to activate numlock in the login screen using numlockx. The instruction point me to add this line
greeter-setup-script=/usr/bin/numlockx on

to this file
 /etc/init/lightdm.conf

I tried to reboot. In the boot screen this line was shown.
ERROR: File /etc/init/lightdm.conf: syntax invalid:
init:lightdm.conf:62: Unknown stanza

Which means the added line. What should I do?
Comment: What is the source of your instructions? A link would help.
Comment: @Parto: Possibly this question, with a misleading answer, is the source: http://askubuntu.com/questions/450776/how-do-you-set-up-numlockx-at-startup-in-ubuntu-14-04
Comment: @GunnarHjalmarsson You are right about that source.
Answer: Probably you edited the wrong file. I have a feeling that you are supposed to add that line to e.g. /etc/lightdm/lightdm.conf, which should (at least) contain:
[SeatDefaults]
greeter-setup-script=/usr/bin/numlockx on

Optionally you can use a dedicated file, e.g. /etc/lightdm/lightdm.conf.d/numlock.conf, with the same contents.
Comment: There is no file /etc/lightdm/lightdm.conf indeed, but I decided to create that file and add those lines into it. It works. Also thank you for getting rid of that misleading answer.

How to edit lightdm.conf file


Need to read XML files as a stream using BeautifulSoup in Python

Question: I have a dilemma.
I need to read very large XML files from all kinds of sources, so the files are often invalid XML or malformed XML. I still must be able to read the files and extract some info from them. I do need to get tag information, so I need XML parser.
Is it possible to use Beautiful Soup to read the data as a stream instead of the whole file into memory?
I tried to use ElementTree, but I cannot because it chokes on any malformed XML.
If Python is not the best language to use for this project please add your recommendations.
Comment: lxml has a stream api, you can check the documentations here: https://lxml.de/3.6/parsing.html#incremental-event-parsing
Answer: Beautiful Soup has no streaming API that I know of. You have, however, alternatives.
The classic approach for parsing large XML streams is using an event-oriented parser, namely SAX. In python, xml.sax.xmlreader. It will not choke with malformed XML. You can avoid erroneous portions of the file and extract information from the rest.
SAX, however, is low-level and a bit rough around the edges. In the context of python, it feels terrible.
The xml.etree.cElementTree implementation, on the other hand, has a much nicer interface, is  pretty fast, and can handle streaming through the iterparse() method.
ElementTree is superior, if you can find a way to manage the errors.


Is OAuth2 Password grant type and client_credential grant types the same?

Question: As I understand before messing with Laravel Passport, password grant type is resource owner type and client_credential is for first party app, so basically routes protected with client_credential can access with token issues by itself,
My problem is token issued from password grant type can access routes protected by client_credential, and routes protected by api:auth can't be access by client_credential token
Answer: These are two different flow types.
First you need to understand the different between client and resource owner. This is explained clearly on roles section of the protocol.

resource server
The server hosting the protected resources, capable of accepting and
responding to protected resource requests using access tokens.
client
An application making protected resource requests on behalf of the
resource owner and with its authorization.

Now, the flows you have mentioned use credentials from resource owner and client. The clients in client credential flow are confidential clients. That means they have a client secret with them.
In resource owner password grant, you obtain tokens from token endpoint by presenting resource owner credentials. For client credential grant type, you obtain tokens from token endpoint by presenting client credentials. So as you can see they are two different flows.
Depending on the implementation, tokens issued for these flows could have different scopes. That mean, those tokens may have a different validity or could have limitations. Such restrictions are independent of OAuth 2.0 protocol.
Comment: oh I got it, your point is token issued by Password grant type is belong to both owner and client, that's why the token can access endpoints protected by `client` and `api:auth`.


Determine if a command has been finished executing in CMD in C#

Question: Introduction
I am creating a R.A.T (Remote Administration Tool) In c# with TCP client-server configurations.
Everything was going quite fine until I realized a need to detect whether or not a command has been finished executing in a command-prompt process created by my c# application.
Please have a look at the code below.
private static Process CMDProc = null;
private static StreamWriter ToCMDShell = null;

public static void StartCMD()
{
       ProcessStartInfo PSInfo = new ProcessStartInfo
       {
             FileName = "cmd.exe",
             CreateNoWindow = true,
             UseShellExecute = false,
             RedirectStandardInput = true,
             RedirectStandardOutput = true,
             RedirectStandardError = true
       };

       CMDProc = new Process { StartInfo = PSInfo };
       CMDProc.Start();
       ToCMDShell = CMDProc.StandardInput;
       ToCMDShell.AutoFlush = true;
       CMDProc.BeginOutputReadLine();
       CMDProc.BeginErrorReadLine();
       CMDProc.OutputDataReceived += (s, e) => { /*Do something with e.Data*/ };
       CMDProc.ErrorDataReceived += (s, e) => { /*Do something with e.Data*/ };
       ToCMDShell.WriteLineAsync("ping 220.127.116.11"); //Execute a long running command in cmd terminal.
}

What I Want To Achieve
As you may guess that ping command takes variable amount of time to complete depending upon the speed of the internet connection, now what I want is to run a method called CMDCommandExecuted() when a long running command like "ping" finished executing in the terminal which was invoked using the c# code ToCMDShell.WriteLineAsync("any dos command to execute");.
What I Had Tried Till Now
I tried to read the e.Data from the output stream received from the CMDProc.OutputDataReceived Event-Handler but had no luck, because maybe for some other long running commands other than the ping no data at all is being written to the output stream so it is not a bulletproof solution.
And yes I had tried to search for my solutions on the internet as well, yet no luck!
That's why I am here seeking for your help.
Comment: Have you thought about executing the DOS command directly without the Command Shell first? The result should be that you can then use `WaitForExit` when the command finished.
Comment: It's usually best to invoke functionality directly within your own process rather than launching a different process to do it - and here you're doing it twice indirectly, by running a `cmd` process just to get `ping` running. In that example, far better to use [Ping](https://learn.microsoft.com/en-us/dotnet/api/system.net.networkinformation.ping?view=net-5.0) directly.
Comment: Best way is to send a response back when command is completed.  A command in windows normally terminates when completed and closed the Input and Output Stream so testing for the streams close (WaitUntilExit).  Running Async you have no method of knowing when the process completes unless you query all the processes to see if it is still running.
Comment: If you need to run the Command Shell first, you can use the `/C` switch to have the shell exit after it run. See [CMD.exe](https://ss64.com/nt/cmd.html) for more info
Comment: When I run your code with an `OutputDataReceived` event handler, I get the command prompt followed by a `null` when the ping finishes. Can you watch for the command prompt?
Comment: Further testing seem to indicate prompt showing up is inconsistent but can be triggered with an additional `WriteLineAsync("")`
Comment: I wrote a complicated answer, but it seems like putting `await` in front of the `WriteLineAsync` is sufficient to wait until the command finishes, so if you don't mind pausing while the command runs...
Answer: Use CMDProc.WaitForExit() to wait for completion and CMDProc.ExitCode to get final status code.
If you get some data from the stream that indicates the process is hung or frozen or needs to be killed, call CMDProc.Kill().
If you get some data from the stream that indicates you should do something else, you can spawn other processes or send additional WriteLine calls to the process to do further processing.
The following program sends the ping command output back to me correctly. Maybe you just need that wait command or a console read line to give it time.
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace MyNamespace
{
    class Program
    {
        private static Process CMDProc = null;
        private static StreamWriter ToCMDShell = null;

        public static void Main()
        {
            StartCMD();
        }

        public static void StartCMD()
        {
            ProcessStartInfo PSInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };

            CMDProc = new Process { StartInfo = PSInfo };
            CMDProc.Start();
            ToCMDShell = CMDProc.StandardInput;
            ToCMDShell.AutoFlush = true;
            CMDProc.BeginOutputReadLine();
            CMDProc.BeginErrorReadLine();
            CMDProc.OutputDataReceived += (s, e) =>
            {
                Console.WriteLine("PROC: {0}", e.Data);
                if (e.Data != null && e.Data.Contains("Average ="))
                {
                    // last line, you don't have to exit here, you could do something else instead...
                    ToCMDShell.WriteLine("exit");
                }
            };
            CMDProc.ErrorDataReceived += (s, e) => Console.WriteLine("PROC ERR: {0}", e.Data);
            ToCMDShell.WriteLine("ping 126.96.36.199"); //Execute a long running command in cmd terminal.
            CMDProc.WaitForExit();
            Console.WriteLine("Job done, press ENTER to quit");
            Console.ReadLine();
        }
    }
}

Comment: Will `CMDProc.WaitForExit()` kills the running cmd terminal? Or will it only waits till the specific command is executed?
Comment: It will only wait for the external process. Current process will remain intact, even if you kill the attached process.
Comment: In your case, you spawned a cmd.exe command so it will never exit unless you send it an exit command or forcefully kill it.
Comment: I don't want to kill the CMDProc at all. Is there any alternate solution available?
Comment: You don't have to kill it. You can leave it running and continue to call WriteLine on it. I updated the example to send an exit command conditionally based on some text coming back, in this case the last line of the ping results. You could do something else besides sending the exit command if you like.
Comment: Will `WaitForExit()` blocks the current thread?
Comment: Of course. You can use `HasExited` to check if the process is ended without blocking.
Comment: This is not what I actually need, In fact `WaitForExit()` is blocking my thread forever and `Console.WriteLine("Job done, press ENTER to quit")` is not getting fired. I had removed `ToCMDShell.WriteLine("exit")` since I don't need that process to terminate. Any idea why is this happening?
Answer: It appears that the WriteLineAsync doesn't complete until the long running command does (e.g. the command window is ready for new input), so you just need to Wait on the return from WriteLineAsync when you need to send more data, or know the previous command is done.
private static Process CMDProc = null;
private static StreamWriter ToCMDShell = null;

public static void StartCMD() {
    ProcessStartInfo PSInfo = new ProcessStartInfo {
        FileName = "cmd.exe",
        Arguments = "/k",
        CreateNoWindow = false,
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true
    };

    CMDProc = new Process { StartInfo = PSInfo };
    CMDProc.Start();
    ToCMDShell = CMDProc.StandardInput;
    ToCMDShell.AutoFlush = true;
    CMDProc.BeginOutputReadLine();
    CMDProc.BeginErrorReadLine();
    CMDProc.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
    CMDProc.ErrorDataReceived += (s, e) => Console.WriteLine($"ERR: {e.Data}");

    var run = ToCMDShell.WriteLineAsync("ping 18.104.22.168"); //Execute a long running command in cmd terminal.
    // do some stuff
    run.Wait(); // wait for long command to complete
    ToCMDShell.WriteLine("exit"); //Done
}


Installing on a mac without a CD burner or USB boot

Question: I am new to Ubuntu, i installed it in an old PC and now it works GREAT!!! My Macbook pro has a glitch and refuses to run Mac OS X, so i installed Windows, and i really want Ubuntu since Windows is not for me. Here's the problem(s) my drive only READS DVDs, if i put a blank in it, it will ignore it and my mac has the updated EFI, so no booting from a USB connected device! I also tried Wubi, but then i cant make it a FULL partition and get rid of windows!!! Thank you!
Answer: If I understand, you want to download a new version of Ubuntu and put it on some media and boot from that media to install it to the whole disk on your Mac OS system. You are constrained in that the media you can write to you can't boot from and you can boot from the CD/DVD drive but have no means of writing one. Further, I assume you can't write a CD from that old PC running Ubuntu.
If all of that is correct, I can see three choices. (If it's not correct, please correct me by editing your question).

Buy an Ubuntu 12.04 CD. Canonical has them here . At one time Canonical would give away single CD's on request but I don't see that on the Get Ubuntu part of the Ubuntu site anymore. The cost is about five pounds.
Get an Ubuntu CD from your LOCO (or maybe one nearby). If it's inconvenient to meet with LOCO members perhaps someone would mail you a CD. LOCO's are Ubuntu Local Community Teams. You can find LOCO's starting from here. A LOCO near me always seems to have extra CD's they give away. A LOCO is a good alternative for getting help and advice too. This would be my choice if I were in your situation.
In France, for example, please see this site.
As a final alternative, if you still have the old CD you used to install Ubuntu on that old PC, perhaps you could install from that CD onto your Mac, and then upgrade the system to 12.04. If you installed from USB, however, I see from your question that USB booting won't work.
Comment: Thank you very much for your answer! Is LOCO available in France? Again, thank you for your help! Best wishes!
Comment: De rien. I've updated the answer with the French LOCO team's web site.


unknown error from cudaGetErrorString(err)

Question: I get unknown error when I call cudaMemcpy in cudaT.h.
When I compile I get this warning, repeated multiple times at line 46, 50, 52:

./gameoflife.cu(46): Warning: Cannot tell what pointer points to, assuming global memory space

main.cu
<code>#include "gameoflife.cu"

#include <iostream>

using namespace std;

#define DIM 20

__global__ void Func(CudaMem<GameOfLife<DIM, DIM> > * golDevice)
{
    golDevice->m_t->Step();
}

int main()
{
    GameOfLife<DIM, DIM> golHost;

    golHost.CreateCell(3,3);
    golHost.CreateCell(4,3);
    golHost.CreateCell(5,3);
    golHost.CreateCell(5,2);
    golHost.CreateCell(4,1);

    golHost.CreateCell(1,7);
    golHost.CreateCell(2,7);
    golHost.CreateCell(3,7);

    cout << golHost << endl;

    CudaMem<GameOfLife<DIM, DIM> > golDevice;
//  GameOfLife<DIM, DIM>* golDevice;
//  cudaMalloc((void **)&golDevice, sizeof(GameOfLife<DIM, DIM>));

    CudaMem<GameOfLife<DIM, DIM> >::CudaMemcpyHostToDevice(golDevice, &golHost);
//  cudaMemcpy(golDevice, &golHost, sizeof(GameOfLife<DIM, DIM>), cudaMemcpyHostToDevice);

    for(int i = 0 ; i < 1 ; ++i)
    {

//      cout << "Press anykey to exit.";
//      cin.ignore();
//      cin.get();

        Func<<<DIM, DIM>>>(&golDevice);

        CudaMem<GameOfLife<DIM, DIM> >::CudaMemcpyDeviceToHost(golDevice, &golHost);
//      cudaMemcpy(&golHost, golDevice, sizeof(GameOfLife<DIM, DIM>), cudaMemcpyDeviceToHost);

        cout << golHost << endl;

    }

//  cudaFree(golDevice);

    cudaDeviceReset();

}
</code>
gameoflife.cu
<code>#include <cuda_runtime.h>
#include "cudaT.h"
#include <cstddef>
#include <iostream>

using namespace std;

template<size_t ROWS, size_t COLUMNS>
class GameOfLife
{
public:
    __host__ GameOfLife()
    {
        memset(m_dots, 0, sizeof(m_dots));
        memset(m_dots, 0, sizeof(m_temp));
    }

    __host__ __device__ ~GameOfLife()
    {

    }

    __host__ void CreateCell(size_t _row, size_t _column)
    {
        // need to check overflow
        m_dots[_row + 1][_column + 1] = 1;
    }

    __host__ void KillCell(size_t _row, size_t _column)
    {
        // need to check overflow
        m_dots[_row + 1][_column + 1] = 0;
    }

    __device__ void Step()
    {
        int liveNeighbours = 0;

        if(threadIdx.x > ROWS || blockIdx.x > COLUMNS )
        {
            return;
        }

        m_temp[threadIdx.x + 1][blockIdx.x + 1] = m_dots[threadIdx.x + 1][blockIdx.x + 1];

        __syncthreads();

        liveNeighbours = CalcLiveNeighbours() % 9;

        m_dots[threadIdx.x + 1][blockIdx.x + 1] = ( m_temp[threadIdx.x + 1][blockIdx.x + 1] && (liveNeighbours > 1 && liveNeighbours < 4) )
        || ( !m_temp[threadIdx.x + 1][blockIdx.x + 1] && liveNeighbours == 3) ;

    }

    template<size_t R, size_t C>
    __host__ friend ostream& operator<<(ostream& os, GameOfLife<R, C>& gol);

private:
    __device__ __host__ GameOfLife(const GameOfLife& other);

    __device__ int CalcLiveNeighbours()
    {
        return  m_temp[threadIdx.x + 0][blockIdx.x + 0] +
                m_temp[threadIdx.x + 0][blockIdx.x + 1] +
                m_temp[threadIdx.x + 0][blockIdx.x + 2] +
                m_temp[threadIdx.x + 1][blockIdx.x + 0] +
                m_temp[threadIdx.x + 1][blockIdx.x + 2] +
                m_temp[threadIdx.x + 2][blockIdx.x + 0] +
                m_temp[threadIdx.x + 2][blockIdx.x + 1] +
                m_temp[threadIdx.x + 2][blockIdx.x + 2]
        ;
    }

    int m_temp[ROWS + 2][COLUMNS + 2];
    int m_dots[ROWS + 2][COLUMNS + 2];
};

template<size_t R, size_t C>
__host__ ostream& operator<<(ostream& os, GameOfLife<R, C>& gol)
{
    for(int i = 1 ; i < (R+1) ; ++i)
    {
        for(int j = 1 ; j < (C+1) ; ++j)
        {
            os << gol.m_dots[i][j] << " ";
        }
        os << endl;
    }

    return os;
}
</code>
cudaT.h
<code>#pragma once

#include "cuda.h"
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <assert.h>

#include "cudaException.h"

#include <iostream>
using namespace std;

template<typename T>
class CudaMem
{
public:

    CudaMem():m_t(0)
    {
        cudaError_t err = cudaSuccess;
        err = cudaMalloc((void **)&m_t, sizeof(T));

        if (err != cudaSuccess)
        {
            throw CudaException(err);
        }

    }

    // CudaMem(T& copyFrom):m_t(0)

    explicit CudaMem(const CudaMem<T>& other):m_t(0)
    {
        cout << "CudaMem copy ctor" << endl;
        cudaError_t err = cudaSuccess;

        err = cudaMalloc((void **)&m_t, sizeof(T));

        if (err != cudaSuccess)
        {
            throw CudaException(err);
        }
        // need to copy the memory
    }

    static void CudaMemcpyHostToDevice(CudaMem<T>& _deviceMem, T* _hostMem)
    {
        cudaError_t err = cudaSuccess;

        err = cudaMemcpy(_deviceMem.m_t, _hostMem, sizeof(T), cudaMemcpyHostToDevice);

        if(err != cudaSuccess)
        {
            throw CudaException(err);
        }
    }

    static void CudaMemcpyDeviceToHost(CudaMem<T>& _deviceMem, T* _hostMem)
    {
        cudaError_t err = cudaSuccess;
        err = cudaMemcpy(_hostMem, _deviceMem.m_t, sizeof(T), cudaMemcpyDeviceToHost);

        if (err != cudaSuccess)
        {
            throw CudaException(err);
        }
    }

    ~CudaMem()
    {
        cout << "CudaMem dtor" << endl;
        cudaFree(m_t);
    }

    const T* Get()
    {
        return m_t;
    }

    operator void*()
    {
        return m_t;
    }

    operator T*()
    {
        return m_t;
    }

    T* operator->()
    {
        return m_t;
    }

    T* const m_t;
private:

};
</code>
cudaException.h
<code>#pragma once

#include <string>
#include <sstream>

#include "cuda.h"
#include "cuda_runtime.h"
#include "device_launch_parameters.h"

using std::string;
using std::stringstream;

class CudaException : public std::exception
{
public:
    CudaException(cudaError_t _err):m_str(cudaGetErrorString(_err))
    {

    }

    CudaException(cudaError_t _err, string _file, int _line):m_str(cudaGetErrorString(_err))
    {
        string s;
        stringstream out;
        out << _line;
        s = out.str();
        m_str += " At file: " + _file + " At line: " + s;
    }

    virtual const char* what() const throw ()
    {
        return m_str.c_str();
    }

    virtual ~CudaException() throw (){}

private:
    string m_str;
};
</code>
Generally what I'm trying to do is to wrap the cudaMalloc\cudaFree in a class.
When I'm not using this class CudaMem everything is working just fine.
Comment: There is far to much code here and no obvious question. Nobody here is going to debug a few hundred lines of code for you. You haven't explained *where* the error is occuring or how you are building to code, your cuda version, platform or just about anything else. Having said that, this:  `Func<<>>(&golDevice);` is almost certainly wrong. That is passing a host pointer to the kernel.
Comment: Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). BTW, it's "Thanks in advance", not "Thanks in advanced".
Comment: Thanks that was the problem, I just needed someone else to look at this code, cause I didn't know what to look for which make question not specific.
Comment: Please write a short answer with your solution to your problem and add it as an answer to this question (that is perfectly OK). You can later accept this answer, and it will get the question off the unanswered list and make it easier to find in search for the next person with a similar problem.
Answer: The problem was with this function call :
<code>Func<<<DIM, DIM>>>(&golDevice);
</code>
Which I sent a host memory pointer and not a device memory pointer.


TypeError: Cannot read property 'map' of undefined Nextjs?

Question: Cannot read property 'map' of undefined i don't know how to solve i am new to react please help me for this code
  {rooms && rooms.length === 0 ? (

            No Rooms

        ) : (
          rooms.map((room) => <RoomItem key={room._id} room={room} />)
        )}

Comment: Try ```rooms?.map```, because ```rooms``` isn't an array when rendered for the first time, that's my guess..
Answer: Let's reverse that logic.
If rooms is defined and it's length is greater than 0, then render rooms.
Else, render "No Rooms"
{
  rooms?.length > 0 ? (
    rooms.map((room) => <RoomItem key={room._id} room={room} />)
  ) : (

      No Rooms

  );
}

Answer: Add first:
{if(! rooms) return}
Answer: Break the code down to its basics and you have:
if (rooms && rooms.length === 0)
  return "No Rooms";
else
  return rooms.map(room => room.id);

When rooms is undefined, && short-circuits (i.e., the second operand is skipped if first is falsey), the code is now equivalent to:
if (undefined) return "No Rooms"
else return undefined.map(/*...*/)

This is why you're getting the "cannot read property map of undefined" error. I suspect you just added rooms&& as you were getting "cannot read property length of undefined" initially. You should try to always put the 'backup case' in the else-block to avoid this issue.
Fix it by reversing the check:
rooms && rooms.length > 0 ? (
 // rooms.map ...
) : (
 // No Rooms ...
)


How to pass data back to the first view controller in Swift?

Question: I have two view controllers and I have this code to navigate between the  two views
ViewController:
func goToSecondViewController() {
  let aa = self.storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController
  self.navigationController.pushViewController(aa, animated: true)
}

/
SecondViewController:
func goToFirstViewController() {
  self.navigationController.popToRootViewControllerAnimated(true)
}

How to send some data to the first view before popping it ?
Answer: If A is a view controller with the following declaration:
class A : UIViewController {
   var data: String!
}

Then, whenever you have an instance of A, you can just set the data property directly:
let a = A() // assuming you've defined the init method
a.data = "hello"

Edit
If you want to send data before popping, you'd do something like:
func goToFirstViewController() {
  let a = self.navigationController.viewControllers.first as! A
  a.data = "data"
  self.navigationController.popToRootViewControllerAnimated(true)
}

(haven't compiled the above)
Comment: hello
it shows compilation error on ((firstObject))
" '[AnyObject]' does not have a member named 'firstObject' "
Comment: `let a = self.navigationController.viewControllers.first as! A`
Comment: I am doing exactly same that you have done but I am calling `self.navigationController.popViewControllerAnimated(true)` instead of `popToRoot` what shold i do that


Fastest way to level up in Modern Warfare 2 / Black Ops

Question: What is the quickest way that you have found to level up in MW2?
EDIT: I've been playing a lot of Hardcore CTF lately with friends... this has been getting me a lot of XP... we would just hold the flag and play for a draw the first 2 rounds and cap in the 3rd round if possible...
i'd say 8k up to 25k xp per round..
Answer: I would say avoid big games especially Ground War. It seems it's easier to get kills because there's more people but in fact it's a lot harder to get high kill streak because of bigger chance of getting killed.
Do learn the maps as fast as you can so you can easily pick good spots and avoid those from where you can get killed from easily. Watch killcams for that (as was suggested in the answer to another question).
Unlock challenges for the same gun to get optimal performance out of it. Almost every gun (at least from assault rifles) can be configured to be effective.
Lastly, try to play stealth to avoid many deaths and therefore build higher streaks. Use silencer, Ninja and Cold Blooded for that.
Comment: Worth mentioning that if you're having a hard time playing on any given day, it's prudent to equip low killstreak rewards, rather than the higher ones which tend to make you even more frustrated.
Comment: Also note the cold blooded bug: if you shoot down a pavelow or any other kill streak that starts spiraling after it dies, every bullet you put into it after that counts as a cold blooded 'kill'.  Its an easy way to get cold blooded pro and a bunch of experience.  Also, if you really want a speed run, try to complete as many achievements as possible (unless you are the kinda person who can use one and only one gun in which case stick with your favorite gun)
Answer: I actually recommend playing Ground War, especially Domination.  You can rack up some serious points will capturing the flag point and kills.  A good strategy would be to spawn trap the opposing team.  You can accomplish this by letting them hold one flag and they will spawn around that point.  The AC-130 is great for spawn trapping.
Headquarters Pro is also another game type where you can rack up experience points.  You get +10 for every 5 seconds you hold the HQ, but you do not respawn if you die during the time.  You will have to wait until the other team destorys the HQ.
The last game type you can play is Search and Destory.  You get serious experience points for kills and destorying the target.  I personally do not like this game mode, I find it boring.
Comment: Also, maximize your playing time during double xp weekends.
Answer: A decent way to get easy points is setting up a SAM turret in Ground War. Just set it up somewhere and wait for it to shoot things down.
Answer: I found that I got the most experience per minute played in Demolition.
Answer: I hear that Headquarters Pro is supposed to be good for earning XP quickly.
Answer: Headquarters Pro is great since it's fast to gain points by capping or defending, and since enemies will always target the area you're defending. I'd avoid any type of deathmatch or free-for-all since the only way to get points is to call in killstreaks or kill players.
Answer: Definitely Search and Destroy. You get 500 XP per kill and 1000 for planting/defusing the bomb.
Comment: You do however respawn only once. Therefore, if you aren't a pro then you'll have a hard time scoring at all.
Answer: In Black Ops you could check your Score Per Minute by game type statistics page. It would give you some clues about what works best for your play style.
Answer: In Black Ops (on the PC at least), I've found it's pretty easy to grind on one of the many available 24/7 Nuketown servers. Throw 18 people onto a tiny map like that and, well...
Points. They happen.


UX deliverables for UI/visual design outsourcing

Question: I have been working on a mobile application design: conducted the user research, designed and iterated the wireframes, and did a clickable prototype of the app. Now we need to do the UI + visual design of the application, and we're outsourcing it to external agency (the development is done by other vendor). I wonder what should I deliver to them 1) For them to understand the scope of work and give me a timeframe estimate 2) The full package needed for them to do their job.
I think that the app description + wireframes + interactive prototypes + scope of work (what exactly needs to be delivered) are enough to understand the amount of work, while for the total work I can supply them with personas, user stories and use cases (user journey not relevant in this case. Is there anything else that may be needed for the two phases?
Comment: Sounds about right. If you have any branding guides, give that as well along with any predetermined things like fonts and icon sets. If there are none, it'll add some time for them.
Answer: The main thing to keep in mind, when you outsource a job, is to make sure that it doesn't become obvious that you had the job outsourced to an external or third party group for development. Having said this, what can you do to make sure your product, even with the fact that it was outsourced for development, looks like an original product that reflects you or your company?

Make sure you make the outsourced team feel like they work for you and your company, and isn't a completely different organization. This means that you must treat them as your own employees.
Make your company policies and visions perfectly clear to them. Give them a complete overview what your company does, what you guys are expected to do, and what is the standard of work that is generally delivered.
Do not give them the impression that once you outsource the work, your work is done. You need to continuously collaborate with them. This, not only ensures flawless work, but also maintains a high morale for the team.
Provide them with all that they might need. This includes the complete wireframes, user stories, click-throughs, prototypes, as well as a high-level or a user overview of what your application or product is supposed to do, in non-technical terms. Also give them the correct font families, images, icons, color themes and other standards.
Give them properly evaluated estimate. Make sure you estimate with a little buffer time, but make sure you do not give them lax time.
Your user stories and user journeys should be crystal clear. This should not change amidst the development. This maybe very difficult for them to incorporate in between development.
Always make sure that you or your team is always available to them, in case they have doubts (which they will, naturally).

Always remember, you are the clients of your outsourced team. So you have to treat them exactly the way you want your clients to treat you. This includes a proper morale, a good chemistry and proper availability of resources.


Prometheus inhibit alert selectively

Question: I need to create an alerting system that has to notify when a particular condition (e.g. Tomcat goes down) is met.
Multiple remote servers deployed in different locations (with different time zones) host Tomcat services and are being monitored by Prometheus.
I need to receive the alert only from 8:05 to 22:45 local time so I proceed as follow:

Defined a custom rule "check_system_time_in_interval" that returns 1 if the server local time is in [8:05,22:45], 0 otherwise
Used rule 1) to define an alert Inhibit alert during NO working hours in "prometheus.rule.yml":

<code>- name: quite_hours
  rules:
    - alert: Inhibit alert during NO working hours
      expr: check_system_time_in_interval==0
      labels:
        notification: none
        severity: critical
</code>

Defined a new inhibit_rule in "alertmanager.yml" file that inhibits the alert TOMCAT down (fires alert when TOMCAT service is out of service) when the monitored server time is not in the interval

<code>inhibit_rules:
- source_match:
    alertname: Inhibit alert during NO working hours
  target_match_re:
    alertname: (TOMCAT down)
</code>
TOMCAT down uses a custom rule "tomcat_up" that checks if Tomcat is up or not.
Now it seems to work quite properly but with this approach I would have problems due to time zones: I need to be notified if the LOCAL time of the monitored server is in [8:05,22:45] even if Prometheus server is located to different time zone.
One simple solution would be to inhibit the alert only if the 'instance' label of check_system_time_in_interval time series is equals to 'instance' label of TOMCAT down (e.g. if check_system_time_in_interval{instance="10.41.0.118"}=0 and tomcat_up{instance="10.41.0.118}=1" then fire an alert) but I don't know how to modify "inhibit_rule" in order to do that.
Answer: After a while, I came up with a trivial solution: adding a new label "timezone" and inhibit an alert only if "timezone" labels match.
Comment: I think you can also avoid the additional tz metric by using Prometheus time functions. Similar to: https://stackoverflow.com/questions/69717672/time-based-alerts-in-prometheus-alertmanager/69719774#69719774

Prometheus inhibit alert selectively


Calculating time difference between 2 dates in Teradata

Question: I'm trying to calculate time difference (in months) between the current date, and the date the customer opened his account (only for those who joined in January 2012).
I try to use current_date and cast, but I think my problem is in my date field which is in the following format: dd/mm/yyyy
I'm working on Teradata.
Your help will be appreciated.
Comment: can you show us the query you actually did? the code itself, that'd be helpful for us to help you
Comment: My code is: **SELECT CURRENT_DATE-CAST(startDate) FROM myTable WHERE startDate BETWEEN 1120101 AND 1120131
Answer: You can try like this:
SELECT CURRENT_DATE - CAST('2016-06-06' AS DATE) MONTH(4);

and if your date is in dd/mm/yyyy format then you can try like
SELECT CURRENT_DATE - cast(myDate as date format 'YYYY-MM-DD') MONTH(4);

Comment: What is the significance of adding month(4) at the end? Can you share some reference?


Removing the shadow which comes below a tab layout in android. [done]

Question: I am curious to know if there is anyway I can remove OR change the drop-shadow like effect that android gives below a Tab layout.
Answer: As soon as I ask this question, I get the answer in another stackoverflow post. Anyways for the benefit of people who have landed on this post, the answer is to
use a custom theme with its windowContentOverlay set to null
Comment: @null  not working for me on Android lollipop versions


Does breaking a demon altar work with artificial ore veins?

Question: Lets say in Terraria you were to mine out every ore block in the world, then break two demon altars in hard mode, put all back down in one large vein would it all change to titanium/adamantium? Or does the game keep track of which ores have been mined and which ones were placed?
Comment: Hardmode ore generation doesn't convert existing deposits to the new ore type, it spawns new ore veins, overwriting any blocks that were previously present
Comment: @JonK I believe that qualifies as an answer. It may require just a bit more info.
Comment: @Zerjack I've been trying to find a source for that but I'm not finding any. Not sure I could authoritatively say how it *does* work, though experience tells me how it *doesn't* work. I'll cobble that into an answer somehow
Answer: Hardmode ore generation doesn't work that way, it doesn't replace existing ore veins with the new hardmode ore deposits. Hardmode ore can definitely spawn in some placed blocks (I'm unsure about if it can spawn in Bricks, but player placed Stone, Ash, etc... work fine).
The best way to think of the ore generation is that the new veins replace existing blocks (i.e. it cannot create new blocks where there are none), rather than existing types of blocks. If you were to dig up the entire world and just pop down one large deposit of ore, you'd get very little hardmode ore out of it, as there wouldn't be many places for that ore to spawn.
I actually tested this out on an old world to be certain (I deleted all terrain in a hardmode world and then created a block about 128x128 of Gold Ore, stuck a Demon Altar on top of it then went in game and smashed it - almost no ore spawned), you'd end up with a tiny amount of hardmore ore, if any at all.
Edit: Actually in my test world no ore spawned at all. Seems as though it doesn't overwrite existing ores, just 'junk' blocks like stone.
Further edit: Ore does spawn when I use Ash blocks as a base instead of an ore, however it lags horribly while (presumably) it's trying to find valid locations to spawn the ores, and you don't get much of it when it does spawn.
Comment: Huh that's actually a pretty interesting test. I'm sure the wiki or the wikia would love to have those experiment results in their notes about hardmode ores.
Comment: Thanks soooo much with this I'm not good with knowing the terrain gen and stuff.


difference in logging mechanism: API and application(python)

Question: I am currently writing an API and an application which uses the API. I have gotten suggestions from people stating that I should perform logging using handlers in the application and use a "logger" object for logging from the API.
In light of the advice I received above, is the following implementation correct?
class test:
    def __init__(self, verbose):
        self.logger = logging.getLogger("test")
        self.logger.setLevel(verbose)

    def do_something(self):
        # do something
        self.logger.log("something")
        # by doing this i get the error message "No handlers could be found for logger "test"

The implementation i had in mind was as follows:
 #!/usr/bin/python

 """
 ....
 ....
 create a logger with a handler
 ....
 ....

 """

 myobject = test()
 try:
     myobject.do_something()
 except SomeError:
     logger.log("cant do something")

I'd like to get my basics strong, I'd be grateful for any help and suggestions for code you might recommend I look up.
Thanks!
Comment: I like the question, is there a tutorial which shows exactly what kind of patterns to follow while using logging?
Answer: It's not very clear whether your question is about the specifics of how to use logging or about logging exceptions, but if the latter, I would agree with Adam Crossland that log-and-swallow is a pattern to be avoided.
In terms of the mechanics of logging, I would make the following observations:

You don't need to have a logger as an instance member. It's more natural to declare loggers at module level using logger = logging.getLogger(__name__), and this will also work as expected in sub-packages.
Your call logger.log("message") would likely fail anyway because the log method has a level as the first argument, rather than a message.

You should declare handlers, and if your usage scenario is fairly simple you can do this in your main method or if __name__ == '__main__': clause by adding for example
logging.basicConfig(filename='/tmp/myapp.log', level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(name)s %(message)s')

and then elsewhere in your code, just do for example
import logging
logger = logging.getLogger(__name__)

once at the top of each module where you want to use logging, and then
logger.debug('message with %s', 'arguments') # or .info, .warning, .error etc.

in your code wherever needed.
Answer: The danger with the pattern that you are thinking about is that you may end up effectively hiding exceptions by putting them in a log. Many exceptions really should crash your program because they represent a problem that needs to be fixed. Generally, it is more useful to be able to step into code with a debugger to find out what caused the exception.
If there are cases that an exception represents an expected condition that does not affect the stability of the app or the correctness of its behavior, doing nothing but writing a notation to the log is OK. But be very, very careful about how you use this.
Answer: I usually do the following:
import logging
import logging.config
logging.config.fileConfig('log.congig')

# for one line log records
G_LOG = logging.getLogger(__name__)
# for records with stacktraces
ST_LOG = logging.getLogger('stacktrace.' + __name__)

try:
    # some code
    G_LOG.info('some message %s %s', param1, param2)
except (StandardError,):
    message = 'some message'
    G_LOG.error(message)
    # exc_info appends stacktrace to the log message
    ST_LOG.error(message, exc_info=True)

Format of the config file can be seen in the python manual


Using a delay in for loop -- Swift

Question: Im trying to make a simple startup application to learn Swift. I am new to programming in general and I am in a little over my head. This bit of code is meant to highlight (change the background color) of a certain UIButton and then change it back. At first I added a delay of 0.5 seconds to each action but then I learned a IBAction only updates once at end of execution?. So I then added the delay to increment each time. The code works for the first 3 or 4 loops but then acts up and does not delay correctly. Please help, Thanks
func SSSays(clicks:Int) {

    sPattern.append(Int(arc4random_uniform(4) + 1))
    var wait = 0.5

    for button in sPattern {

        if(button == 1) {
            wait = wait + 0.5
            self.delay(wait) {self.BBB.backgroundColor = UIColor.init(red: (102/255), green: (178/255), blue: (255/255), alpha: (1))}

            wait = wait + 0.5
            self.delay(wait) { self.BBB.backgroundColor = UIColor.blueColor() }

        } else if(button == 2) {

            wait = wait + 0.5
            self.delay(wait) {self.RBB.backgroundColor = UIColor.init(red: (255/255), green: (153/255), blue: (153/255), alpha: (1))}

            wait = wait + 0.5
            self.delay(wait) {self.RBB.backgroundColor = UIColor.redColor() }

        } else if(button == 3){

            wait = wait + 0.5
            self.delay(wait) {self.GBB.backgroundColor = UIColor.init(red: (153/255), green: (255/255), blue: (204/255), alpha: (1)) }

            wait = wait + 0.5
            self.delay(wait) {self.GBB.backgroundColor = UIColor.greenColor() }

        } else if(button == 4){

            wait = wait + 0.5
            self.delay(wait) {self.OBB.backgroundColor = UIColor.init(red: (255/255), green: (204/255), blue: (255/255), alpha: (1)) }
            wait = wait + 0.5
            self.delay(wait) {self.OBB.backgroundColor = UIColor.magentaColor() }

        }
    }

}

func delay(delay:Double, closure:()->()) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(delay * Double(NSEC_PER_SEC))),dispatch_get_main_queue(), closure)
}

Answer: I suggest you look into animation functions. They were created for this reason and will greatly simplify your code. Here's a basic one that you can play with to get you started:
UIView.animateWithDuration(1.0, delay: 0.0, options: [], animations: {
            self.BBB.backgroundColor = UIColor.redColor()
            }, completion: nil)

Swift 4.0
UIView.animate(withDuration: 1.0, delay: 0.0, options:.allowAnimatedContent, animations: {
                self.BBB.backgroundColor = .red
            }, completion: nil)

You can then add in code for the completion block to handle additional code once that duration of the animation completes if you see fit.
options: [] can take parameters such as Autoreverse, Repeat, etc. to give you additional effects.

Using a delay in for loop -- Swift


How to create custom classes in orientdb using Gremlin

Question: I want the equivalant of this syntax in SQL:
create class Person extends V

in Gremlin
Comment: I'm not sure it is possible to manipulate OrientDB schema through Gremlin. Gremlin is independent on OrientDB and is not adapted on schemas.
Comment: Yeah I suppose that would be the answer. don't you know any way to add a vertex in particular class
Answer: I'm not sure it is possible to manipulate OrientDB schema through Gremlin. Gremlin is independent on OrientDB and is not adapted on schemas because not all of graph databases support schemas.
For adding vertex of particular class in OrientDB you can use Graph API (see doc). If you prepend string class: before the name of the class, you will create a vertex of this class.
graph.addVertex("class:User");

This snippet will create vertex of class User. I hope it will help you.


JQuery checkbox value on check

Question: A multiple number of checkboxes are created on a html page with PHP in the following format:
<input class="check" type="checkbox" name="att[]">

The number of these checkboxes varies depending on other variables, for this reason I have given each one the class "check".
On check of any checkbox, I want its value to be "YES". When a checkbox is not checked, I want it's value to be "No".
I have tried using the following jQuery to do this but have been unsuccessful.
if (($this).next('.check').is(':checked')) {
        ($this).next('.check').val('Yes');
    } else {
        ($this).next('.check').val('No');
    }

Answer: $(".check").change(function(){
    //alert("checked");
    if($(this).is(":checked")){
        $(this).val("yes");
        //alert($(this).val());
    } else {
        $(this).val("no");;
    }
});

demo
Answer: That's not how checkboxes work. If it's checked, its value will be passed to the server.
Just set the value originally to Yes:
<input class="check" type="checkbox" name="att[]" value="Yes">

Comment: I need it to have a value if it's not checked too. It is to be sent to a database, I need a value for both on submission of the form.
Comment: @user2620746 - So do that server-side.
Comment: As you can see in the name attribute I'm putting the value into an array. This array contains other input types too. When posting to an array and a checkbox is unticked, it is skipped by php and not given a position in the array. Therefore server side can't help me and I need to use JS to define a value before the form is submitted

JQuery checkbox value on check


iOS Simulators are not working in Xcode 6.1.1?

Question: Iam able to run my project in iPad and iphone but when i tried to run it in iPad simulators
but then i got this error .
<code>ld: building for iOS Simulator, but linking against dylib built for MacOSX file '/Users/apple/Documents/releaseAPICON2015/SenTestingKit.framework/SenTestingKit' for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>
please check this link for screenshot
Error
Please tell me how to get back all simulators in xcode 6.1.1
Answer: You are trying to link SenTestingKit.framework in you iOS project. You cannot use OS X binaries in iOS Simulator apps as they are not compatible.
On older versions of iOS, you would encounter runtime errors (incorrect values or crashes). On iOS 8.0, this became a link-time error.
You need to build a version of SenTestingKit.framework for iOS. Hope this helps.. :)
Comment: can u answer my this question  http://stackoverflow.com/questions/27863507/uitableviewcell-image-size-changing-on-click-of-cell
Comment: http://stackoverflow.com/questions/27863507/uitableviewcell-image-size-changing-on-click-of-cell


Can users connecting to my server download mods directly from me?

Question: I set up my own minecraft-Forge 1.10.2 server with a few mods on it.
My question is now: Can I achieve, that connecting Clients automatically download missing mods so they can play on my server without hours of seeking for the mods, or downloading the modpack?
I want to ask the user like "Do you want to download the missing mods?"
If that is possible, how do I do that?
Comment: i dont want to do it THAT automatically xD ofc its a sec-risk... i want something like "u dont have da mods, u need to DL, do u want?" thing
Comment: I don't think this will be possible and I seriously do hope so, since it's a major security risk to download and install something without the user's direct permission.
Comment: That wasn't specific for your case. But if you can do it, everyone can - and not everyone has good intentions by doing this.
Comment: srry, ill add id to my question, ofcourse i do not want to support "bad-intentios"
Answer: You can create a pack and publish it on the Curse launcher and tell them the code.
The launcher then will download and maintain the mods required to connect to your server for them.


How do I simulate a delay with chai-as-promised and karma/angular?

Question: Example test faking a delayed promise resolve:
describe('Example', function() {
  var $q;
  var $rootScope;
  var $scope;
  var $timeout;
  var fakePromise;

  beforeEach(inject(function (_$q_, _$rootScope_, _$timeout_) {
    $q = _$q_;
    $rootScope = _$rootScope_;
    $timeout = _$timeout_;
    $scope = $rootScope.$new();

    fakePromise = function (){
      return new Promise(function(resolve, reject){
        $timeout(function(){
          resolve('foo');
        }, 100);
      });
    };
  }));

  afterEach(function () {
    $scope.$apply();
  });

  it('should wait for promise to resolve and have a result', function(){
    return fakePromise().should.eventually.equal('foo'); //taken from chai-as-promised readme
  });

});
The readme says to do:
return doSomethingAsync().should.eventually.equal("foo");

The error I get is:
Chrome 49.0.2623 (Mac OS X 10.11.4) Example should wait for promise to resolve and have a result FAILED
  Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

Comment: How about this? trigger `done()` callback with `.notify(done);`
Answer: The $timeout service already returns a promise. No need to manufacture one.
fakePromise = $timeout(function() {return "foo"}, 100);

In this example, fakePromise is set to a promise that resolves to "foo" after 100 milliseconds.


is it possible for a function continuous everywhere and differentiable nowhere have a finite arc length between two points?

Question: is it possible for a function continuous everywhere and differentiable nowhere have a finite arc length between two points? and if so how would you find it?
it was a little weird finding out such functions exists I didn't know if it was possible or not to even define arc length.
Comment: I don't think it's possible because it's a fractal. I might be wrong tho.
Comment: The graph of $f:[a,b]\to\mathbb{R}$ has finite arc-length (i.e., rectifiable) if and only if $f$ is of bounded variation, and so, differentiable almost everywhere. Consequently, every nowhere-differentiable function is non-rectifiable.
Answer: Consider $\mathbb{R}^2$ with the norm $|(x, y)|_1 = |x| + |y|$.
Then $f$ has finite arc-length along $[0, 1]$ $\iff$ $f$ is bounded variation on $[0, 1]$. But functions of bounded variation are a.e. differentiable.
Since we have $|(x, y)|_2 = (x^2 + y^2)^\frac{1}{2} \ge \frac{1}{\sqrt{2}}|(x, y)|_1$, the same argument applies.
Comment: I think you could make this work for the usual definition of the norm as well.  For example, using the fact that all norms are equivalent on $\mathbb R^2$.
Comment: (+1) Or simply using the inequality $$V_{a}^{b}(f)\leq\operatorname{length}(\{(x,f(x)):a\leq x\leq b\})\leq V_{a}^{b}(f)+(b-a),$$ where $V_{a}^{b}(f)$ denotes the total variation of $f$ on $[a,b]$.
Comment: @StephenMontgomery-Smith Indeed. I'll edit it to make the answer more complete, thanks.


Finding unique linear transformation in tensor product.

Question: I'm trying to learn tensor products by myself, and I'm using primarily the Linear Algebra and Geometry book, by Kostrikin and Manin.
I need help with the following question:

Let $V$ and $W$ be $\mathbb{K}$-vector spaces. Show that there is a unique linear transformation $\Gamma: V \otimes W \rightarrow \mathcal{L}(V^*,W)$ that satisfies $$\Gamma(v\otimes w)(f) = f(v)w$$ for any $v \in V, w \in W$ and $f\in V^*$.

My first (and only) idea was to define an application $t$ from $V\times W$ to $V \otimes W$ that associates the pair $(v,w)$ to $v\otimes w$, and use (somehow) that $t$ is universal. However, I'm very much stuck.
Any help would be deeply appreciated.
Comment: Assuming $\mathcal{L}(V^*,W)$ means linear maps $V^*\to W$ then define $\Gamma:V\times W\rightarrowtail \mathcal{L}(V^*,W)$ by $\Gamma(v,w):f\mapsto f(v)w$.  Prove $\Gamma$ is biadditive (distributes) and apply universal mapping property of the tensor product.
Comment: Thank you, @Algeboy. I've managed to answer the question. If no one post an answer, I will post mine latter on, just to close the question.
Answer: Recall that every pair of $\Bbb K$-vector spaces $V$ and $W$ defines a map

where $\Phi$ is the $\Bbb K$-bilinear map defined by $\Phi(v, w)=v\otimes w$. The map $\Phi$ is characterized by the following universal property.

Universal Property of $\Phi$. Consider a diagram of $\Bbb K$-vector spaces

where $\phi$ is $\Bbb K$-bilinear. Then there exists a unique
  $\Bbb K$-linear map $\Gamma$ making

commute.

Next, to address your example, take $X=\mathcal L(V^\ast, W)$. The space $V^\ast$ consists of all linear maps $V\to \Bbb K$ and the space $\mathcal L(V^\ast, W)$ consists of all linear maps $V^\ast \to W$.
Now, let $\phi:V\times W\to\mathcal L(V^\ast, W)$ be defined by $\phi(v, w)(f)=f(v)\cdot w$. The formulas
\begin{align*}
\phi&(\lambda_1\cdot v_1+\lambda_2\cdot v_2, w)(f)\\ &= f(\lambda_1\cdot v_1+\lambda_2\cdot v_2)\cdot w & \phi&(v, \lambda_1\cdot w_1+\lambda_2\cdot w_2)(f)\\  &= f(v)\cdot(\lambda_1\cdot w_1+\lambda_2\cdot w_2) \\
&= \{\lambda_1\cdot f(v_1)+\lambda_2\cdot f(v_2)\}\cdot w & &= \lambda_1\cdot f(v)\cdot w_1+\lambda_2\cdot f(v)\cdot w_2 \\
&= \lambda_1\cdot f(v_1)\cdot w+\lambda_2\cdot f(v_2)\cdot w & &= \lambda_1\cdot\phi(v, w_1)(f)+\lambda_2\cdot\phi(v, w_2)(f) \\
&= \lambda_1\cdot\phi(v_1, w)(f)+\lambda_2\cdot\phi(v_2, w)(f)
\end{align*}
demonstrate that $\phi$ is $\Bbb K$-bilinear.
Now, we have a diagram

where $\phi$ is bilinar. What does the universal property of $\Phi$ say?


How to grab the order status of the last order in WooCommerce via a shortcode

Question: I'm trying to give our customers a better insight in their order status without going to their account. My plan is to print the info on the home page once someone has ordered.

I'm struggling to get the order status to display elsewhere.
Here is the current code I've whipped up based on a code used to grab the product of the last order.
function woostatus() {
    // Not available
    $na = __( 'N/A', 'woocommerce' );

    // For logged in users only
    if ( ! is_user_logged_in() ) return $na;

    // The current user ID
    $user_id = get_current_user_id();

    // Get the WC_Customer instance Object for the current user
    $customer = new WC_Customer( $user_id );

    // Get the last WC_Order Object instance from current customer
    $last_order = $customer->get_last_order();

    // When empty
    if ( empty ( $last_order ) ) return $na;

     // Get order date
    $order_items = $last_order->get_status();

    // Latest WC_Order_Item_Product Object instance
    $last_item = end( $order_items );

    // Pass product ID to products shortcode
    return $order_items;
}
// Register shortcode
add_shortcode( 'display_woostatus', 'woostatus' );

Answer: $order_items = $last_order->get_status() will return a string and is therefore not an array. So using end( $order_items ) is a superfluous step.
Use instead:
function woostatus() {
    // Not available
    $na = __( 'N/A', 'woocommerce' );

    // For logged in users only
    if ( ! is_user_logged_in() ) return $na;

    // The current user ID
    $user_id = get_current_user_id();

    // Get the WC_Customer instance Object for the current user
    $customer = new WC_Customer( $user_id );

    // Get the last WC_Order Object instance from current customer
    $last_order = $customer->get_last_order();

    // When empty
    if ( empty ( $last_order ) ) return $na;

    // Get order status
    $order_status = $last_order->get_status();

    // Return
    return $order_status;
}
// Register shortcode
add_shortcode( 'display_woostatus', 'woostatus' );

SHORTCODE USAGE
In an existing page:
[display_woostatus]

Or in PHP:
echo do_shortcode('[display_woostatus]');


How to create simple div with transparent rest of site?

Question: How to create simple div with transparent rest of site (This div will be show after click in link or other div)
Here exemple:
Comment: make use of opacity in CSS........opacity:0.4; check this link http://www.w3schools.com/CSS/css_image_transparency.asp
Answer: Can't you use rgba(0, 0, 0, 0.8); as background? Fiddle For Demonstration
div#transparent {
width:100%;
height:100%;
position:absolute;
top:0;
left:0;
z-index:2;
background:rgba(0, 0, 0, 0.8);
}
div#content {
width:300px;
height:300px;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
}

Comment: I don't know how to do with jquery. How display div#content after click on link
Answer: Another method would be to use jQuery UI. With jQuery UI you can use the dialog widget along with the modal property to get the same effect.  jQuery UI also has a lot of other widgets that are pretty useful.
jQuery UI:
http://jqueryui.com/
You can also add different themes to jQuery UI or make custom themes to get that transparent background that you wanted by using the jQuery Themeroller
jQuery Themeroller: http://jqueryui.com/themeroller/
Working example on jsFiddle: http://jsfiddle.net/jk4ru/
Answer: with jquery: http://jsfiddle.net/bbgwB/
$.fn.center = function () {
    this.css({
        'top': ($(window).height() - this.height()) / 2,
        'left': ($(window).width() - this.width()) / 2
    });
    return this;
};

$(function () {
    $(window).resize(function () {
        $('.message').center();
    }).resize();
});

used css:
html, body {
   height:100%;
}
.overlay {
  width:100%;
  height:100%;
  background:rgba(0, 0, 0, 0.4);
  position:relative;
  z-index:1;
}
.message {
   width:120px;
   height:200px;
   background:yellow;
   position:absolute;
   z-index:2;
   left:0;
   top:0;
}


For vectors $0 \neq s,y \in \mathbb{R^n}$ with $(s,y)>0$ there exist only one positive definite symmetric matrix $Q$ such that $Qs = y$.

Question: The statement above was given as an exercise to prove. I've done the existence part. The problem with it is that the part about uniqueness might be a typo. Is it unique?
Comment: Is there not a confusion between $y$ and $v$?
Comment: @mathcounterexamples.net yes thanks! Corrected the title
Answer: This is clearly not true.
Take $s=y=e_1$ where $e_1$ is the first vector of the canonical basis then any diagonal matrix $Q$ with for diagonal $1, \lambda_2, \dots , \lambda_n$ where $\lambda_i \gt 0$ is symmetric positive definite and such that $Qs=y$.
Comment: This is just nitpicky, but don't $s$ and $v$ have to be strictly positive vectors?
Comment: @paulinho I don't know what means to be positive for vectors??? Can you elaborate ? At least the inner product $(e_1,e_1)$ is strictly positive, which is what is requested in the question.
Comment: @paulinho no, only strictly positive inner product, but thanks for your counterexample also
Comment: Ah, I see. I wasn't aware that the notation $( \cdot, \cdot)$ referred to the inner product here. I took it to mean that each element of $s$ and $y$ were positive
Answer: No, it's not unique. Consider
$$s = y = \begin{bmatrix} 1 \\ 1\end{bmatrix}$$
Then there are infinitely many positive semi-definite matrices $Q$ that have $s$ as a $1$-eigenvector, namely $Q s = s = y$. To construct these examples, just consider an eigendecomposition of a positive definite $Q$ which has $s$ as a $1$-eigenvector. Then the eigendecomposition is of the form
$S D S^\dagger$
where $s / \|s\|$ is a column of $S$ (which is unitary), the corresponding diagonal entry in $D$ is one, and the rest of the diagonal entries in $D$ are also positive. For example,
$$\left( \frac{1}{\sqrt{2}}\begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix} \right) \begin{bmatrix} 1 & 0 \\ 0 & \mu \end{bmatrix} \left(\frac{1}{\sqrt{2}}\begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix}\right)$$
satisfies the criterion for any positive $\mu$.


Cannot perform an aggregate function on an expression containing an aggregate or a subquery - error

Question: I have a problem with getting the top selling product from my database. This is the code I have tried:
SELECT productid
FROM soldvia
GROUP BY productid
HAVING SUM(noofitems) =  (SELECT MAX(SUM(noofitems))
                          FROM soldvia
                          GROUP BY productid);

I get this error:

Msg 130, Level 15, State 1, Line 68
  Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

I have no idea what I am doing wrong, please help.
Answer: In SQL Server, you can write this as:
SELECT productid
FROM soldvia
GROUP BY productid
HAVING SUM(noofitems) = (SELECT TOP (1) SUM(noofitems)
                         FROM soldvia
                         GROUP BY productid
                         ORDER BY SUM(noofitems) DESC
                        );

The more typical way to write the query, though, uses RANK() or window functions:
SELECT productid
FROM (SELECT productid, SUM(noofitems) as numitems,
             RANK() OVER (ORDER BY SUM(noofitems) DESC) as seqnum
      FROM soldvia
      GROUP BY productid
     ) t
WHERE seqnum = 1;


Subset dataframe by row names

Question: I'd like to subset a dataframe by a range of row names.  But I keep getting this error message:
comparison (1) is possible only for atomic and list types

my data looks like this:
              KATstd samp.depth
    1800 0.4015238          8
    1801 1.2792888          8
    1802 1.5981420          8
    1803 1.9429598          8
    1804 2.7847786          9

This is the code I am trying to use:
KAT.sub<-subset(KAT,row.names==(1929:2009))

Answer: You want to use KAT[1929:2009,]. The == logical equivalence operator is not "vectorized" and you cannot refer to the row.names of a data.frame like that. You may want to brush up on basic subsetting by looking at ? extract.

Subset dataframe by row names


Ascii value corresponding to hex

Question: The below lines does not write anything to the file, ascii.txt. Trying to write the ascii equivalent of hex "88". However nothing is written to the file, nor nothing is asssigned to the variable, ascii.
Dim ascii = ChrW(Convert.ToInt32("88", 16))
My.Computer.FileSystem.WriteAllText("e:\ascii.txt", ascii, True)

In excel or openoffice, you can get the ascii equivalent using the below formula. What is wrong with the code?
=CHAR(HEX2DEC("88"))

Comment: 88 hex = 136 decimal. That's not ASCII.
Answer: ChrW doesn't know ASCII, it only knows Unicode code points.
U+0088 is a control character, it's non-printable (i.e. it doesn't normally correspond to a displayable character). It's therefore not surprising that the file appears empty.
Furthermore, even ChrW worked with ASCII, the character 0x88 is not ASCII, it's outside its range. In case you were talking about the former standard Windows character set, codepage 1252, you can use the following code to retrieve the string representation of the character code:
Dim bytes = New Byte() { &H88 }
Dim text = System.Text.Encoding.GetEncoding(1252).GetString(bytes)

Ascii value corresponding to hex


Circular imports django

Question: I have wrote this code in my models.py file.
As you see the code, I have a class called File and also I have imported in models.py the same class.
Now it gives me this error while migration:
Cannot import name "File" from 'uploadapp.models'
I understand it's the error for circular (recursive) import. But how can I solve this?
from django.db import models
from .models import File

class File(models.Model):
    file = models.FileField(blank=False, null=False)
    def __str__(self):
        return self.file.name

Comment: Remove the `from .models import File`, you import the `models` module *in* the `models` module.
Answer: You remove the from .models import File. It makes no sense to import the module in the same module:
from django.db import models
# from .models import File

class File(models.Model):
    file = models.FileField(blank=False, null=False)

    def __str__(self):
        return self.file.name

Circular imports django


About the use of Russian Roulette in Smallpt

Question: I was taking a look at Smallpt (http://www.kevinbeason.com/smallpt), more specifically at the Russian Roulette part. Actually, RR is used in two places along the code: first, to determine ray termination; and second, for the rendering of dielectrics.
That is the code for the ray termination case (expanded code version):
<code>// p = maximum reflectance
// fr = BRDF
double p = fr.x > fr.y && fr.x > fr.z ? fr.x : fr.y > fr.z ? fr.y : fr.z;

if ( ++depth > 5 )
    if ( erand48(Xi) < p )
        fr = fr * ( 1 / p );
    else
        return obj.emission;
</code>
After five bounces, RR is used to determine if the ray path continues or not. If it continues, the BRDF is scaled to compensate for it. This is Ok for me.
RR is also used in a second code segment to select between refraction or transmission during the rendering of dielectrics (expanded code version):
<code>double Re = R0 + ( 1 - R0 ) * cost * cost * cost * cost * cost;
double Tr = 1 - Re;
double P = .25 + .5 * Re;
double RP = Re / P;
double TP = Tr / ( 1 - P );
Vec Lo; // output radiance

if ( depth > 2 )
    if ( erand48(Xi) < P )
        Lo = radiance(reflRay,depth,Xi) * RP;
    else
        Lo = radiance(Ray(x,tdir),depth,Xi) * TP;
else
    Lo = radiance(reflRay,depth,Xi) * Re + radiance(Ray(x,tdir),depth,Xi) * Tr;
</code>
According to the code above, the path branches recursively if the ray has bounced up to two times. After two bounces, however, RR is used to select the path to be followed. This is also Ok for me.
What is a bit confusing is the fact that the radiance returned by both possible non-branching paths (refraction and transmission) is scaled. I understand that there are different probabilities regarding reflection and transmission. However, if for instance Re = 0.3 and Tr = 0.7, and 100 rays strike the surface, about 30% of the rays will be reflected and 70% of will be transmitted due RR. In this case, I understand that there is no path termination neither energy loss, so there wouldn't be anything to compensate for.
Thus, my first two questions are: why are these radiances scaled? Should they be scaled, or would it work without scaling at all?
My third question is related to the scaling factors: Why the author has used P, RP and TP instead of Re and Tr?
Any indication of a good reading about this topic is also very welcome!!
Thank you!
Answer: The reflected and transmitted values need to be scaled because they are not sampled proportionally to their contribution. You'll notice how the decision whether to reflect or transmit is made based on P, not Re.
About why that scaling has been done in the first place, only the author can give you the definitive answer. My guess is that this is done to prevent extreme values that would come from tiny probabilities. Imagine that Re is 0.001 and is used without scaling. Then only one in 1000 rays would reflect, and the contribution of that ray would be multiplied by 1000. At a render with, say, 64 rays per pixel, this would leave very visible artefacts, as not every pixel would get a reflected ray. The scaling from this code snipped on the other hand makes sure that the ray budget is more evenly distributed between reflection and transmission and that each potential path taken is guaranteed at least 25% or the rays.
For further reading about path tracing, there is no better and comprehensive resource than www.pbrt.org - both the book and the source code are worth reading.


Water in dishwasher

Question: I had a Kenmore dishwasher installed in January, in less than a month we had a repair call because the inside of the machine was always wet and was stinking.  The repair man said the new machine needed to be seasoned with the rinse agent being wiped on the entire inside of the machine. Said it would be okey in a matter of time.  It still stinks and am having a nightmare with Sears to get this resolved.  Their install people came back out and on the bottom of the machine, there is a cup thing that was full of water, up to the level of the machine.  He said that much water should not be there, and to get the dish washer replaced. He said a little water was fine, but not over 3 inches of water. The hose under the sink is not looped up, but the hose is looped over the dish washer under the counter.  The repair supervisor at Sears said the standing water should be there so smell doesn't back up.  I am really questioning his expertise on this issue. They are sending out another repair tech to look at the dish washer.
[Question: who is correct? Is some standing (and stinking) water in the dishwasher normal or not? Would this be a defect in the machine, or in the way it was installed? And if it isn't normal, how can I get Sears to take responsibility and fix it?"]
Comment: And what's your question?
Comment: Have you tried running a [dishwasher cleaning agent](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=dishwasher+cleaner&tbm=shop) through it? When I moved into my house, the dishwasher (which hadn't been used in months) had a moldy smell, even after several cycles with dish detergent. The dishwasher cleaning agent took care of the odor, and it hasn't come back in 2 years (I run the cleaning agent through around every 6 months). Obviously a new dishwasher shouldn't have any odor, but if they aren't going to replace it, it might be worth a shot.
Comment: I've taken the liberty of adding an explicit question. If you intended to ask something else, please re-edit to clarify. We really do need to know exactly what you want answered.)
Comment: Sears is saying the water should be there, everything I read on line says no it shouldn't. Okay to have a little, but not up to the level of the dish washer. The dishes are clean and dry after a wash, but the stink remains in the dish washer, and in the inside is always wet.
Comment: Sears sub contracting installers are idiots........the dish washer has to be looped up over the sink.  Sears sub contracting repair techs took care of it today.
Comment: @Leanne - this comment should probably be posted as an answer, it's ok to answer your own question. Though details on what "looped up over the sink" means would  be helpful.
Comment: Leanne, your response to your question helped me. I recently had an issue and determined that my loop was not far enough above the sink because the tenant was filling the sink then draining it. Causing it to backfill into the dishwasher.
Answer: There shouldn't be any standing water inside of your dishwasher while it is not in operation.
The water could be a few different things, but I would check first to see if water from your sink is being siphoned into the dishwasher. Depending on the install, you will either need a high loop on your dishwasher waste line, or an air gap device.
A high loop basically is when you bring the drain up much higher than the trap in the sink so the water from the sink goes down the drain instead of into your dishwasher. I did this in my own home by fastening the pipe to the bottom of my cabinet before it drops down to the dishwasher.
Your dishwasher may also be defective and is not draining correctly. The pump should be sucking out all of the water from your dishwasher down the drain. There is a possibility that there is something clogging it and preventing it from emptying all the way. Since you already had people out to look at it, then that probably isn't what is causing the problem.
Another possibility is that the sewer itself is backing up into your home. Since the dishwasher is one of the lowest points in your home, the water will go in there first.

Water in dishwasher


Nearest unblockaded core province with a port. How is this computed?

Question: How does the game compute the nearest unblockaded core province with a port? I am playing as Ming and have cored and colonized Midway islands (picture below). However, the game still says my closest unblockaded core is in Gubbi Gubbi (Australia). How is this computed and why is Midway Islands not my closest port?
Answer: You need a) a core and b) a dock (or any better port). Since you cored it, you probably forgot to construct a port in Midway.
The calculation is the same as the distance measurement used for sea attrition. I am not certain if it is affected by trade winds, that could be another reason.
(In older versions you could also rent port access from another country, iirc, but that was removed around 1.5-ish.)
Comment: @Sunspawn I think an actual dock is required, I had the exact problem as OP myself (not sure if same island tho) and building a dock seemed to fix it, I recall. Maybe OP could comment if this answer fixed his problem, too (it was accepted, so I guess it did).

I don't have EU4 installed right now, I'll try to test it later. Of course if you tested it, let me know. Or is there is another aspect to this that we missed?
Comment: I don't think that is true. There is no building called "port", all coastal provinces has one.
Comment: @Nix I've added a link and fixed the wording.
Comment: I'm fairly sure you don't need the building. Port refers to a coastal province - a province that shits can dock into.


What is the difference between `blocktrans` and `blocktranslate`? Between `trans` and `translate`?

Question: What is the difference between these two lines of code in a Django template?
{% blocktrans %}Example{% endblocktrans %}
{% blocktranslate %}Example{% endblocktranslate %}

Likewise, what is the difference between these two lines of code in a Django template?
{% trans "Example" %}
{% translate "Example" %}

Answer: There is no difference. {% blocktrans %} is equivalent to {% blocktranslate %}, it's just an alias. Likewise, {% trans %} is equivalent to {% translate %}.
Comment: True, there is no difference.  The tag was changed from `trans` to `translate` in Django 3.1 (https://docs.djangoproject.com/en/3.1/topics/i18n/translation/#translate-template-tag).  Look at the bottom of that section.


Operating system not found

Question: I have uninstalled Ubuntu 12.04 and installed Ubuntu 13.04 instead. It told me that Ubuntu is installed and that I need to restart my PC. After restarting I got an error message that said: operating system not found.
How can I fix this?
Answer: Try to boot using the live CD and install Boot Repair program:

sudo add-apt-repository ppa:yannubuntu/boot-repair
sudo apt-get update
sudo apt-get install boot-repair

then launch Boot Repair, use the default settings and follow the instructions (it may ask you to do something manually)

Operating system not found


Example of $\arg\min\limits_{T: E(T(X))=\theta}\mathbb{E}|T(X) - \theta| \neq \arg\min\limits_{E(T(X))=\theta}\mathbb{E}(T(X) - \theta)^2$

Question: Suppose that $X_1, X_2, \dots, X_n$ is an i.i.d. sample distributed according to $F(x, \theta)$ distribution function, and we want to estimate $\theta$.
Among all unbiased estimators, the best one is considered to be the one which has the minimum variance.
But what if we want to minimize not variance, but absolute deviation, e.g. find such statistics $T(X)$ which has minimum $\mathbb{E}|T(X_1, X_2, \dots, X_n) - \theta|$, not $\mathbb{E}(T(X_1, X_2, \dots, X_n) - \theta)^2$?
Can you provide examples of a distribution $F(x, \theta)$ and two unbiased estimators one of which has the least variance and another one – the least expected absolute deviation?
I tried to consider normal distribution. It is known that both the sample mean and the sample median are unbiased estimators for the mean. But I'm not sure that the median has the least expected absolute deviation here.
Any help, comments, hints and, especially, complete answers are very welcome and would be greatly appreciated!
Comment: I would try using a Bernoulli distribution with parameter $\theta$.  It's simple to work with and isn't as symmetric as the Gaussian.
Answer: The Laplace distribution seems like it would be the canonical example for this kind of thing. If $X$ is Laplace distributed with density:
\begin{equation}
f_X(x) = \frac{1}{2b}\textrm{Exp}(-\frac{|x-\mu|}{b})
\end{equation}
The MLE for $\mu$ is the sample median $\hat{m}$, and the MLE for $b$ is the sample average absolute deviation from the median: $\hat{b} = \frac{1}{N}\sum_{n=1}^N |x_i - \hat{m}|$. Note that $\bar{x}$ is also unbiased for $\mu$ as the mean and median are the same in a Laplace distribution.
Denoting by $\mu_{m}$ and $\mu_{\mu}$ the sample median and sample mean, respectively, we can examine their variances and absolute deviations:
$E[(\mu_{\mu} - \mu)^2] = E[\mu_{\mu}^2 - 2\mu_{\mu}\mu + \mu^2] = E[\mu^2_{\mu}]-\mu^2$.
Expanding $\mu_{\mu}^2 = (\frac{1}{N}\sum_{i=1}^N x_i)^2 = \frac{1}{N^2}\sum_{i,j=1}^N x_ix_j$ Taking the expectation and noting the independence of the observations we get:
$E[\mu_\mu^2] = \frac{1}{N^2}(\sum_{i=1}^N E[x_i^2] + 2\sum_{i\neq j = 1}^N E[x_i]E[x_j] ) = \frac{1}{N^2}(2b^2 + \mu^2 + 2\binom{N}{2}\mu^2)$.
$E[\mu_\mu^2] = \frac{1}{N^2}(N2b^2 + N\mu^2 + 2\binom{N}{2}\mu^2) = \frac{1}{N^2}(N2b^2 + N\mu^2 + N*(N-1)\mu^2) = \frac{1}{N}(2b^2 + \mu^2 + (N-1)\mu^2)$
So $Var[\mu_\mu] = \frac{2b^2}{N}$.
I think you can do some similar stuff with the median, and also calculate the absolute deviation for $\mu_\mu$, but I ran out of time to do the algebra.


How to determine the type of the object an iterator is pointing to in c++ template function?

Question: I have a template function in C++ that serializes an iterable:
template<typename Stream, typename Iter, typename Infix, typename Closure>
inline Stream &stream_iterable(Stream &os, Iter from, Iter to, Infix infix_, Closure open, Closure close) {
    if (from == to) return os;
    os << open << *from;
    for (++from; from != to; ++from) {
        os << infix_ << *from;
    }
    os << close;
    return os;
}

For examaple, it basically converts std::vector<int>{1,2} to a string "[1,2]"
I would like to check the type of the object the iterator is pointing to and if it is std::string, I would like to use std::quoted to add quotation around the elements of the vector, Something like this:
template<typename Stream, typename Iter, typename Infix, typename Closure>
inline Stream &steam_iterable_quoted(Stream &os, Iter from, Iter to, Infix infix_, Closure open, Closure close) {
    if (from == to) return os;
    os << open << std::quoted(*from);
    for (++from; from != to; ++from) {
        os << infix_ << std::quoted(*from);
    }
    os << close;
    return os;
}

How can I check the type of (*from) and combine these two functions into one?
Comment: I suggest using *specialization* instead of "checking" type.
Comment: @motam79: Then specialization is your answer. in C++17 we can use `if constexpr` to perform compile-time type checking (& branching) in a more readable manner.
Comment: Are you compiling with C++17?
Comment: I am compiling with C++ 14
Comment: @AndyG I agree, after reading about if constexpr. I am motivated to upgrade to C++17. It makes the template code much more readable.
Answer: You don't actually need to know the type in the body of stream_iterable. As the old saying goes, add a level of indirection:
namespace detail {
  template<typename T>
  constexpr T const& prepare_to_print(T const& t) { return t; }

  auto prepare_to_print(std::string const s&) { return std::quoted(s); }
  // A non-const overload would be required as well...
  // Forwarding can be a drag sometimes
}

Just pass the dereferenced iterator to prepare_to_print. The nice thing about overloads is that you can customize the behavior further by adding more of them later on.
Comment: Care with forward reference against regular overloads: `std::string&` would take forwarding one :/.
Comment: @Jarod42 - Yeah, I omitted a fair few overloads for simplicity. Though if you ask me that's a language defect, plain and simple :S. At least in this case the default behavior is to do nothing.
Comment: `const T&` would be enough in that case. (we don't consume/mutate parameter for printing normally).
Comment: @Jarod42 - Mmm.. Yeah I suppose code would have to be truly Machiavellian to break with a mere `const&` overload
Answer: This simplest, working version:
namespace quoting {
  template<class T>
  T const& auto_quote( T const& t ) { return t; }
  template<class C, class T>
  auto auto_quote( std::basic_string<C,T> const& s ) {
    return std::quoted(s);
  }
  // add more std types that need quoting here.
}

now do this:
// ...
if (from == to) return os;
using quoting::auto_quote;
os << open << auto_quote(*from);
for (++from; from != to; ++from) {
    os << infix_ << auto_quote(*from);
}
os << close;
// ...

in order to make something be quoted differently, override auto_quote in the namespace of the type (if not in std; no injecting names into std allowed) or in namespace quoting.  It will be picked up automatically.
So if you have your my_string in namespace my_ns:
namespace my_ns {
  auto auto_quote( my_string const& s ) {
    // some manual quoting code
  }
}

and it will be picked up automatically by the above code.
Comment: It works. Thanks! Just a question: why do we need two template types: template for the string case?
Comment: @motam79 because the standard?  One is the char, the other the traits.
Answer: You can use decltype(*from) to obtain the result type of the dereference operator, but (1) it may need to be further massaged before doing comparisons (it may be a reference, a value, possibly cv-qualified, ...), and (2) it's not really extensible WRT other types.
In general for this kind of stuff you want to delegate to a template function that (in your case) is responsible to actually output the datum on the stream, with a default for the "normal" types, and specialize it for types that require special treatment.
Answer: Use this to retrieve type of object referenced by an iterator: std::iterator_triats<SomeIteratorType>::value_type
To combine these two functions you can use constexpr if statement which is a C++17 feature.


Best OCR for extracting text from a plot?

Question:
(source: goldprice.org)
Does anyone know of a good ocr that is able to convert this image into text?
I tried tesseract but it didn't work out the way I expected.
Comment: the Text Gold Price GBP634.92△3.07 637, 636, 634,
Comment: What kind of output would you expect from this? "Gold Price GBP634.92△3.07 637, 636, 634, ..."  Or are you trying to extract the graph values?
Answer: You can try at first to find the text "Gold Price" or "GBP" (if this text is always the same)
And then you will know the place where that text is places, then just cut that part of image containing the text and proceed OCR to that line separately.
You can also try Cuneiform:
link text
Answer: Sounds like you need Engauge Digitizer (Open Source) - Digitizing software that converts an image file showing a graph or map, into numbers.


Concerning pointer and reference in class

Question: Here's my program
class Base
{
public:
  void fc()
  {
    cout << "Class function is called" << endl;
  }
};

void main()
{
  Base* ptr;
  ptr = 0;
  Base b1, b2;
  *ptr = b1;
  ptr->fc();
  ptr = 0;
  ptr = &b2;
  ptr->fc();
}

It runs OK
My question is simple:
You can assign object to pointer by *ptr=b1; or ptr=&b1 so what's the difference between these two, if any? Can you go deeper as why there are two ways of assigning pointer if they achieve the same goal? Are they fundamentally different?
Secondly, some people call '&' reference sign, some say it's 'get address of' can some one clear this out for me ? More over what's the difference between reference and pointer?
Thanks a lot
Linus
Comment: In your code `*ptr=b1;` raises undefined behavior. `ptr` isn't initialized with a valid address, at that point.
Comment: They are not equivalent, `*ptr=b1;` will copy the object. For your second question the answer is `&` means different things in different contexts, like many of C++'s operators and keywords. For your third question please read a good introductory C++ book.
Comment: _"some people call '&' reference sign, some say it's 'get address of'"_ and some say its 'bit-wise and'. So why not clarify those from a good book, professor lecture, good video tutorial or a web search ?
Comment: As for the question (though you haven't used references) see here please: http://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in
Comment: The symbol "&" has three different meanings in C++. Which one depends on the context.
Comment: It's like the difference between a person and the house where that person lives. `house = &person` tells you where the person lives. `*house` tells you who lives in the house. `*house = person` gives the house a new occupant.
Answer: When you do *ptr = b1, what you are doing is as follows:
1) Dereferencing the object that is already at the memory location pointed to be ptr
2) Copying over the members of b1 to the object deferenced in 1
Which is why, your code will give you a segmentation fault if you utilised a member variable. Consider the following modification for your class:
#include <iostream>
#include <string>

class Base
{
public:
    Base():name("undefined")
    {
    }

    Base& operator=(const Base& other){
        std::cout << "Copying from " << other.name << " to " << name << std::endl;
        name = other.name;
        return *this;
    }

    void fc(){
        cout<<"Class function is called"<<endl;
    }

    std::string name;
};

Now, with the above modifications, the following code will segfault:
int main()
{   Base *ptr; ptr=0;
    Base b1,b2;
    *ptr=b1; // will segfault here
    ptr->fc();
    ptr=0;
    ptr=&b2;
    ptr->fc();
    return 0;
}

In the second case, i.e. when you call

ptr=&b2

what you are doing is merely setting the address of the memory location that ptr points to. So, the following code WILL run fine:
int main()
{   Base *ptr; ptr=0;
    Base b1,b2;
    ptr=&b2;
    ptr->fc();
    return 0;
}

A more illustrative example will be the following:
int main()
{   Base *ptr;

    Base objA;
    objA.name = "objA";
    Base objB;
    objB.name = "objB";

    ptr = new Base();
    ptr->name = "ptrObj";
    *ptr = objA;
    std::cout << "Ptr is now " << ptr->name << std::endl;

    ptr = &objB;
    std::cout <<  "Ptr is now " << ptr->name << std::endl;

    return 0;
}

Which gives the following output:
Copying from objA to ptrObj
Ptr is now objA
Ptr is now objB

Answer:
You can assign object to pointer by *ptr=b1; or ptr=&b1 so what's the
  difference between these two,

First one de-references the ptr and changes the value in the address that ptr points to. Second one changes where ptr points in the memory to the address of b1.But in your example since the ptr doesn't point to a valid address in memory dereferencing it will cause undefined behaviour.

Secondly, some people call '&' reference sign, some say it's 'get address of' can some one clear this out for me ?

It depends on the context.For example when you use it like ptr = &b1 it means address-of operator. When you use it in a declaration it means a reference for ex: int &i; means i is a reference to an int.If you use it in a boolean expression it means AND or possibly Bitwise AND operator.There may be other scenarious that I missed but the important thing is to know that what it means depends on where you are using it.
Answer: @balajeerc you'll have memory leak that way... You're pointing to object objB now, and memory that's reserved earlier can't be accessed anymore nor freed.


WebRequest and HttpServletRequest in Spring MVC

Question: What is the difference between the two? Both have a getParameter method as well as setAttribute method, then where comes the difference between the two?
1) Which one is better to use in general?
2) Please explain specific scenarios where they can be used.
Answer: The javadoc of WebRequest is pretty clear on the subject:

Generic interface for a web request. Mainly intended for generic web request interceptors, giving them access to general request metadata, not for actual handling of the request.

(emphasis mine).
The javadoc links to WebRequestInterceptor, which says:

Interface for general web request interception. Allows for being applied to Servlet request as well as Portlet request environments, by building on the WebRequest abstraction.

So, basically, you should not use WebRequest except in a WebRequestInterceptor. And they introduced this interface in order to be able to write interceptors that apply to servlets and portlets. Other than that, if you really need access to the request in Spring MVC controllers, you should use the standard HttpServletRequest.
Comment: So, your interpretation of the JavaDoc reference directly contradicts the reference documentation, where among the supported argument types for request mapping methods in a controller there is the following item: "`org.springframework.web.context.request.WebRequest` or `org.springframework.web.context.request.NativeWebRequest`. Allows for generic request parameter access as well as request/session attribute access, without ties to the native Servlet/Portlet API." It also explains the differences (and the advantages) of using it instead of `HttpServletRequest`.