text:
Q: IStream COM read to buffer then send through winsock I've created a server/client through winsock2. Where the client takes a bmp screenshot, compresses it into jpeg and sends it to the server. The problem I'm having is the server is having problems saving the file onto disk. Like the data isn't receiving right. I think it has to do in the way I'm sending or receiving the buffer.
EDIT: From Setting breakpoints during debug it seems as if all the data was received. istream->Write returns correct number of bytes in correlation with Size and istream->Seek returns S_OK and the CLSID COM object contains the same data that was sent. Also before I send the buffer I test it to see if it saves and it does. Therefore I'm assuming it has to be the way  Buffer was sent or received.
EDIT:
On both ends the buffer looks like This
Screen Shot plus send code.
    ScreenShot(Packet_Handler* _Handle)
{
IStream* istream;
    //char* Buff;
    HRESULT res = CreateStreamOnHGlobal(NULL, true, &istream);
    Gdiplus::GdiplusStartupInput gdiInput;
    ULONG_PTR gdiToken;
    Gdiplus::GdiplusStartup(&gdiToken, &gdiInput, NULL);
    {
        HDC scrdc, memdc;
        HBITMAP membit;
        scrdc = ::GetDC(0);
        int Height = GetSystemMetrics(SM_CYSCREEN);
        int Width = GetSystemMetrics(SM_CXSCREEN);
        memdc = CreateCompatibleDC(scrdc);
        membit = CreateCompatibleBitmap(scrdc, Width, Height);
        HBITMAP hOldBitmap = (HBITMAP)SelectObject(memdc, membit);
        BitBlt(memdc, 0, 0, Width, Height, scrdc, 0, 0, SRCCOPY);

        Gdiplus::Bitmap bitmap(membit, NULL);
        CLSID clsid;
        GetEncoderClsid(L"image/jpeg", &clsid);

        bitmap.Save(istream, &clsid, NULL);
        bitmap.Save(L"Test.jpeg", &clsid, NULL); //THIS WORKS
        STATSTG pstatstg = { 0 };
        istream->Stat(&pstatstg, 0);
        ULONG Bytes;
        char* isBuff = new char[pstatstg.cbSize.QuadPart];
        LARGE_INTEGER li;
        li.QuadPart = 0;
        istream->Seek(li, STREAM_SEEK_SET, NULL);
        if (istream->Read(isBuff, pstatstg.cbSize.QuadPart, &Bytes) == S_OK)
        {
            IStream* nistream = nullptr;
            ULONG nBytes;
            CreateStreamOnHGlobal(NULL, true, &nistream);
            if (nistream->Write(isBuff, pstatstg.cbSize.QuadPart, &Bytes) == S_OK)
            {

                if (nistream->Seek(li, STREAM_SEEK_SET, NULL) == S_OK)

                {
                    Gdiplus::Bitmap bitmap2(nistream, NULL);
                    bitmap2.Save(L"Testing.jpeg", &clsid, NULL); //THIS WORKS
                }
            }
        }

        int Size = pstatstg.cbSize.QuadPart;
        int SOLI = sizeof(ULARGE_INTEGER);
        int SOCID = sizeof(CLSID);
        int SOIS = sizeof(IStream);

        Send_Full_Packet(_Handle, &Size, isBuff, TRUE);
        Send_Full_Packet(_Handle, &SOCID, &clsid, FALSE);

        printf("saving Screenshot");

        DeleteObject(memdc);
        DeleteObject(membit);
        ::ReleaseDC(0, scrdc);

    }
    Gdiplus::GdiplusShutdown(gdiToken);
    _getch();
    return 0;
}
    void Send_Full_Packet(Packet_Handler* _Handle, int* pSize, void * Buff, bool ispchar)
    {
        int SentPackets = 0;
        int sCheck = 0;
        int rCheck = 0;
        int Size = *pSize;
        char* isBuff;// = new char[Size];

            sCheck = send(_Handle->ConnectSocket, (char*)&Size, sizeof(int), NULL);

        int PacketsSent = 0;
        sCheck = 0;
        int PacketsLeft = Size;
        while (PacketsSent < Size)
        {
            if (ispchar == FALSE)
            {
                SentPackets = send(_Handle->ConnectSocket, (char*)Buff + PacketsSent, PacketsLeft, NULL);
            }
            else {
                isBuff = (char*)Buff;
                SentPackets = send(_Handle->ConnectSocket, isBuff + PacketsSent, PacketsLeft, NULL);
            }
            if (SentPackets == SOCKET_ERROR)
            {
                if (WSAGetLastError() != 10054)
                {
                    if (WSAGetLastError() == 10035)
                    {
                        SentPackets == 0;

                    }
                    else
                    {
                        printf("Sending Socket error: %d\n", WSAGetLastError());
                        break;
                    }

                }
            }
            PacketsSent += SentPackets;
            PacketsLeft -= SentPackets;
        }

    }

Receive code
    ScreenShot_Receive_Thread(Packet_Handler* _Handle)
{

    Packet_Handler::_Packet_Type Packet = Packet_Handler::_Packet_Type::Remote;
    while (true)
    {
        if (send(_Handle->si.Connections[_Handle->si.ConnectionCounter - 1], (char*)&Packet, sizeof(Packet_Handler::_Packet_Type), 0) != INVALID_SOCKET)
        {
            while (true)
            {
                int Size = 0;
                char* Buff = NULL;
                Buff = _Handle->Receive_Full_Packet(_Handle, &Size, Buff, TRUE);
                CLSID clsid;
                int SOCID = sizeof(CLSID);
                _Handle->Receive_Full_Packet(_Handle, &SOCID, &clsid, FALSE);
                IStream* istream = nullptr;
                ULONG Bytes;
                CreateStreamOnHGlobal(NULL, true, &istream);
                if (istream->Write(Buff, Size, &Bytes) == S_OK)
                {
                    LARGE_INTEGER li;
                    li.QuadPart = 0;
                    if (istream->Seek(li, STREAM_SEEK_SET, NULL) == S_OK)
                    {
                        Gdiplus::Bitmap bitmap(istream, NULL);
                        bitmap.Save(L"Testing.jpeg", &clsid, NULL);//DOESNT WORK
                    }
                }

            }
        }
    }
    MessageBox(NULL, L"CLient COnnection Error!", NULL, NULL);
    return 0;
}

  char* Packet_Handler::Receive_Full_Packet(Packet_Handler * _Handle, int* pSize, void * Buff, bool ispchar)
{
    int rCheck = 0;
    int sCheck = 0;
    int Size = *pSize;
    rCheck = recv(_Handle->si.Connections[_Handle->si.ConnectionCounter - 1], (char*)&Size, sizeof(int), 0);
    if (rCheck == -1)
    {
        int Error = WSAGetLastError();
        AllocConsole();
        freopen("CONOUT$", "w", stdout);
        std::cout << "The Error is: " << Error << std::endl;
    }
    *pSize = Size;
    char* isBuff;// = NULL;
    int PacketsReceived = 0;
    int PacketsLeft = Size;
    int ReceivedPackets = 0;
    while (PacketsReceived < Size)
    {
        if (ispchar == FALSE)
        {
            ReceivedPackets = recv(_Handle->si.Connections[_Handle->si.ConnectionCounter - 1], (char*)Buff + PacketsReceived, PacketsLeft, 0);

        }
        else
        {
            isBuff = new char[Size]; //I Think my problem is here//

            ReceivedPackets = recv(_Handle->si.Connections[_Handle->si.ConnectionCounter - 1], isBuff + PacketsReceived, PacketsLeft, 0);

        }
        if (ReceivedPackets == SOCKET_ERROR)
        {
            int Error = WSAGetLastError();
            if (Error != 10054)
            {
                if (Error == 10035  || Error == 6)
                {
                    ReceivedPackets == 0;
                }
                else
                {
                    AllocConsole();
                    freopen("CONOUT$", "w", stdout);
                    std::cout << "The Error is: " << Error << std::endl;
                    //MessageBox(NULL, (WCHAR*)WSAGetLastError(), NULL, NULL);
                    _getch();
                    //return NULL;
                    break;
                }
            }
        }

        PacketsReceived += ReceivedPackets;
        PacketsLeft -= ReceivedPackets;
    }
    return isBuff;
}

A: The data may require multiple recv calls to receive fully. When this happens, Receive_Full_Packet allocates a new buffer for every such call, promptly leaking all but one of them. What it returns to the caller is the last such allocation - a mostly uninitialized buffer full of random garbage, with the last chunk of data at the very end of it.
Move isBuff = new char[Size]; line outside the loop, place it right after the first recv call that retrieved the size.

A: Finally Figured it out. Turns out there was absolutely nothing wrong with the way i was sending the buffer. It was actually the CLSID. I ended up putting the GetEncoderClsid function in the receiving end. Works like butter.


text: Q: Rsession.exe not releasing RAM Running R program that requires a lot of RAM (Running in R studio).   After program finishes running, rsession.exe is not releasing the ram.  I have to close and restart R in order to release the RAM.  I have tried using gc() garbage collection but it does not fix the problem.  Any suggestions on ways to periodically free up the RAM without restarting would be greatly appreciated, Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to execute a file in windows using NodeJS? I installed Nodejs and I'm using it for the first time.  The API is a bit too generic.  The first example does not explain how to specify a file path.  I setup the testFile.js with the code:
var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type':
'text/plain'});
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at
http://127.0.0.1:8124/');

I verified node.js is correctly installed by typing "node <enter> 1 + 1" and got a response of "2".  Then I tried:
>node "C:\path\testNode.js"

This returns ... which is no different than passing an incorrect file
>node "C:\INCORRECTPATH\testNode.js"
Then I tried dropping the parenthesis, still no work.  Also tried doing a change directory before running "node" command.  Guess what!  Still no worky.  The error ... is super useful, but I just dunno how to fix it..?
What's the syntax?

A: UPDATE
<AnticlimacticConclusion>
Restarting the computer corrected the problem.
</AnticlimacticConclusion>
So node.js did install.  And it even gave results (remember in the OP 1 + 1 returns 2).  But, the PATH remained jacked up for whatever reason.   (Yes I tried a new instance of cmd).
(The rest of this post is old information for reference only)
What did not work
The commands did not function when I went to the command prompt via:
start > run > cmd > node C:\path\testNode.js
It also did not function with a shortcut I had in my start menu to an admin mode version of cmd which links to:
%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools\VsDevCmd.bat""
What worked
I ran a search on my PC and found a program entitled "Node.js command prompt".  The shortcut on my machine pointed to:
C:\Windows\System32\cmd.exe /k "C:\Program Files\nodejs\nodevars.bat"
When I run node commands with this batch file pre-loaded then everything works out.  E.G.
> node C:\path\testNode.js
returns Server running at http://127.0.0.1:8124/.  A picture says 1000 words.  Note the first line.

In other words, it appears this batch file is required.

A: It looks like you're executing the node command inside a node repl.
This would happen if you are working in the window that pops up when you click a "Node.js" icon in your start menu.
To execute it in the way you've tried, run it from a normal command prompt. i.e. hit windows-r, type cmd, press return, or find Command Prompt in your start menu.
You can also run an external node script from inside the node repl by requiring it.
 require("C:\\path\\testNode.js")

This will only work the first time as it is cached for subsequent require calls.


text:
Q: Python socket client always sending message So I have this server file which is ok, always is up for connections, after sending a message from the client, client connection closes. I want the client to be up again for sending a message (get input again). I don't want to start the client again (in my case it's odev1.py)
# server.py
import socket

HOST = socket.gethostname()
PORT = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
    server_socket.bind((HOST, PORT))
    server_socket.listen()

    while True:
        print('waiting for a connection')
        connection, client_address = server_socket.accept()
        try:
            print(f'{client_address[0]} has entered the chat\n')

            while True:
                data = connection.recv(1024)
                print(f'{client_address[0]} - {str(data, encoding="utf-8")}')
                if data:
                    print('sending data back to the client')
                    connection.sendall(data)
                else:
                    print('no data from', client_address[0])
                    break

        finally:
            print("Closing current connection")
            connection.close()

this is my client ->
# client.py
import sys
import socket

host = socket.gethostname()
port = 65432

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as e:
    print("Error creating socket: %s" % e)
    sys.exit(1)
# Second try-except block -- connect to given host/port

try:
    s.connect((host, port))
except socket.gaierror as e:
    print("Address-related error connecting to server: %s" % e)
    sys.exit(1)
except socket.error as e:
    print("Connection error: %s" % e)
    sys.exit(1)
# Third try-except block -- sending data
try:
    # NOTE: I want it to take input again
    # Send data
    message = input('write something: ')
    s.sendall(message.encode('utf-8'))
    print('sending {!r}'.format(message))

    # Look for the response
    amount_received = 0
    amount_expected = len(message)

    while amount_received < amount_expected:
        data = s.recv(1024)
        amount_received += len(data)
        print('received {!r}'.format(data))

finally:
    print('closing socket')
    s.close()

this is how it looks right now:


text:
Q: Exception when getting data from form Django When I try to perform the following calculation:
self.total * ((100 + self.tax) / 100)

I get:
unsupported operand type(s) for +: 'int' and 'tuple'

I get the value with:
offer = offer_form.save(commit=False)
offer.tax = offer_form.cleaned_data['tax'].value,

I thought .value is supposed to give me the value of the form, which in this case is a ChoiceField. I used to create the object like the following and it used to work:
offer = Offer(
    ...
    tax=offer_form.cleaned_data['tax_model'].value,
    ...
)

models.py
Tax field in offer:
tax = models.DecimalField(default=0, max_digits=5, decimal_places=2, validators=[MinValueValidator(0),MaxValueValidator(100)])

Tax object I select from ChoiceField:
value = models.DecimalField(max_digits=5, decimal_places=2, validators=[MinValueValidator(0),MaxValueValidator(100)])

When I print offer_form.cleaned_data['tax'].value this is what I get:
65.00

My question is: Why did it use to work when I used method Instance() and not when I attribute the value to the variable.
And also, how can I make it work?

A: You have an extra comma, here:
offer.tax = offer_form.cleaned_data['tax'].value,

which makes it a tuple..


text:
Q: How to set a NULL column value through an ADO query connected to a MySQL ODBC source in C++? Given a given MySQL table
DESC tabl_foo;
--------------------------------
Field            Type         Null    Key    Default    Extra
-----------------------------------------------------------------
fooId            varchar(15)  NO      PRI    NULL
FooDate          date         YES     MUL    NULL

I need to update FooDate for a given row. So I tried this code :
query->SQL->Add("UPDATE tbl_foo SET FooDate = :FooDate WHERE fooId = :id"):

// both arguments are AnsiString
query->Parameters->FindParam("id")->Value = FoodId;
query->Parameters->FindParam("FooDate")->Value = FooDate;

query->ExecSQL();

However, this fails

Incorrect date value: "" for folumn FooDate at row 1

It turns out that FooDate may be an empty string (or { data:NULL }), and MySQL does not like that. So, I tried setting Null() :
if (FooDate.IsEmpty())
   query->Parameters->FindParam("FooDate")->Value = Null();
else
   query->Parameters->FindParam("FooDate")->Value = FooDate;

But then I get this error :

Parameter object is improperly defined. Inconsistent or incomplete information was provided.

What should be the value to set for MySQL NULL?

A: To make the update the system needs to know the types of the parameters.  It can deduce the type from the variant you apply, and MySQL can do certain conversions for you, but it's always best to specify the data type.
So what you would need is something like:
  if((pParam=query->Parameters->FindParam("FooDate"))!=NULL)
  {
    pParam->DataType=ftDate;
    if(FooDate.IsEmpty())
    {
      pParam->Value=Null();
    }
    else
    {
      pParam->Value=FooDate;
    }
  }

You may want to look at keeping FooDate as a TDateTime, but you will need to detect NULL dates properly.


text:
Q: Building binutils - lfs - error while 'make' I'm going to build my own Linux from scratch, but I've got an error while running 'make' for binutils in chapter 5 I get some errors. The output of 'make' is here: http://pastebin.com/8aVz6jfd
There is output of version-check.sh
enedil@linux-from-scratch:~$ bash version-check.sh
bash, version 4.2.45(1)-release
/bin/sh -> /bin/dash
Binutils: (GNU Binutils for Ubuntu) 2.23.2
bison (GNU Bison) 2.5
/usr/bin/yacc -> /usr/bin/bison.yacc
bzip2,  Version 1.0.6, 6-Sept-2010.
Coreutils:  8.20
diff (GNU diffutils) 3.2
find (GNU findutils) 4.4.2
gawk: not an option: --version
/usr/bin/awk -> /usr/bin/mawk
gcc (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3
(Ubuntu EGLIBC 2.17-0ubuntu5) 2.17
grep (GNU grep) 2.14
gzip 1.5
Linux version 3.8.0-31-generic (buildd@panlong) (gcc version 4.7.3 (Ubuntu/Linaro 4.7.3-1ubuntu1) ) #46-Ubuntu SMP Tue Sep 10 20:03:44 UTC 2013
m4 (GNU M4) 1.4.16
GNU Make 3.81
patch 2.6.1
Perl version='5.14.2';
GNU sed version 4.2.1
tar (GNU tar) 1.26
s: line 33: makeinfo: command not found
Texinfo:
xz (XZ Utils) 5.1.0alpha
gcc compilation OK

My distro is Ubuntu 13.04.

A: The problem seems to be missing texinfo, which causes the build process to abort (search the log for lines of the form *** [directory_name] Error X). It also tells you, that you normally shouldn't need it, unless you modified sources for the info manuals. I assume this is in one of the bootstrapping parts of LFS, since otherwise you should have makeinfo available already.
Check what patches you have applied (if any) - they might have modified some of the documentation files thus triggering the rebuild. You may also try to disable manual building (the configure script might have an option for that).

A: You should have included pastebin (make output) info here. But, it does indicate a number of missing things in your binutils build;
checking for aclocal... no
checking for autoconf... no
checking for autoheader... no

And, the missing makeinfo.
sudo apt-get install autoconf automake autotools-dev

This will give you aclocal, autoconf, and autoheader as per AUTOTOOLS FAQ. Your make info package is carried by textinfo so installing that will solve that problem.
sudo apt-get install texinfo

After this, try again and post an update.


text:
Q: "TypeError: Error converting shape to a TensorShape: only size-1 arrays can be converted to Python scalars" when compiling LSTM neural network I am currently making an LSTM neural network to analyze the closing prices of stock data. I am getting an error which reads:
TypeError: Error converting shape to a TensorShape: only size-1 arrays can be converted to Python scalars.
when executing this code:
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
#take user input to replace stock to analyze
userInput = input('Stocks: \n')
days = int(input('how many time series to analyze? \n'))
#read data
data = pd.read_csv('Stocks/%s.us.txt' % userInput, usecols=[5], engine = 'python', skipfooter = 3)
#convert it into numpy array
dataSet = data.values
#scale the data into a range of 0, 1
scaling = MinMaxScaler(feature_range = (0,1))
#transform testing data to have 0 mean
dataSet = scaling.fit_transform(dataSet)
#splitting to testing and training data
trainData = int(len(dataSet) * 0.80)
testData = len(dataSet) - trainData
#time series data shaping
features = []
labels = []
for i in range(days, len(dataSet)):
    features.append(dataSet[i-days:i, 0])
    labels.append(dataSet[i, 0])
#convert features and labels to numpy arrays
features, labels = np.array(features), np.array(labels)
#building LSTM model
model = Sequential()
model.add(LSTM(1, input_shape=(1, dataSet)))
model.add(Dense(1))
model.compile(optimizer = 'adam', loss = 'mse')
model.fit(trainData, testData, batch_size = 32, epochs = 10)

In this post here it explains that this problem might arise from indexing the rows of the different dimensions rather than the lengths, but I do not see how this applies to my code, as I never index anything of that sort. I have tried looking in other posts but none of the solutions apply to my problem. It is also worth noting that the error traces back to line 143 of an Anaconda3 lib file, like so
File "C:\Users\me\Anaconda3\lib\site-packages\tensorflow\python\eager\execute.py", line 143, in make_shape

Why is this error showing up, and how can I fix it?


text:
Q: Rao Blackwell theorem on Bernoulli distribution I need help with the following Problem: Let $X_1,...,X_n$ be a random sample of iid random variables,
$X_i\sim Ber(p), p\in (0,1)$. We want to estimate $\theta = p^2$. It is known, that $\hat{\theta}(X_1,...,X_n)=\sum \limits_{i=1}^{n} X_i$ is complete and sufficient. Futhermore, it is easy to see, that the estimator $\tilde{\theta}=X_1X_2$ is unbiased.
We have to use the Rao-Blackwell theorem to find a better estimator $\theta^*=E[\tilde{\theta}|\hat{\theta}]$.
I would like where the mistake in the following idea is:
First, we obeserve that $\tilde{\theta}=X_1X_2\in\left\{0,1\right\}$ almost surely and
$\tilde{\theta}=1 \Leftrightarrow X_1=X_2=1$ . Then
$\theta^*=E[\tilde{\theta}|\hat{\theta}] = E[\tilde{\theta}|\hat{\theta}=k]=1\cdot P(\tilde{\theta}=1|\hat{\theta}=k)+0\cdot P(\tilde{\theta}=0|\hat{\theta}=k)=P(X_1=1,X_2=1|\sum \limits_{i=1}^{n} X_i=k) \\ =\frac{P(X_1=1,X_2=1,\sum \limits_{i=3}^{n} X_i=k-2)}{P(\sum \limits_{i=1}^{n} X_i=k)}=\frac{P(X_1=1)P(X_2=1)P(\sum \limits_{i=3}^{n} X_i=k-2)}{P(\sum \limits_{i=1}^{n} X_i=k)}=\frac{P(X_1=1)P(X_2=1)P(\sum \limits_{l=1}^{n-2} X_l=k-2)}{P(\sum \limits_{i=1}^{n} X_i=k)}=p^2\frac{\binom{n-2}{k-2}p^{k-2}(1-p)^{n-2-k+2}}{\binom{n}{k}p^k(1-p)^{n-k}}\\
=\frac{\binom{n-2}{k-2}}{\binom{n}{k}}=\frac{(n-2)!k!}{n!(k-2)!}=\frac{k(k-1)}{n(n-1)}$
I know there has to be a mistake somewhere since $\theta^*=E[\tilde{\theta}|\hat{\theta}]$ is not unbiased, but it should be.

A: The computation is fine. I think the problem is conceptual. $\theta^*=E[\tilde{\theta}|\hat{\theta}]$ is a random variable which is a function of $\hat{\theta}$, whose value when $\hat{\theta}=k$ is $E[\tilde{\theta}|\hat{\theta}=k] = \frac{k(k-1)}{n(n-1)}$.
Hence, to compute the expectation you should remember the formula $E[g(X)]=\sum_k g(k) P(X=k)$. Here $\hat{\theta}$ plays the role of $X$ and $g(k)=E[\tilde{\theta}|\hat{\theta}=k]$. Therefore:
$$E[\theta^*]=\sum_{k=2}^n E[\tilde{\theta}|\hat{\theta}=k] P(\hat{\theta}=k)= \sum_{k=2}^n \frac{\binom{n-2}{k-2}}{\binom{n}{k}} \binom{n}{k}p^k(1-p)^{n-k} = p^2\sum_{k=2}^n \binom{n-2}{k-2} p^{k-2}(1-p)^{n-2-(k-2)} = p^2,$$ as one would expect, since by the law of iterated expected values: $E[\theta^*]=E[E[\tilde{\theta}|\hat{\theta}]]=E[\tilde{\theta}]=p^2$.


text:
Q: socket.io emit message from one namespace to another I'm trying to emit a message from one namespace to another (on connection).
Bellow is some sample code with how I was trying to approach it.
[Server]
// Namespaces
var users_ns = io.of('/users');
var machines_ns = io.of('/machines');

// Attempt to receive the event on the socket
users_ns.on('connection', function(socket){
    socket.on('test', function(socket){
        console.log('socket test');
    });
});

// Attempt to receive the event on the namespace
users_ns.on('test', function(socket){
    console.log('namespace test');
});

// Emit an event to the 'users' namespace
machines_ns.on('connection', function(socket){
    users_ns.emit('test');
});

[Client1]
var socket = io('http://localhost/users');

[Client2]
var socket = io('http://localhost/machines');

Any idea why this doesn't work?

A: Your server code is correct, but some misunderstanding occurred.
[server]
// Namespaces
var users_ns = io.of('/users');
var machines_ns = io.of('/machines');

// Attempt to receive the event on the socket
users_ns.on('connection', function(socket){
    socket.on('test', function(){
        console.log('socket test');
    });
});

// Emit an event to the 'users' namespace
machines_ns.on('connection', function(socket){
    users_ns.emit('test');
});

When you are broadcasting to users_ns sockets, this events received in client side, not in server sides. So this is correct client side code
[Client1]
var socket = io('http://localhost/users');
socket.on('test',function(){ alert('broadcast received');});

[Client2]
var socket = io('http://localhost/machines');

when one socket connect to machine namespace, all clients connected to users namespace will raise 'broadcast received' alert.


text:
Q: How to set the first part of a split input to the second part (Python3) var1 = "plzHalp"
cmd = input("> ")
subcmd = cmd.split(" ")
if subcmd[0] == "set" and subcmd[1] in setL:
    secondOp = subcmd[1]
    cmdVar = subcmd[2]
    eval(subcmd[1]) = subcmd[2]
    print("[Set",secondOp,"==>",cmdVar)

What I want this to do, is assign the second part of the subcommand (subcmd[1]) and change a pre-made variable to the third part (subcmd[2]).
E.g. if the command is "set var1 fixedYay" then var1 would then be equal to "fixedYay".

A: If I understand your question correctly, you need to replace eval(subcmd[1]) with globals()[subcmd[1]]. See the below example and read up on the globals() and locals() functions.
C:\Users\nagul>python
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:16:59) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> var1='plzHalp'
>>> var1_str='var1'
>>> print(globals()[var1_str])
plzHalp
>>> globals()[var1_str]='fixedYay'
>>> print(var1)
fixedYay
>>>


text:
Q: How to trigger an UI action when the app is closed in React Native? Apologies if my question is already answered in any other ways. I am very new to react-native with no knowledge of android or java.
I am trying to make a video conferencing app with react native. I used Agora for video calling and linked it with socket.io and react-native-callkeep for real time experience.
Now i am stuck in a situation where i have to make the app functional when someone is calling and the app is ""Closed"". Something like Whatsapp. I thought of implementing Firebase Cloud Messaging for push notification. And though it will open the application in someway. But the application opens when user opens the notification.
Can anyone please help me with any of the following or better ideas:
1. Keep the socket io open even when app is closed
Or 2. Open my application with incoming push notification (Without Opening It)

Please avoid abstruct answers as i am very new in this sector. I really appreciate the help. Thank you.

A: I think the second method is the  way to go you can also look at this library called react-native-callkeep I think it fits your use-case as well.


text:
Q: for update record using sharepoint 2010 Timer job i want to know that how to update record in  MS sql server 2012 using SharePoint 2010 Timer job.Or how to call MS Sqlserver procedure using sharePoint timer job every hours.
Please help me any body,this is very urgent.

A: There are tons of resources online about how to create timer jobs for sharepoint like this one and also from Microsoft in the MSDN here
What you would have to do is to replace the content of the Execute method with your custom code to update the SQL database.
And in the EventReceiver that installs the Timer Job you should do an new SPHourlySchedule (that schedules the timer job to be executed hourly)
For an extremly detailed guide to how you can create and deploy Timer Jobs I would recommend this blogpost
As you can see, there are many steps involded, each probably already well documented both here on stackexchange and on different blogs. But I think that the last blogpost really teaches you the basics.
For more information about how to update the SQL database i recommend you to just google terms like "update SQL database from C#" or variants on the same theme.


text:
Q: Secure previously created API without token based authentication I am asked to maintain security for web-API(will be clarified in a minute), but the problem is I am not allowed to make any structural changes, that is using any kind of token-based or user-based authentication is not possible. I offered to use CORS, but both mobile and web application use the same service, so this is not an option as well. The bottom line is I want to make the service secure with minimal changes.

A: you could use a secret apiKey, and then for every api call you take the entire body of the request, add "- apiKey" at the end, and run it trough a sha1 encryption (or simmilar one way enryption) then you put the result as "checksum" in the header
on the serverend you do the same thing, take the body of the request, add "- apiKey" and run it trough the same oneway encryption, and hten compare the result to the checksum in the header of the resuest. if the strings matches you allow it, otherwise block the call.
this is not too much to implement, and it doesnt really change anything about the structure, but if this is too much "changes" so you are not allowed, then the only other option is using firewall to only allow certain ip addresses.

A: The token approach is advisable as there isn't much structural change. You need to add a middleware, where all the API calls hit, and there you perform a token validation. Orrr you could use cookies to secure your endpoints


text:
Q: Parse a log file and get entry data I have a big log file with multiple lines separated by new line. Each line entry stores four values.
If I am reading the log file and want to store this information, what data type/object should I use?
Example:

source1 destination1 result time
source2 destination1 result time
sources3 destination2 result time

The values are not unique between lines and they can repeat.
Can I declare a struct for each line with {source, destination, result, time} values and store the struct object in a List<T> for the entire file?

A: Yes, you can take the approach of creating your own specific class and making a List of that class.
Depending on how large your file is, you could do better by using a DataTable to do this:
var dt = new DataTable();
dt.Columns.Add(new DataColumn("Source", typeof(string)));
dt.Columns.Add(new DataColumn("Destination", typeof(string)));
dt.Columns.Add(new DataColumn("Result", typeof(string)));
dt.Columns.Add(new DataColumn("Timestamp", typeof(DateTime)));

var dr = dt.NewRow();
dr["Source"] = "DATA";
dr["Destination"] = "DATA";
dr["Result"] = "DATA";
dr["Timestamp"] = DateTime.Now;
dt.Rows.Add(dr);

A: Yes that is exactly what I would do.  If you don't have LINQ you can use generic List with a custom class of your own.
public class LogEntry
{
     private String _source = String.Empty;
     private String _destination = String.Empty;
     private String _result = String.Empty;
     private String _time = String.Empty;

     public String Source
     {
         get { return _source; }
         set { _source = value; }
     }

     public String Destination
     {
            get { return _source; }
            set { _source = value; }
     }

     public String Result
     {
         get { return _source; }
         set { _source = value; }
     }

     public String Time
     {
         get { return _source; }
         set { _source = value; }
     }

     public LogEntry()
     {
     }

     public LogEntry( String source, String destination, String result, String time )
     {
         _source = source;
         _destination = destination;
         _result = result;
         _time = time;
     }

    public LogEntry( String[] args )
    {
        _source = args[0];
        _destination = args[1];
        _result = args[2];
        _time = args[3];
    }
  }

You can then use a list like so:
 List<LogEntry> _logEntries = new List<LogEntry>();

I would read the each line from the file into a String and create a new LogEntry class passing in the result from a String.Split method call.  The code below is strictly psuedo code.
char[] splitter = new char[1];
splitter[0] = ' ';

while( readLines into String )
{
   _logEntries.Add( new LogEntry( String.Split( splitter ) ) );
}

This solution is extremely brittle and any change in the log file format will horribly break the code but it will work.  Also your breaking on white space so you better make sure that's what you really want to break on.

A: Roll your own class
public class LogEntry
{
    public string Source;
    public string Destination;
    public DateTime ResultTime;
}

You could then call Split() on each entry line, then parse each element of the String[] into your LogEntry objects.

A:         class YourType
        {
            public String Source { get; private set; }
            public String Destination { get; private set; }
            public String Resoult { get; private set; }
            public String Time { get; private set; }

            //or func returning bool and remove exception
            public YourType(String line)
            {
                var split = line.Split(' ');

                if (split.Length != 4)
                    throw new ArgumentException();

                Source = split[0];
                Destination = split[1];
                Resoult = split[2];
                Time = split[3];
            }

        }

        public Main()
        {
            String values =
 @"source1 destination1 result time
source2 destination1 result time
sources3 destination2 result time";

            var v = from line in values.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)
                    select new YourType(line);

            foreach (var it in v)
            {
                Console.WriteLine(it.Source);
            }

        }


text:
Q: Using git, how do I merge the main (upstream) branch into a topic branch but see the differences as if I merged the topic branch into the main branch? Using git, how do I merge the main (upstream) branch into a topic branch but see the differences as if I merged the topic branch into the main branch?
It is our habit, when a topic branch is ready, to do the merge into the main branch (with git) as a two-stage process:

*

*Merge the main branch into the topic branch.  Push the topic branch, which triggers tests on an external test system to check that the application functionality still works as expected.

*Merge the topic branch into the main branch.  Push the main branch, which triggers the tests again.

The advantage of this is that if there are any problems with the merged version, then they are likely to show up already in the topic branch where they don't bother the other developers yet.
The disadvantage is that when merging the main branch into the topic branch, then the reported differences are those introduced into the main branch by other developers.  There can be very many of them, and I wasn't involved in making any of them, so it is difficult for me to verify that the merge did not make any mistakes.
If instead I immediately merge the topic branch into the main branch, without first merging the main branch into the topic branch, then the reported differences are only those introduced by me for the topic branch.  Those are fewer in number, and I am intimately familiar with them, so it is a lot easier for me to verify that the merge did not make any mistakes, but then we don't get the advantage of first testing the combination in the context of the topic branch.
I cannot run the tests locally before pushing, so it is not an option to merge the topic branch into the main branch, then test, resolve any problems, and only then push the main branch.
Assuming that the merges go well, it doesn't matter for the final code whether I merge the topic branch into the main branch or the main branch into the topic branch: In both cases I end up with the same code, but associated with different branches.
What I would like is to have the merged code in the topic branch, but to see the differences as if I merged the topic branch into the main branch.  What is the most convenient way to do that?
The clunky way is to have two local copies of the repository, with the main branch checked out in one of them and the topic branch checked out in the other one.  Merge the topic branch into the main branch in the first repository copy (see only my own diffs -- excellent!), then copy the source code but not the .git directory to the other repository copy, and commit into the topic branch.  This is cumbersome and wasteful of disk space.
I also tried merging the topic branch into the main branch (but not pushing!) and then doing a hard reset of the topic branch onto the merge commit in the main branch, but that merely moves the topic branch marker, losing the connection with the previous commits in the topic branch.
EDIT: I moved my own solutions from here to an Answer, 2019-11-29, at the suggestion of a comment.

A: FIRST PARTIAL SOLUTION, ADDED 2018-01-19
I've found a partial solution to my problem. When I'm in the middle of merging the main branch into the topic branch, then
git diff --stat MERGE_HEAD...

(note the three dots at the end) shows how many lines in which files have changed in the topic branch since the most recent common ancestor with the main branch. Those are the files that would be reported as changed if I instead merged the topic branch into the main branch; those are the files that I changed.
In my merge of the main branch into the topic branch, I can ignore all files that aren't in that list from git diff. Those files to be ignored weren't changed by me, so I do not need to double-check them for merge problems that git cannot detect.
SECOND PARTIAL SOLUTION, ADDED 2018-01-23
This solution is based on a comment that Steve added below this question, with some additions.

*

*Make a new temporary branch on master and merge topic branch into this. Change the commit message to something like "Merge main branch into topic branch", similar to what it would be if you merged the main branch into the topic branch directly. (The default commit message mentions the temporary branch, which we're going to delete shortly, so it will be confusing if the commit message refers to it. Also, the effective merge direction is going to be the reverse of what the default commit message says.)

*Switch to the topic branch and merge (fast-forward) the temporary branch into this. Delete the temporary branch. Then push the topic branch to trigger the tests.

*merge (probably with --no-ff?) the now tested topic branch into master.

THIRD PARTIAL SOLUTION
And a colleague of mine suggested a third way to reduce the pain: Use a worktree to get a cheap second copy of the main branch without having to clone the entire repository again. Assuming that you're in the main repository directory "repo" with the topic branch checked out:
# create worktree and check out main-branch in it:
git worktree add ../repo-worktree main-branch
cd ../repo-worktree
git merge topic-branch
# (resolve any merge conflicts)
# copy changed files to the main repository:
cp <changed-files> ../repo
cd ../repo    # go to main repository
git add -u    # stage copied files (no new ones!)
git commit -m "merged main branch into topic branch"

# when you don't need the worktree anymore, then
rm -rf ../repo-worktree  # removes worktree
git worktree prune       # removes obsolete worktree administrative files


text:
Q: move config files with fpm I'm using fpm to build a .deb package from a Golang program. The program uses a .ini file to run, and there's a .service file in order to activate the program as a systemd service.
I'm building the package as follows:
mkdir -p $BUILD_ARTIFACTS_DIR && cp $BINARY_NAME $BUILD_ARTIFACTS_DIR
if which fpm; then
    fpm --description '${DEB_PACKAGE_DESCRIPTION}' -s dir -t deb -n myprogram \
      --config-files myprogram.ini --config-files myprogram.service --version $VERSION_STRING \
      --deb-user root --deb-group root \
      --deb-systemd myprogram.service \
      $BINARY_NAME=/usr/bin/ \
      myprogram.ini=/etc/myprogram/ \
      myprogram.service=/etc/systemd/system/
      -p ${DEB_PACKAGE_NAME}-${VERSION_STRING}.deb \

If I run dpkg -c ./myprogram_1.0-d71d9a0_amd64.deb I have:
drwxrwxr-x 0/0               0 2021-09-13 04:45 ./
drwxr-xr-x 0/0               0 2021-09-13 04:45 ./usr/
drwxr-xr-x 0/0               0 2021-09-13 04:45 ./usr/bin/
-rwxrwxr-x 0/0        22287262 2021-09-13 04:45 ./usr/bin/myprogram
drwxr-xr-x 0/0               0 2021-09-13 04:45 ./usr/share/
drwxr-xr-x 0/0               0 2021-09-13 04:45 ./usr/share/doc/
drwxr-xr-x 0/0               0 2021-09-13 04:45 ./usr/share/doc/myprogram/
-rw-r--r-- 0/0             144 2021-09-13 04:45 ./usr/share/doc/myprogram/changelog.gz
-rw-rw-r-- 0/0             137 2021-09-13 04:45 ./myprogram.ini
drwxr-xr-x 0/0               0 2021-09-13 04:45 ./lib/
drwxr-xr-x 0/0               0 2021-09-13 04:45 ./lib/systemd/
drwxr-xr-x 0/0               0 2021-09-13 04:45 ./lib/systemd/system/
-rw-r--r-- 0/0             252 2021-09-13 04:45 ./lib/systemd/system/myprogram.service
-rw-rw-r-- 0/0             252 2021-09-13 04:45 ./myprogram.service
drwxr-xr-x 0/0               0 2021-09-13 04:45 ./etc/
drwxr-xr-x 0/0               0 2021-09-13 04:45 ./etc/systemd/
drwxr-xr-x 0/0               0 2021-09-13 04:45 ./etc/systemd/system/
-rw-rw-r-- 0/0             252 2021-08-20 04:00 ./etc/systemd/system/myprogram.service
drwxr-xr-x 0/0               0 2021-09-13 04:45 ./etc/myprogram/
-rw-rw-r-- 0/0             137 2021-08-20 03:52 ./etc/myprogram/myprogram.ini`

What I want is that during installation with sudo dpkg -i mypackage.deb the file myprogram.ini goes to /etc/myprogram/ and myprogram.service to /etc/systemd/system/. How can I accomplish that?

A: You were close to the solution but you missed the file names in the end of the path.
You currently have two options:

*

*use an input file where you list all your files. In this case, you specify the option --inputs myfiles.txt

*specify the files in the command line (almost) as you have done.

Option 1:
the file myfiles.txt content looks as follows:

./myprogram.ini=/etc/myprogram/myprogram.ini
./myprogram.service=/etc/systemd/system/myprogram.service

Option 2:
if you don't have too many files, you can append the files to the command line, but it has to be done in the following way:
... [stripped code]
$BINARY_NAME=/usr/bin/ \
      ./myprogram.ini=/etc/myprogram/myprogram.ini \
      ./myprogram.service=/etc/systemd/system/myprogram.service
      -p ${DEB_PACKAGE_NAME}-${VERSION_STRING}.deb


text:
Q: Characteristic polynomials of matrices Good day!
Given a characteristic polynomial $P$ of matrix $A$ I need to show that the characteristic polynomial $O$ of $A^2$ can't have more different real roots than $P$.
I know that the characteristic polynomial for both cases can be calculated like this:
$P = |A - \lambda I| = 0$
$O = |A^2 - \lambda^2 I| = 0$
But in a general case with $n*n$ matrices they become way too complicated.
Can anyone guide me in the right direction?
Thanks!

A: This is false, for somewhat trivial reasons. Let $A$ be a matrix with eigen values $\lambda_1,\dots,\lambda_n$ then note that the eigenvalues of $A^2$ are
$\lambda_1^2,\dots,\lambda_n^2$ since if $v_i$ is an eigenvector of $\lambda_i$ then
$$A^2v_i=A(\lambda v_i)=\lambda Av_i=\lambda^2v_i.$$
For instance if the eigenvalues are purely imaginary the number of real eigenvalues increases. To take an example from the comments
$$A=\begin{pmatrix}0 & -1 \\ 1 & 0\end{pmatrix}$$
then $\mathsf{char}(A)=x^2+1$ which has imaginary roots $\pm i$ but $\mathsf{char}(A^2)=(x+1)^2$ has real repeated root $-1$.
Are there some more conditions on your matrix perhaps?

A: Since the roots of these polynomials are eigenvalues, let's just think in terms of eigenvalues.
The eigenvalues of $A^2$ are just the eigenvalues of $A$, squared (right? It's tempting to believe, and scribbling on a napkin made it seem so but I could be overlooking something silly).
In that case, the real eigenvalues of $A$ would stay real after squaring, and some complex eigenvalues might become real after squaring.
This would show that $A^2$ has at least as many real eigenvalues as $A$. (This is not the original question, but it seems like this might have been the intended question.)


text:
Q: Numpy array index out of range with Genetic Algorithm I wrote a script to generate an image based from a source, with randomized ellipses using genetic algorithms. I keep receiving this error (the length of seeds is different every time, this is just an example) after running it:
Output:
[[ 42 166  88  21]
 [ 25 201 321 227]
 [ 21  78 153  53]
 [  5  74 231  20]
 [  3  96 394  15]
 [ 20 239  28 244]
 [ 33   6  94  27]
 [  4 253 193 113]
 [ 10 139 323  16]
 [ 31   9  97 117]
 [ 23 273 181 214]
 [ 24 286 361 231]
 [ 33   2 187  47]
 [ 35  98 133 177]
 [ 10 307 136  76]
 [ 35 132 269 161]
 [ 25 147  11   2]
 [ 36 141 338 100]
 [ 23 163 430  37]
 [ 17 285 216  53]
 [ 18   2 181 119]
 [ 43 199 117 253]] 22

Traceback (most recent call last):
  File "E:/genetic image/genetic_image.py", line 106, in <module>
    generate()
  File "E:/genetic image/genetic_image.py", line 93, in generate
    params, test_image = seed_test(seeds[:random.randint(0, reproduce)])
  File "E:/genetic image/genetic_image.py", line 41, in seed_test
    r = int(seeds[i, 0] + random.random() - 0.5)
IndexError: index (22) out of range (0<=index<22) in dimension 0

Here is the script:
import random
import copy
import numpy
from PIL import Image, ImageDraw

optimal = Image.open("charles-darwin_large.jpg")
optimal = optimal.convert("RGB")
size = width, height = optimal.size
population = 2
generations = 5000
elements = int(1e3)
reproduce = height / 10
max_radius = height / 10
diff_max = height / 10

def random_test():
    test_elements = []
    test_image = Image.new("RGB", (width, height), "white")
    draw = ImageDraw.Draw(test_image)

    for i in range(elements):
        r = int(max_radius * random.random())
        x, y = random.randint(0, width), random.randint(0, height)
        color_value = random.randint(0, 255)
        color = (color_value, color_value, color_value)

        test_elements.append([r, x, y, color_value])

        draw.ellipse((x - r, y - r, x + r, y + r), fill = color)

    return test_elements, test_image

def seed_test(seeds):
    test_elements = []
    test_image = Image.new("RGB", (width, height), "white")
    draw = ImageDraw.Draw(test_image)

    print seeds, len(seeds)

    for i in range(elements):
        r = int(seeds[i, 0] + random.random() - 0.5)
        x, y = seeds[i, 1] + random.randint(-5, 5), seeds[i, 2] + random.randint(-5, 5)
        color_value = seeds[i, 3] + random.randint(-5, 5)
        color = (color_value, color_value, color_value)

        test_elements.append([r, x, y, color_value])

        draw.ellipse((x - r, y - r, x + r, y + r), fill = color)

    return test_elements, test_image

def grayscale(image):
    return image.convert("LA")

def fitness(source, generated):
    fitness = 0
    for i in range(height - 1):
        for j in range(width - 1):

            r1, g1, b1 = source.getpixel((j, i))
            r2, g2, b2 = generated.getpixel((j, i))

            deltaRed = r1 - r2
            deltaGreen = g1 - g2
            deltaBlue = b1 - b2

            pixelFitness = deltaRed ** 2 + deltaGreen ** 2 + deltaBlue ** 2

            fitness += pixelFitness

    return fitness

def generate():
    samples = []
    scores = [0] * reproduce

    for i in range(population):
        params, test_image = random_test()
        fitness_score = fitness(optimal, test_image)

        if fitness_score > scores[-1]:
            scores[-1] = fitness_score
            scores = sorted(scores)

            samples.append(params)

    for generation in range(generations):
        seeds = numpy.array(copy.deepcopy(samples))[0]
        samples = []
        scores = [0] * reproduce

        for i in range(population):
            params, test_image = seed_test(seeds[:random.randint(0, reproduce)])
            fitness_score = fitness(optimal, test_image)

            if fitness_score > scores[-1]:
                scores[-1] = fitness_score
                scores = sorted(scores)

                samples.append(params)

        for each in samples:
            print each

if __name__ == "__main__":
    generate()

The source image can be found here.
What does the error mean?

A: you have 1000 elements (1e3) and 22 seeds (indexes 0 - 21), so when you try to get the item seeds[22, 0] in following loop, the index is out of range:
for i in range(elements):
    r = int(seeds[i, 0] ...

I suspect tha what you need to do is:
for i in range(len(seeds)):
    ...

A: In your code you are setting the global elements to 100, why not set it to len(elements)? At present if there are less that 100 seed valuers the algorithm id guaranteed to fail in the way you describe.
A problem with your current solution attempt is the fact that much of the "coupling" between the various functions takes place through global variables. In Python we like to say "implicit is better than explicit", and best software engineering practice would be to pass the data explicitly to those functions that use it.


text:
Q: Maven resolver at Jenkins job with Arquillian tests (Issue when creating WAR by ShrinkWrap) I'm trying to do a little modular project that uses Arquillian tests remotely launched on WildFly 8.1.0 server. Everything is wirking, but only when i launch tests from my IDE. When Jenkins tries to do the same, it fails with error:
SEVERE [domain.testframework.logic.UserPersistTest] : org.jboss.shrinkwrap.resolver.api.Invokable$InvocationException: Unable to invoke onlyOne([Ljava.lang.Class;@5d79653) on object org.jboss.shrinkwrap.resolver.spi.loader.ServiceRegistry with parameters [Ljava.lang.Object;@cce2624
    at org.jboss.shrinkwrap.resolver.api.Invokable.invokeMethod(Invokable.java:108) [shrinkwrap-resolver-api-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.api.ResolverSystemFactory.createFromUserView(ResolverSystemFactory.java:91) [shrinkwrap-resolver-api-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.api.ResolverSystemFactory.createFromUserView(ResolverSystemFactory.java:53) [shrinkwrap-resolver-api-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.api.Resolvers.use(Resolvers.java:68) [shrinkwrap-resolver-api-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.api.maven.Maven.resolver(Maven.java:36) [shrinkwrap-resolver-api-maven-2.1.1.jar:2.1.1]
    at domain.testframework.logic.UserPersistTest.createDeployment(UserPersistTest.java:61) [:]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_13]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_13]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_13]
    at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_13]
    at org.jboss.arquillian.container.test.impl.client.deployment.AnnotationDeploymentScenarioGenerator.invoke(AnnotationDeploymentScenarioGenerator.java:177) [arquillian-container-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.container.test.impl.client.deployment.AnnotationDeploymentScenarioGenerator.generateDeployment(AnnotationDeploymentScenarioGenerator.java:103) [arquillian-container-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.container.test.impl.client.deployment.AnnotationDeploymentScenarioGenerator.generate(AnnotationDeploymentScenarioGenerator.java:64) [arquillian-container-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.container.test.impl.client.deployment.DeploymentGenerator.generateDeployment(DeploymentGenerator.java:79) [arquillian-container-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_13]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_13]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_13]
    at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_13]
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:116) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:67) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.container.test.impl.client.ContainerEventController.execute(ContainerEventController.java:100) [arquillian-container-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_13]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_13]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_13]
    at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_13]
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:84) [arquillian-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_13]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_13]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_13]
    at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_13]
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:65) [arquillian-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_13]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_13]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_13]
    at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_13]
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:116) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.beforeClass(EventTestRunnerAdaptor.java:80) [arquillian-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:190) [arquillian-junit-core-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:345) [arquillian-junit-core-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:49) [arquillian-junit-core-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:207) [arquillian-junit-core-1.1.5.Final.jar:1.1.5.Final]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309) [junit-4.11.jar:]
    at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:155) [arquillian-junit-core-1.1.5.Final.jar:1.1.5.Final]
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264) [surefire-junit4-2.17.jar:2.17]
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153) [surefire-junit4-2.17.jar:2.17]
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124) [surefire-junit4-2.17.jar:2.17]
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200) [surefire-booter-2.17.jar:2.17]
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153) [surefire-booter-2.17.jar:2.17]
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103) [surefire-booter-2.17.jar:2.17]
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_13]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_13]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_13]
    at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_13]
    at org.jboss.shrinkwrap.resolver.api.Invokable.invokeMethod(Invokable.java:100) [shrinkwrap-resolver-api-2.1.1.jar:2.1.1]
    ... 60 more
Caused by: java.lang.RuntimeException: Could not create new service instance
    at org.jboss.shrinkwrap.resolver.spi.loader.SpiServiceLoader.createInstance(SpiServiceLoader.java:248) [shrinkwrap-resolver-spi-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.spi.loader.SpiServiceLoader.createInstances(SpiServiceLoader.java:208) [shrinkwrap-resolver-spi-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.spi.loader.SpiServiceLoader.all(SpiServiceLoader.java:79) [shrinkwrap-resolver-spi-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.spi.loader.SpiServiceLoader.onlyOne(SpiServiceLoader.java:85) [shrinkwrap-resolver-spi-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.spi.loader.ServiceRegistry.onlyOne(ServiceRegistry.java:117) [shrinkwrap-resolver-spi-2.1.1.jar:2.1.1]
    ... 65 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) [rt.jar:1.7.0_13]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) [rt.jar:1.7.0_13]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) [rt.jar:1.7.0_13]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525) [rt.jar:1.7.0_13]
    at org.jboss.shrinkwrap.resolver.spi.loader.SpiServiceLoader.createInstance(SpiServiceLoader.java:244) [shrinkwrap-resolver-spi-2.1.1.jar:2.1.1]
    ... 69 more
Caused by: org.jboss.shrinkwrap.resolver.api.InvalidConfigurationFileException: Unable to get security configuration from /root/.m2/settings-security.xml. Please define path to the settings-security.xml file via -Dorg.apache.maven.security-settings, or put it the the default location defined by Maven.
    at org.jboss.shrinkwrap.resolver.impl.maven.internal.decrypt.MavenSecurityDispatcher.getMaster(MavenSecurityDispatcher.java:171) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.internal.decrypt.MavenSecurityDispatcher.decrypt(MavenSecurityDispatcher.java:96) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.internal.decrypt.MavenSettingsDecrypter.decrypt(MavenSettingsDecrypter.java:92) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.internal.decrypt.MavenSettingsDecrypter.decrypt(MavenSettingsDecrypter.java:60) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.bootstrap.MavenSettingsBuilder.decryptPasswords(MavenSettingsBuilder.java:223) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.bootstrap.MavenSettingsBuilder.buildSettings(MavenSettingsBuilder.java:186) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.bootstrap.MavenSettingsBuilder.buildDefaultSettings(MavenSettingsBuilder.java:113) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.MavenWorkingSessionImpl.<init>(MavenWorkingSessionImpl.java:136) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.MavenResolverSystemImpl.<init>(MavenResolverSystemImpl.java:44) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    ... 74 more

@Deployment method
@Deployment
    public static WebArchive createDeployment() {
        File pom = new File("pom.xml");
        LOG.info("---->>" + pom);

        File[] libs = null;
        try {
            libs = Maven.resolver().loadPomFromFile(pom)
                    .importRuntimeDependencies().resolve().withTransitivity().asFile();
        } catch (Throwable exception) {
            LOG.log(Level.SEVERE, "", exception);
        }
        LOG.info("LIBS RESOLVED: " + libs.length);
        for (File lib : libs) {
            System.out.println(lib);
        }
        WebArchive archive = ShrinkWrap.create(WebArchive.class, "ShrinkWrap-arquillian-test.war")
                .addAsWebInfResource("web.xml")
                .addClass(User.class)
                .addAsResource("test-persistence.xml", "META-INF/persistence.xml")
                .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
                .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");

        for (File lib : libs) {
            if (!lib.toString().contains("test-framework-data")) {
                archive.addAsLibrary(lib);
            }
        }
    }

any idea why this is happening?
my parent POM
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>domain</groupId>
    <artifactId>test-framework-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>
    <modules>
        <module>test-framework-web</module>
        <module>test-framework-logic</module>
        <module>test-framework-data</module>
        <module>test-framework-ear</module>
    </modules>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java-version>1.7</java-version>
        <!--Wersje pluginów-->
        <ejb-plugin-version>2.3</ejb-plugin-version>
        <war-plugin-version>2.4</war-plugin-version>
        <ear-plugin-version>2.9</ear-plugin-version>
        <compiler-plugin-version>3.1</compiler-plugin-version>
        <maven-dependency-plugin-version>2.8</maven-dependency-plugin-version>
        <!--Wersje zależności-->
        <javaee-api-version>7.0</javaee-api-version>
        <shrinkwrap.bom-version>2.1.1</shrinkwrap.bom-version>
        <postgreslq.version>9.1-901-1.jdbc4</postgreslq.version>
        <!--Wersja EJB-->
        <ejb-spec-version>3.2</ejb-spec-version>
        <!--Wersje środowiska testowego-->
        <surefire-plugin-version>2.17</surefire-plugin-version>
        <junit-version>4.11</junit-version>
        <arquillian-version>1.1.5.Final</arquillian-version>
        <wildfly-version>8.1.0.Final</wildfly-version>
        <arquillian-wildfly-version>8.1.0.Final</arquillian-wildfly-version>
        <arquillian-transaction-version>1.0.1.Final</arquillian-transaction-version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>javax</groupId>
                <artifactId>javaee-api</artifactId>
                <version>${javaee-api-version}</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit-version}</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.shrinkwrap.resolver</groupId>
                <artifactId>shrinkwrap-resolver-bom</artifactId>
                <version>${shrinkwrap.bom-version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.jboss.shrinkwrap.resolver</groupId>
                <artifactId>shrinkwrap-resolver-depchain</artifactId>
                <version>${shrinkwrap.bom-version}</version>
                <type>pom</type>
            </dependency>
            <dependency>
                <groupId>org.jboss.arquillian.extension</groupId>
                <artifactId>arquillian-transaction-bom</artifactId>
                <version>${arquillian-transaction-version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.wildfly</groupId>
                <artifactId>wildfly-arquillian-container-remote</artifactId>
                <version>8.1.0.Final</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.jboss.arquillian</groupId>
                <artifactId>arquillian-bom</artifactId>
                <version>${arquillian-version}</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>

            <dependency>
                <groupId>postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <version>${postgreslq.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-ear-plugin</artifactId>
                    <version>${ear-plugin-version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <version>${maven-dependency-plugin-version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>${surefire-plugin-version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>${compiler-plugin-version}</version>
                    <configuration>
                        <source>${java-version}</source>
                        <target>${java-version}</target>
                        <encoding>${project.build.sourceEncoding}</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-ejb-plugin</artifactId>
                    <version>${ejb-plugin-version}</version>
                    <configuration>
                        <ejbVersion>${ejb-spec-version}</ejbVersion>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>${war-plugin-version}</version>
                    <configuration>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                        <packagingExcludes>WEB-INF/lib/*.jar</packagingExcludes>
                        <archive>
                            <manifest>
                                <addClasspath>true</addClasspath>
                                <classpathPrefix>lib/</classpathPrefix>
                            </manifest>
                        </archive>
                        <webResources>
                            <resource>
                                <filtering>true</filtering>
                                <directory>src/main/webapp</directory>
                                <includes>
                                    <include>**/web.xml</include>
                                </includes>
                            </resource>
                        </webResources>
                    </configuration>
                </plugin>

            </plugins>
        </pluginManagement>
    </build>
    <name>test-framework</name>
</project>

A: Solution to this problem was a bit trivial.
Problem was with the settings.xml for maven repository. I have local repository with credentials like <password>{123}abc</password>.
Maven.resolver() requires modification to <password>\{123\}abc</password> otherwise it will look for file 'settings-security.xml'. I've modified local copy of this file, however on server it was not changed.


text:
Q: Access web camera from Excel web add-in I am using Excel web add-in and would like to access images from a user's web camera.
I cannot get access to the web camera through normal html5 in Excel. Neither through old school flash.
Perhaps the user can take photos outside of office, that gets stored in a local folder, and my Excel Addin, can look in that folder every second to see if a file is added?
Any suggestions on how to get access to a local folder?

A: Since OfficeJs runs within a web container, it doesn't have access to the local drive or network ports. If this is for personal automation, you could spin-up a web server, such as node server, and expose an API that add-in can interface with. The function of the server web would be to act as a file server and serve the file content over HTTP to the add-in abstracting the storage tier.
If this is a production class add-in, then it is better to store the file on a cloud storage service that offers API level access to the file (such as OneDrive).


text:
Q: What does "costly" mean in terms of software operations? What is meant by Operation is costly or the resource is costly in-terms of Software. When i come across with some documents they mentioned something like Opening a file every-time is a Costly Operation. I can have more examples like this (Database connection is a costly operation, Thread pool is a cheaper one, etc..). At what basis it decided whether the task or operation is costly or cheaper? When we calculating this what the constraints to consider? Is based on the Time also?
Note : I already checked in the net with this but i didn't get any good explanation. If you found kindly share with me and i can close this..

A: Expensive or Costly operations are those which cause a lot of resources to be used, such as the CPU, Disk Drive(s) or Memory
For example, creating an integer variable in code is not a costly or expensive operation
By contrast, creating a connection to a remote server that hosts a relational database, querying several tables and returning a large results set before iterating over it while remaining connected to the data source would be (relatively) expensive or costly, as opposed to my first example with the Integer.
In order to build scalable, fast applications you would generally want to minimize the frequency of performing these costly/expensive actions, applying techniques of optimisation, caching, parallelism (etc) where they are essential to the operation of the software.
To get a degree of accuracy and some actual numbers on what is 'expensive' and what is 'cheap' in your application, you would employ some sort of profiling or analysis tool. For JavaScript, there is ySlow - for .NET applications, dotTrace - I'd be certain that whatever the platform, a similar solution exists. It's then down to someone to comprehend the output, which is probably the most important part!

A: Running time, memory use or bandwidth consumption are the most typical interpretations of "cost". Also consider that it may apply to cost in development time.

A: I'll try explain through some examples:
If you need to edit two field in each row of a Database, if you do it one field at a time that's gonna be close to twice the time as if it was properly done both at same time.
This extra time was not only your waste of time, but also a connection opened longer then needed, memory occupied longer then needed and at the end of the day, your eficience goes down the drain.
When you start scalling, very small amount of time wasted grows into a very big waste of Company resources.

A: It is almost certainly talking about a time penalty to perform that kind of input / output. Lots of memory shuffling (copying of objects created from classes with lots of members) is another time waster (pass by reference helps eliminate a lot of this).

A: Usually costly means, in a very simplified way, that it'll take much longer then an operation on memory.
For instance, accessing a File in your file system and reading each line takes much longer then simply iterating over a list of the same size in memory.
The same can be said about database operations, they take much longer then in-memory operations, and so some caution should be used not to abuse these operations.
This is, I repeat, a very simplistic explanation. Exactly what costly means depends on your particular context, the number of operations you're performing, and the overall architecture of the system.


text:
Q: passcode unique word generation I'm looking to use a single passcode string, rather than the email/pass combo that most sites are using to authenticate users. I know if they lose their passcode (unless there are forget questions) that the account will become inactive, but I want the site to be completely anonymous and I don't want to store any data in the db that can link back to an actual person.
That said, can you share any methods (or point to current examples) on how to randomly generate English words with numbers to create a passcode (similar to say: taco_eat3R, nacho_P0tatoes, etc...)?

A: If you insist on using a dictionary, then you will need long passphrases (not passwords) to defeat brute force.  Diceware uses six or more words from a 7776 word dictionary, not all of which are English words.
ETA: the Diceware 8k wordlist is better suited for computer generated passphrases.
Also be sure to use a cryptogrphic standard RNG to pick the words from the dictionary.

A: Generation:

*

*Store a table of English words

*Randomly combo two of the words together (use regex to add numerals)

*Cross-reference it with existing users (to avoid duplication)


text:
Q: How can I use a mod in an array using numpy Let's say I have an array
a = ([6,8,10,13,15,18,21])

I have another array
b= ([2,5])

I want to return an array which gives me nonzero values of a%b. If any value in a mod any value in b equals zero, I don't want to return it.
c = ([13,21])

Using numpy.mod(a,b) returns

ValueError: operands could not be broadcast together with shapes

How can I execute this?

A: The problem refers to the fact that numpy cannot apply the np.mod operation on the arrays with the given shape, one solution is to reshape, for example:
import numpy as np

a = np.array([6, 8, 10, 13, 15, 18, 21]).reshape((-1, 1))
b = np.array([2, 5])

print(a[np.mod(a, b).all(1)].reshape(-1))

Output
[13 21]

Note that you need to reshape back to obtain the requested output. The best solution is the one proposed by @PaulPanzer:
import numpy as np

a = np.array([6, 8, 10, 13, 15, 18, 21])
b = np.array([2, 5])

print(a[np.mod.outer(a, b).all(1)])

Output
[13 21]

Further

*

*On numpy broadcasting see 1 and 2.

*On outer.


text:
Q: What happens with my iCloud data after leaving family sharing? What happens with my iCloud data after leaving family sharing?
Eg I will add 50gb of data and then I will be kicked out but not all the data is on my iPhone.

A: This Apple Support document answers your query:

*

*Share an iCloud storage plan with your family

If your family stops sharing storage or you leave Family Sharing
If you leave a family that shares an iCloud storage plan and you're using more than 5GB of storage, you have 28 days to buy your own plan.
If you choose not to buy your own plan and the content that you're storing in iCloud exceeds your available storage, new photos and videos won't upload to iCloud Photos, files will no longer upload in iCloud Drive, and your iOS devices will stop backing up.

i.e., you will have 28 days of grace period to get a separate plan and keep access to your data.


text:
Q: unable to see Task tracker and Jobtracker after Hadoop single node installation 2.5.1 Iam new to Hadoop 2.5.1. As i have already installed Hadoop 1.0.4 previously, i thought installation process would be same so followed following tutorial.
http://www.michael-noll.com/tutorials/running-hadoop-on-ubuntu-linux-single-node-cluster/
Every thing was fine, even i have given these settings in core-site.xml
<name>fs.default.name</name>

  <value>hdfs://localhost:54310</value>

But i have seen in several sites this value as 9000.
And also changes in yarn.xml.
Still everything works fine when i run a mapreduce job. But my question is
when i run command jps it gives me this output..
hduser@secondmaster:~$ jps

5178 ResourceManager

5038 SecondaryNameNode

4863 DataNode

5301 NodeManager

4719 NameNode

6683 Jps

I dont see task tracker and job tracker in jps. Where are these demons running.
And without these deamons how am i able to run Mapreduce job.
Thanks,
Sreelatha K.

A: From hadoop version hadoop 2.0 onwards, default processing framework has been changed to YARN from Classic Mapreduce. You are using YARN, where you cannot see Jobtracker, Tasker in YARN. Jobtracker and Tasktracker is replaced by Resource manager and Nodemanager respectively in YARN.
But still you have an option to use Classic Mapreduce framework instead of YARN.

A: In Hadoop 2 there is an alternative method to run MapReduce jobs, called YARN. Since you have made changes in yarn.xml, MapReduce processing happens using YARN, not using the traditional MapReduce framework. That's probably be the reason why you don't see TaskTracker and JobTracker listed after executing the jps command. Note that ResourceManager and NodeManager are the daemons for YARN.

A: YARN is next generation of Resource Manager who can able to integrate with Apache spark, storm and many more tools you can use to write map-reduce jobs


text:
Q: Copy Cell Color and Send in EMAIL Body Column G has been set with conditional formatting.If less than 0.95, no highlight; if between 0.95 and 1.0, highlighted in green; if over 1.0, highlighted in red.
Table in sheet
Can you please help capture the color in the sheet and copy to HTML email body? Many thanks.
Please find the code as below.

 function last_row(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet 1");
  var data = ss.getRange(1,1,100).getValues();
  var lrow = 0;
  for (i in data){
    var row = data[i];
    if(row[0] != ""){
    lrow++;
    }
   }

function match(){
 var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Match');
  var match = ss.getRange(1,1,19,3).getValues();

function email_to_mgmt(){

  var ss = SpreadsheetApp.getActive().getSheetByName('sheet 1');
  var lastrow = last_row();
  var data = ss.getRange(1,1,lastrow,9).getValues();
  var s = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Match');
  var match = s.getRange(1,1,19,3).getValues();

  var headers = ss.getRange("A1:H1").getValues();
  var pgm_name = headers[0][0];
  var bug_id = headers[0][1];
  var rb_bug_reporter = headers[0][2];
  var rb_bug_yq = headers[0][3];
  var rb_approved_amount = headers[0][4];
  var total_po_spend = headers[0][5];
  var rb_unilization = headers[0][6];
  var scpm_cms = headers[0][7];

  var tableRange = ss.getRange(2,1,lastrow-1,8)
  var tableRangeValues = tableRange.getDisplayValues();
  var colors = tableRange.getBackgrounds().map(([a]) =>a);

  var htmlTemplate = HtmlService.createTemplateFromFile("email");
  htmlTemplate.pgm_name = pgm_name;
  htmlTemplate.bug_id = bug_id;
  htmlTemplate.rb_bug_reporter = rb_bug_reporter;
  htmlTemplate.rb_bug_yq = rb_bug_yq;
  htmlTemplate.rb_approved_amount = rb_approved_amount;
  htmlTemplate.total_po_spend = total_po_spend;
  htmlTemplate.rb_unilization = rb_unilization;
  htmlTemplate.scpm_cms = scpm_cms;

<!DOCTYPE html>

    <base target="_top">

Headerxxx

The following....

        <?= pgm_name ?>	<?= bug_id ?>	<?= rb_bug_reporter ?>	<?= rb_bug_yq ?>	<?= rb_approved_amount ?>	<?= total_po_spend ?>	<?= rb_unilization ?>	<?= scpm_cms ?>

     <? tableRangeValues.forEach((r,i)=>{ ?>
      <tr style="background-color: <?= colors[i]?>">
         <?= r[0] ?>
         <?= r[1] ?>
         <?= r[2] ?>
         <?= r[3] ?>
         <?= r[4] ?>
         <?= r[5] ?>
         <?= r[6] ?>
         <?= r[7] ?>

      <?})?>

htmlTemplate.colors = colors;
  htmlTemplate.tableRange = tableRange;
  htmlTemplate.tableRangeValues = tableRangeValues;

  var htmlForEmail = htmlTemplate.evaluate().getContent();

  var week = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Match").getRange(1,6).getValue();

  MailApp.sendEmail({
    to: "xxx@gmail.com",
    subject:xxx,
    htmlBody: htmlForEmail});
}

A: I believe your goal as follows.

*

*You want to set the background color of the column "G" in the HTML data. The color information is from sheet 1 sheet in the Spreadsheet.

In this case, how about the following modified script?
Modified script:
Google Apps Script side:
function email_to_mgmt() {
  var sheet = SpreadsheetApp.getActive().getSheetByName("sheet 1");
  var range = sheet.getRange("A1:H" + sheet.getLastRow());
  var [[pgm_name, bug_id, rb_bug_reporter, rb_bug_yq, rb_approved_amount, total_po_spend, rb_unilization, scpm_cms], ...tableRangeValues] = range.getDisplayValues();
  var [, ...colors] = range.getBackgrounds().map(e => e[6]);
  var htmlTemplate = HtmlService.createTemplateFromFile("email");
  var obj = {pgm_name, bug_id, rb_bug_reporter, rb_bug_yq, rb_approved_amount, total_po_spend, rb_unilization, scpm_cms, tableRangeValues, colors};
  htmlTemplate.obj = obj;
  var htmlForEmail = htmlTemplate.evaluate().getContent();
  MailApp.sendEmail({ to: "xxx@gmail.com", subject: xxx, htmlBody: htmlForEmail });
}

*

*I thought that the header row and the value rows can be retrieved by one call.

*I thought that when an object is used for sending to HTML template, the script might be simpler.

HTML side:
<!DOCTYPE html>

    <base target="_top">

Headerxxx

The following....

        <?= obj.pgm_name ?>	<?= obj.bug_id ?>	<?= obj.rb_bug_reporter ?>	<?= obj.rb_bug_yq ?>	<?= obj.rb_approved_amount ?>	<?= obj.total_po_spend ?>	<?= obj.rb_unilization ?>	<?= obj.scpm_cms ?>

     <? obj.tableRangeValues.forEach((r,i)=>{ ?>

         <?= r[0] ?>
         <?= r[1] ?>
         <?= r[2] ?>
         <?= r[3] ?>
         <?= r[4] ?>
         <?= r[5] ?>
        <td style="background-color: <?= obj.colors[i]?>"> <?= r[6] ?>
         <?= r[7] ?>

      <?})?>

*

*When you want to change the background color of cell of column "G", please add the style to the tag td.

References:

*

*Destructuring assignment

*Spread syntax


text:
Q: Git push halts on "Writing Objects: 100%" I have set up a linux box with a Git repository (using xinetd).
I have enabled receive-pack for the git daemon to enable pushing to the repository.
Here's my current testing workflow:

*

*On git server, run:

mkdir something
cd something
git init --bare

*

*On a client box:

git clone git://server/repo
(msg about cloning an empty repository)

*

*Perform some commits to the cloned repository.

*git push
getting this msg:
Counting objects: 8, done.
Compressing objects: 100% (3/3) done,
Writing objects: 100% (6/6)

This does not finish. I have introduced only a small change, so this should be completed very quickly.
am i doing something wrong here?

A: If you are using msysgit - they have just released a version that allows a config option to stop git hanging.
Fix is for https://github.com/msysgit/git/issues/101 in release https://github.com/msysgit/msysgit/releases/tag/Git-1.9.4-preview20140611
You can fix it by setting
git config --global sendpack.sideband false

A: The issue is with mgitsys client
Read more here: MGitsys Bug
As a workaround, i am using an older version: git version 1.7.4.rc1.3197.gbf965
This one doesn't have this bug in it.
I have placed this specific build in my SkyDrive public folder, link: http://sdrv.ms/MeuWTD
Hopefully it will be fixed in the near future.


text:
Q: how to remove sql developer - 21.2.1.204.1703 on ubuntu 20.04 i installed sqldeveloper-21.2.1.204.1703-no-jre.zip
and now i cant remove it
i tried using sudo apt remove sqldeveloper
this error come up :E: Unable to locate package sqldeveloper

A: Following @Rinzwind 's comment on your question, this did the job for me:
sudo find / -name "*sqldeveloper*" -type d -exec rm -vR {} \;

You can even do it in two steps if you wanna make sure you're not deleting folders you might need (e.g university folders, ...) :

*

*step 1: sudo find / -name "*sqldeveloper*" -type d
This allows you to see all of the folders with the name "sqldeveloper" in it, you can even precise how deep should the find command search using -maxdepth N where N is the maximum level of depth it will go to (exp: 3).

*

*step 2: Remove them one by one manually using :

rm -vR /the_path_of_the_folder_to_remove

apt remove sqldeveloper

does not work because sqldeveloper is installed by being unzipped, and not using apt-get install .


text:
Q: Is use of `make` meaningful when using VS Code? When using VS Code what you can do with make can be done with tasks.json as well and make is not preinstalled on Windows. If you can force your team which uses various OS to use VS Code, is there any reason to use make?

A: On the surface, you can use either Makefiles or tasks.json to execute various shell scripts. With the property dependsOn of tasks.json, you can do a topological sort of tasks that Makefile also does.
There are still things that make does better than tasks.json:

*

*make can check timestamps of files to find which files are outdated and which tasks it doesn't need to execute. Maybe you can do that using various shell scripts in tasks.json, but using Makefiles would be far more convenient. For very big projects with a lot of source code, this is a very great feature since you can save a lot of time instead of re-building 100s of files you didn't need to.

*make contains an interface engine, supporting suffix rules and support for wildcards. I don't think tasks.json support that. You can probably use some extra shell scripts to achieve the same, but it won't be as neat as how make does it.

*Finally, Makefiles can be run in any system that has make, and therefore it is independent of VS Code.
If you're working on a small/simple enough project, you can absolutely work on it without using make. For large projects, make is the sensible choice.
In my college project, we are using Makefiles. We work on VS Code so we set the tasks.json scripts to just use make commands with the said Makefile. You can do that as well if you like.


text:
Q: C++ throw dereferenced pointer What is the type of the exception object in the following thrown:
Question1> range_error r("error"); throw r;
Answer1>   an object of range_error
Question2> exception *p = &r; throw *p;
Answer2>   a sliced object of exception
Question3> exception *p = &r; throw p;
Answer3>   a pointer pointing to range_error is thrown. The capture-handling can access the range_error member functions through dynamic binding.
Do I get these question right?
// Updated and Compiled and Run on VS2010
#include <iostream>
using namespace std;

class ExClassA
{
public:
    virtual void PrintMe() const
    {
        cout << "ExClassA" << endl;
    }
};

class ExClassB : public ExClassA
{
public:
    virtual void PrintMe() const
    {
        cout << "ExClassB" << endl;
    }
};

int main(int argc, char* argv[])
{
    ExClassB exClassB;
    ExClassA *p = &exClassB;

    try
    {
        throw *p;
    }
    catch (const ExClassA& e)
    {
        e.PrintMe();
    }

    try
    {
        throw p;
    }
    catch (const ExClassA* e)
    {
        e->PrintMe();
    }
}

The first try-catch of above program prints "ExClassA"
The second try-catch of above program prints "ExClassB"

A: Throwing an object always results in the thrown object being a copy of the object you threw, based on the static type of that object. Thus your first two answers are correct.
The third one is a little more complicated. If you catch(range_error*) you won't catch the exception because the types don't match. If you catch(exception*) you won't be able to access members of range_error in the caught pointer; you can dynamic_cast that pointer back to a range_error pointer though.

A: I think you are right in all three. The type of the thrown object (IIRC) is the static type of the object being thrown. I would have to dig into the standard for a while to find the exact quotes, but a simple example seems to confirm this:
struct base {};
struct derived : base {};
void t() {
    derived d;
    base * b = &d;
    throw *b;
}
int main() {
    try {
        t();
    } catch ( derived const & ) {
        std::cout << "derived" << std::endl;
    } catch ( base const & ) {
        std::cout << "base" << std::endl;
    }
}

If the dynamic type of the object being thrown was used, then *b would have type derived and the first catch would succeed, but empirically the second catch is executed (g++).
In the last case, the object thrown is a pointer to exception that refers to a range_error object. The slight difference is again what can be caught, the compiler will not catch in a catch (range_error*) block. The answer is correct, but I would have specified the type of the pointer, as much as the type of the pointee. (The type of the pointer is somehow implicit in the answer)

A: All three answers are correct.  Just note that you'll have to catch a
pointer type in the third case.
The usual way to throw an exception is:
throw range_error("error");

At the throw site, you normally know the exact type of exception you
want to throw.  About the only exception I can think of is when the
exception was passed in as an argument, e.g.:
void f( std::exception const& whatToDoInCaseOfError )
{
    //  ...
    throw whatToDoInCaseOfError;  //  slices
}

It's not a frequence case, but if you want to support it, you'll need a
separate exception hierarchy of your own, with a virtual raise
function:
class MyExceptions
{
public:
    virtual ~MyExceptions() {}
    virtual void raise() const = 0;
};

template<typename ExceptionType>
class ConcreteException : public ExceptionType, public MyExceptions
{
public:
    virtual void raise() const
    {
        throw *this;
    }
};

The client code then wraps the exception he wants to be thrown in a
ConcreteException, and you call the raise function on it, rather
than invoke throw directly.


text:
Q: Remove optional parameter in POST body Retrofit I have a situation where in a web service call is made from two separate situations. The post body has 2 optional parameters. The two parameters needs to be present in one situation and in the other situation it should not be present.
Example:-
Situation 1 Post Body:-
{
    "parameter1" : "data1",
    "parameter2" : "data2",
    "parameter3" : "data3",
    "parameter4" : "data4"
}

Situation 2 Post Body:-
{
    "parameter1" : "data1",
    "parameter2" : "data2",
    "parameter3" : "data3",
    "parameter4" : "data4",
    "parameter5" : "data5",
    "parameter6" : "data6"
}

How do I achieve this using retrofit and Jackson?

A: The Object you use to model your POST body should be annotated with
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
above the class declaration and then from there just leave
 "parameter5" : "data5",
 "parameter6" : "data6"

null, they should not be serialized.


text:
Q: Have contents of email have been changed in transit? A colleague of mine received some bank details in an unsecured email from a company. He used the details in the email to pay a sum of money into an account.
The company that sent him the email to him didn't receive the money. The bank account details in the email that he received were different to the ones sent by the company.
Does this sound plausible? Is this the sort of thing that happens? If this has actually happened as described then where would the point of attack be?

*

*Has my colleague's PC been hacked?

*Has the companies network been hacked?

*Has somebody intercepted the email and changed the details en-route?

What's the most likely scenario?

A: This is plausible.
This is an attack that could conceivably be performed by anyone who simply knew that your colleague and the company had a business relationship.  They could simply send an email pretending to be from the company, but substitute their own payment information instead.  It is something that happens with some frequency.
It is possible that your colleague's email has been compromised.  That would give the thief access to a typical email from the company that they could base their fraud on.  Not required, but it could simplify their job.
I think it is unlikely that someone altered this email in-transit.  That's typically inconvenient (far from impossible; just inconvenient) when compared to the two approaches above.
Your colleague should report the issue to their IT security team (if any), and then probably their bank and their insurance company.

A: This is not an email that has been intercepted in transit. Emails are effectively inert, an email recipient can only be compromised if they click something in the email.
However, this looks like the recipient (your colleague) was socially engineered and then sent an email from someone trying to exploit his bank account. The attacker must have somehow known that your colleague expected to get an email from the company or that he was likely to pay into the account.
The recipient should check the details of where the email came from in the headers of the email. How best to do this depends on the email client used. However, headers can be forged so the 'from' may look legitimate. Check for IP addresses (see the aside below).
Steps to take:

*

*Contact the bank to stop any payments

*Contact the company who he expected the payment was from to advise them that their systems may have been compromised which led to his details being leaked (if applicable).

*Report the infringement / fraud (he will need to check who to report this to in his country).

*Check the email headers and black list the originator if possible.

Aside
If you want to trace the email address, this may help: https://whatismyipaddress.com/trace-email